diff --git a/.DS_Store b/.DS_Store index f4f05c716..3ccbdbaa5 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/.cursor/rules/README.md b/.cursor/rules/README.md new file mode 100644 index 000000000..31959fe73 --- /dev/null +++ b/.cursor/rules/README.md @@ -0,0 +1,107 @@ +# Evolution API Cursor Rules + +Este diretório contém as regras e configurações do Cursor IDE para o projeto Evolution API. + +## Estrutura dos Arquivos + +### Arquivos Principais (alwaysApply: true) +- **`core-development.mdc`** - Princípios fundamentais de desenvolvimento +- **`project-context.mdc`** - Contexto específico do projeto Evolution API +- **`cursor.json`** - Configurações do Cursor IDE + +### Regras Especializadas (alwaysApply: false) +Estas regras são ativadas automaticamente quando você trabalha nos arquivos correspondentes: + +#### Camadas da Aplicação +- **`specialized-rules/service-rules.mdc`** - Padrões para services (`src/api/services/`) +- **`specialized-rules/controller-rules.mdc`** - Padrões para controllers (`src/api/controllers/`) +- **`specialized-rules/dto-rules.mdc`** - Padrões para DTOs (`src/api/dto/`) +- **`specialized-rules/guard-rules.mdc`** - Padrões para guards (`src/api/guards/`) +- **`specialized-rules/route-rules.mdc`** - Padrões para routers (`src/api/routes/`) + +#### Tipos e Validação +- **`specialized-rules/type-rules.mdc`** - Definições TypeScript (`src/api/types/`) +- **`specialized-rules/validate-rules.mdc`** - Schemas de validação (`src/validate/`) + +#### Utilitários +- **`specialized-rules/util-rules.mdc`** - Funções utilitárias (`src/utils/`) + +#### Integrações +- **`specialized-rules/integration-channel-rules.mdc`** - Integrações de canal (`src/api/integrations/channel/`) +- **`specialized-rules/integration-chatbot-rules.mdc`** - Integrações de chatbot (`src/api/integrations/chatbot/`) +- **`specialized-rules/integration-storage-rules.mdc`** - Integrações de storage (`src/api/integrations/storage/`) +- **`specialized-rules/integration-event-rules.mdc`** - Integrações de eventos (`src/api/integrations/event/`) + +## Como Usar + +### Referências Cruzadas +Os arquivos principais fazem referência aos especializados usando a sintaxe `@specialized-rules/nome-do-arquivo.mdc`. Quando você trabalha em um arquivo específico, o Cursor automaticamente carrega as regras relevantes. + +### Exemplo de Uso +Quando você edita um arquivo em `src/api/services/`, o Cursor automaticamente: +1. Carrega `core-development.mdc` (sempre ativo) +2. Carrega `project-context.mdc` (sempre ativo) +3. Carrega `specialized-rules/service-rules.mdc` (ativado pelo glob pattern) + +### Padrões de Código +Cada arquivo de regras contém: +- **Estruturas padrão** - Como organizar o código +- **Padrões de nomenclatura** - Convenções de nomes +- **Exemplos práticos** - Código de exemplo +- **Anti-padrões** - O que evitar +- **Testes** - Como testar o código +- **Padrões de Commit** - Conventional Commits com commitlint + +## Configuração do Cursor + +O arquivo `cursor.json` contém: +- Configurações de formatação +- Padrões de código específicos do Evolution API +- Diretórios principais do projeto +- Integrações e tecnologias utilizadas + +## Manutenção + +Para manter as regras atualizadas: +1. Analise novos padrões no código +2. Atualize as regras especializadas correspondentes +3. Mantenha os exemplos sincronizados com o código real +4. Documente mudanças significativas + +## Tecnologias Cobertas + +- **Backend**: Node.js 20+ + TypeScript 5+ + Express.js +- **Database**: Prisma ORM (PostgreSQL/MySQL) +- **Cache**: Redis + Node-cache +- **Queue**: RabbitMQ + Amazon SQS +- **Real-time**: Socket.io +- **Storage**: AWS S3 + Minio +- **Validation**: JSONSchema7 +- **Logging**: Pino +- **WhatsApp**: Baileys + Meta Business API +- **Integrations**: Chatwoot, Typebot, OpenAI, Dify + +## Estrutura do Projeto + +``` +src/ +├── api/ +│ ├── controllers/ # Controllers (HTTP handlers) +│ ├── services/ # Business logic +│ ├── dto/ # Data Transfer Objects +│ ├── guards/ # Authentication/Authorization +│ ├── routes/ # Express routers +│ ├── types/ # TypeScript definitions +│ └── integrations/ # External integrations +│ ├── channel/ # WhatsApp channels (Baileys, Business API) +│ ├── chatbot/ # Chatbot integrations +│ ├── event/ # Event integrations +│ └── storage/ # Storage integrations +├── cache/ # Cache implementations +├── config/ # Configuration files +├── utils/ # Utility functions +├── validate/ # Validation schemas +└── exceptions/ # Custom exceptions +``` + +Este sistema de regras garante consistência no código e facilita o desenvolvimento seguindo os padrões estabelecidos do Evolution API. diff --git a/.cursor/rules/core-development.mdc b/.cursor/rules/core-development.mdc new file mode 100644 index 000000000..530385795 --- /dev/null +++ b/.cursor/rules/core-development.mdc @@ -0,0 +1,167 @@ +--- +description: Core development principles and standards for Evolution API development +globs: +alwaysApply: true +--- + +# Evolution API Development Standards + +## Cross-References +- **Project Context**: @project-context.mdc for Evolution API-specific patterns +- **Specialized Rules**: + - @specialized-rules/service-rules.mdc for service layer patterns + - @specialized-rules/controller-rules.mdc for controller patterns + - @specialized-rules/dto-rules.mdc for DTO validation patterns + - @specialized-rules/guard-rules.mdc for authentication/authorization + - @specialized-rules/route-rules.mdc for router patterns + - @specialized-rules/type-rules.mdc for TypeScript definitions + - @specialized-rules/util-rules.mdc for utility functions + - @specialized-rules/validate-rules.mdc for validation schemas + - @specialized-rules/integration-channel-rules.mdc for channel integrations + - @specialized-rules/integration-chatbot-rules.mdc for chatbot integrations + - @specialized-rules/integration-storage-rules.mdc for storage integrations + - @specialized-rules/integration-event-rules.mdc for event integrations +- **TypeScript/Node.js**: Node.js 20+ + TypeScript 5+ best practices +- **Express/Prisma**: Express.js + Prisma ORM patterns +- **WhatsApp Integrations**: Baileys + Meta Business API patterns + +## Senior Engineer Context - Evolution API Platform +- You are a senior software engineer working on a WhatsApp API platform +- Focus on Node.js + TypeScript + Express.js full-stack development +- Specialized in real-time messaging, WhatsApp integrations, and event-driven architecture +- Apply scalable patterns for multi-tenant API platform +- Consider WhatsApp integration workflow implications and performance at scale + +## Fundamental Principles + +### Code Quality Standards +- **Simplicity First**: Always prefer simple solutions over complex ones +- **DRY Principle**: Avoid code duplication - check for existing similar functionality before implementing +- **Single Responsibility**: Each function/class should have one clear purpose +- **Readable Code**: Write code that tells a story - clear naming and structure + +### Problem Resolution Approach +- **Follow Existing Patterns**: Use established Service patterns, DTOs, and Integration patterns +- **Event-Driven First**: Leverage EventEmitter2 for event publishing when adding new features +- **Integration Pattern**: Follow existing WhatsApp integration patterns for new channels +- **Conservative Changes**: Prefer extending existing services over creating new architecture +- **Clean Migration**: Remove deprecated patterns when introducing new ones +- **Incremental Changes**: Break large changes into smaller, testable increments with proper migrations + +### File and Function Organization - Node.js/TypeScript Structure +- **Services**: Keep services focused and under 200 lines +- **Controllers**: Keep controllers thin - only routing and validation +- **DTOs**: Use JSONSchema7 for all input validation +- **Integrations**: Follow `src/api/integrations/` structure for new integrations +- **Utils**: Extract common functionality into well-named utilities +- **Types**: Define clear TypeScript interfaces and types + +### Code Analysis and Reflection +- After writing code, deeply reflect on scalability and maintainability +- Provide 1-2 paragraph analysis of code changes +- Suggest improvements or next steps based on reflection +- Consider performance, security, and maintenance implications + +## Development Standards + +### TypeScript Standards +- **Strict Mode**: Always use TypeScript strict mode +- **No Any**: Avoid `any` type - use proper typing +- **Interfaces**: Define clear contracts with interfaces +- **Enums**: Use enums for constants and status values +- **Generics**: Use generics for reusable components + +### Error Handling Standards +- **HTTP Exceptions**: Use appropriate HTTP status codes +- **Logging**: Structured logging with context +- **Retry Logic**: Implement retry for external services +- **Graceful Degradation**: Handle service failures gracefully + +### Security Standards +- **Input Validation**: Validate all inputs with JSONSchema7 +- **Authentication**: Use API keys and JWT tokens +- **Rate Limiting**: Implement rate limiting for APIs +- **Data Sanitization**: Sanitize sensitive data in logs + +### Performance Standards +- **Caching**: Use Redis for frequently accessed data +- **Database**: Optimize Prisma queries with proper indexing +- **Memory**: Monitor memory usage and implement cleanup +- **Async**: Use async/await properly with error handling + +## Communication Standards + +### Language Requirements +- **User Communication**: Always respond in Portuguese (PT-BR) +- **Code Comments**: English for technical documentation +- **API Documentation**: English for consistency +- **Error Messages**: Portuguese for user-facing errors + +### Documentation Standards +- **Code Comments**: Document complex business logic +- **API Documentation**: Document all public endpoints +- **README**: Keep project documentation updated +- **Changelog**: Document breaking changes + +## Quality Assurance + +### Testing Standards +- **Unit Tests**: Test business logic in services +- **Integration Tests**: Test API endpoints +- **Mocks**: Mock external dependencies +- **Coverage**: Aim for 70%+ test coverage + +### Code Review Standards +- **Peer Review**: All code must be reviewed +- **Automated Checks**: ESLint, Prettier, TypeScript +- **Security Review**: Check for security vulnerabilities +- **Performance Review**: Check for performance issues + +### Commit Standards (Conventional Commits) +- **Format**: `type(scope): subject` (max 100 characters) +- **Types**: + - `feat` - New feature + - `fix` - Bug fix + - `docs` - Documentation changes + - `style` - Code style changes (formatting, etc) + - `refactor` - Code refactoring + - `perf` - Performance improvements + - `test` - Adding or updating tests + - `chore` - Maintenance tasks + - `ci` - CI/CD changes + - `build` - Build system changes + - `revert` - Reverting changes + - `security` - Security fixes +- **Examples**: + - `feat(api): add WhatsApp message status endpoint` + - `fix(baileys): resolve connection timeout issue` + - `docs(readme): update installation instructions` + - `refactor(service): extract common message validation logic` +- **Tools**: Use `npm run commit` (Commitizen) for guided commits +- **Validation**: Enforced by commitlint on commit-msg hook + +## Evolution API Specific Patterns + +### WhatsApp Integration Patterns +- **Connection Management**: One connection per instance +- **Event Handling**: Proper event listeners for Baileys +- **Message Processing**: Queue-based message processing +- **Error Recovery**: Automatic reconnection logic + +### Multi-Database Support +- **Schema Compatibility**: Support PostgreSQL and MySQL +- **Migration Sync**: Keep migrations synchronized +- **Type Safety**: Use Prisma generated types +- **Connection Pooling**: Proper database connection management + +### Cache Strategy +- **Redis Primary**: Use Redis for distributed caching +- **Local Fallback**: Node-cache for local fallback +- **TTL Strategy**: Appropriate TTL for different data types +- **Cache Invalidation**: Proper cache invalidation patterns + +### Event System +- **EventEmitter2**: Use for internal events +- **WebSocket**: Socket.io for real-time updates +- **Queue Systems**: RabbitMQ/SQS for async processing +- **Webhook Processing**: Proper webhook validation and processing \ No newline at end of file diff --git a/.cursor/rules/cursor.json b/.cursor/rules/cursor.json new file mode 100644 index 000000000..a3d4275f1 --- /dev/null +++ b/.cursor/rules/cursor.json @@ -0,0 +1,179 @@ +{ + "version": "1.0", + "description": "Cursor IDE configuration for Evolution API project", + "rules": { + "general": { + "max_line_length": 120, + "indent_size": 2, + "end_of_line": "lf", + "charset": "utf-8", + "trim_trailing_whitespace": true, + "insert_final_newline": true + }, + "typescript": { + "quotes": "single", + "semi": true, + "trailing_comma": "es5", + "bracket_spacing": true, + "arrow_parens": "avoid", + "print_width": 120, + "tab_width": 2, + "use_tabs": false, + "single_quote": true, + "end_of_line": "lf", + "strict": true, + "no_implicit_any": true, + "strict_null_checks": true + }, + "javascript": { + "quotes": "single", + "semi": true, + "trailing_comma": "es5", + "bracket_spacing": true, + "arrow_parens": "avoid", + "print_width": 120, + "tab_width": 2, + "use_tabs": false, + "single_quote": true, + "end_of_line": "lf", + "style_guide": "eslint-airbnb" + }, + "json": { + "tab_width": 2, + "use_tabs": false, + "parser": "json" + }, + "ignore": { + "files": [ + "node_modules/**", + "dist/**", + "build/**", + ".git/**", + "*.min.js", + "*.min.css", + ".env", + ".env.*", + ".env.example", + "coverage/**", + "*.log", + "*.lock", + "pnpm-lock.yaml", + "package-lock.json", + "yarn.lock", + "log/**", + "tmp/**", + "instances/**", + "public/uploads/**", + "*.dump", + "*.rdb", + "*.mmdb", + ".DS_Store", + "*.swp", + "*.swo", + "*.un~", + ".jest-cache", + ".idea/**", + ".vscode/**", + ".yalc/**", + "yalc.lock", + "*.local", + "prisma/migrations/**", + "prisma/mysql-migrations/**", + "prisma/postgresql-migrations/**" + ] + }, + "search": { + "exclude_patterns": [ + "**/node_modules/**", + "**/dist/**", + "**/build/**", + "**/.git/**", + "**/coverage/**", + "**/log/**", + "**/tmp/**", + "**/instances/**", + "**/public/uploads/**", + "**/*.min.js", + "**/*.min.css", + "**/*.log", + "**/*.lock", + "**/pnpm-lock.yaml", + "**/package-lock.json", + "**/yarn.lock", + "**/*.dump", + "**/*.rdb", + "**/*.mmdb", + "**/.DS_Store", + "**/*.swp", + "**/*.swo", + "**/*.un~", + "**/.jest-cache", + "**/.idea/**", + "**/.vscode/**", + "**/.yalc/**", + "**/yalc.lock", + "**/*.local", + "**/prisma/migrations/**", + "**/prisma/mysql-migrations/**", + "**/prisma/postgresql-migrations/**" + ] + }, + "evolution_api": { + "project_type": "nodejs_typescript_api", + "backend_framework": "express_prisma", + "database": ["postgresql", "mysql"], + "cache": ["redis", "node_cache"], + "queue": ["rabbitmq", "sqs"], + "real_time": "socket_io", + "file_storage": ["aws_s3", "minio"], + "validation": "class_validator", + "logging": "pino", + "main_directories": { + "source": "src/", + "api": "src/api/", + "controllers": "src/api/controllers/", + "services": "src/api/services/", + "integrations": "src/api/integrations/", + "dto": "src/api/dto/", + "types": "src/api/types/", + "guards": "src/api/guards/", + "routes": "src/api/routes/", + "cache": "src/cache/", + "config": "src/config/", + "utils": "src/utils/", + "exceptions": "src/exceptions/", + "validate": "src/validate/", + "prisma": "prisma/", + "tests": "test/", + "docs": "docs/" + }, + "key_patterns": [ + "whatsapp_integration", + "multi_database_support", + "instance_management", + "event_driven_architecture", + "service_layer_pattern", + "dto_validation", + "webhook_processing", + "message_queuing", + "real_time_communication", + "file_storage_integration" + ], + "whatsapp_integrations": [ + "baileys", + "meta_business_api", + "whatsapp_cloud_api" + ], + "external_integrations": [ + "chatwoot", + "typebot", + "openai", + "dify", + "rabbitmq", + "sqs", + "s3", + "minio" + ] + } + } +} diff --git a/.cursor/rules/project-context.mdc b/.cursor/rules/project-context.mdc new file mode 100644 index 000000000..0a4da37e7 --- /dev/null +++ b/.cursor/rules/project-context.mdc @@ -0,0 +1,174 @@ +--- +description: Evolution API project-specific context and constraints +globs: +alwaysApply: true +--- + +# Evolution API Project Context + +## Cross-References +- **Core Development**: @core-development.mdc for fundamental development principles +- **Specialized Rules**: Reference specific specialized rules when working on: + - Services: @specialized-rules/service-rules.mdc + - Controllers: @specialized-rules/controller-rules.mdc + - DTOs: @specialized-rules/dto-rules.mdc + - Guards: @specialized-rules/guard-rules.mdc + - Routes: @specialized-rules/route-rules.mdc + - Types: @specialized-rules/type-rules.mdc + - Utils: @specialized-rules/util-rules.mdc + - Validation: @specialized-rules/validate-rules.mdc + - Channel Integrations: @specialized-rules/integration-channel-rules.mdc + - Chatbot Integrations: @specialized-rules/integration-chatbot-rules.mdc + - Storage Integrations: @specialized-rules/integration-storage-rules.mdc + - Event Integrations: @specialized-rules/integration-event-rules.mdc +- **TypeScript/Node.js**: Node.js 20+ + TypeScript 5+ backend standards +- **Express/Prisma**: Express.js + Prisma ORM patterns +- **WhatsApp Integrations**: Baileys, Meta Business API, and other messaging platforms + +## Technology Stack +- **Backend**: Node.js 20+ + TypeScript 5+ + Express.js +- **Database**: Prisma ORM (PostgreSQL/MySQL support) +- **Cache**: Redis + Node-cache for local fallback +- **Queue**: RabbitMQ + Amazon SQS for message processing +- **Real-time**: Socket.io for WebSocket connections +- **Storage**: AWS S3 + Minio for file storage +- **Validation**: JSONSchema7 for input validation +- **Logging**: Pino for structured logging +- **Architecture**: Multi-tenant API with WhatsApp integrations + +## Project-Specific Patterns + +### WhatsApp Integration Architecture +- **MANDATORY**: All WhatsApp integrations must follow established patterns +- **BAILEYS**: Use `whatsapp.baileys.service.ts` patterns for WhatsApp Web +- **META BUSINESS**: Use `whatsapp.business.service.ts` for official API +- **CONNECTION MANAGEMENT**: One connection per instance with proper lifecycle +- **EVENT HANDLING**: Proper event listeners and error handling + +### Multi-Database Architecture +- **CRITICAL**: Support both PostgreSQL and MySQL +- **SCHEMAS**: Use appropriate schema files (postgresql-schema.prisma / mysql-schema.prisma) +- **MIGRATIONS**: Keep migrations synchronized between databases +- **TYPES**: Use database-specific types (@db.JsonB vs @db.Json) +- **COMPATIBILITY**: Ensure feature parity between databases + +### API Integration Workflow +- **CORE FEATURE**: REST API for WhatsApp communication +- **COMPLEXITY**: High - involves webhook processing, message routing, and instance management +- **COMPONENTS**: Instance management, message handling, media processing +- **INTEGRATIONS**: Baileys, Meta Business API, Chatwoot, Typebot, OpenAI, Dify + +### Multi-Tenant Instance Architecture +- **CRITICAL**: All operations must be scoped by instance +- **ISOLATION**: Complete data isolation between instances +- **SECURITY**: Validate instance ownership before operations +- **SCALING**: Support thousands of concurrent instances +- **AUTHENTICATION**: API key-based authentication per instance + +## Documentation Requirements + +### Implementation Documentation +- **MANDATORY**: Document complex integration patterns +- **LOCATION**: Use inline comments for business logic +- **API DOCS**: Document all public endpoints +- **WEBHOOK DOCS**: Document webhook payloads and signatures + +### Change Documentation +- **CHANGELOG**: Document breaking changes +- **MIGRATION GUIDES**: Document database migrations +- **INTEGRATION GUIDES**: Document new integration patterns + +## Environment and Security + +### Environment Variables +- **CRITICAL**: Never hardcode sensitive values +- **VALIDATION**: Validate required environment variables on startup +- **SECURITY**: Use secure defaults and proper encryption +- **DOCUMENTATION**: Document all environment variables + +### File Organization - Node.js/TypeScript Structure +- **CONTROLLERS**: Organized by feature (`api/controllers/`) +- **SERVICES**: Business logic in service classes (`api/services/`) +- **INTEGRATIONS**: External integrations (`api/integrations/`) +- **DTOS**: Data transfer objects (`api/dto/`) +- **TYPES**: TypeScript types (`api/types/`) +- **UTILS**: Utility functions (`utils/`) + +## Integration Points + +### WhatsApp Providers +- **BAILEYS**: WhatsApp Web integration with QR code +- **META BUSINESS**: Official WhatsApp Business API +- **CLOUD API**: WhatsApp Cloud API integration +- **WEBHOOK PROCESSING**: Proper webhook validation and processing + +### External Integrations +- **CHATWOOT**: Customer support platform integration +- **TYPEBOT**: Chatbot flow integration +- **OPENAI**: AI-powered chat integration +- **DIFY**: AI workflow integration +- **STORAGE**: S3/Minio for media file storage + +### Event-Driven Communication +- **EVENTEMITTER2**: Internal event system +- **SOCKET.IO**: Real-time WebSocket communication +- **RABBITMQ**: Message queue for async processing +- **SQS**: Amazon SQS for cloud-based queuing +- **WEBHOOKS**: Outbound webhook system + +## Development Constraints + +### Language Requirements +- **USER COMMUNICATION**: Always respond in Portuguese (PT-BR) +- **CODE/COMMENTS**: English for code and technical documentation +- **API RESPONSES**: English for consistency +- **ERROR MESSAGES**: Portuguese for user-facing errors + +### Performance Constraints +- **MEMORY**: Efficient memory usage for multiple instances +- **DATABASE**: Optimized queries with proper indexing +- **CACHE**: Strategic caching for frequently accessed data +- **CONNECTIONS**: Proper connection pooling and management + +### Security Constraints +- **AUTHENTICATION**: API key validation for all endpoints +- **AUTHORIZATION**: Instance-based access control +- **INPUT VALIDATION**: Validate all inputs with JSONSchema7 +- **RATE LIMITING**: Prevent abuse with rate limiting +- **WEBHOOK SECURITY**: Validate webhook signatures + +## Quality Standards +- **TYPE SAFETY**: Full TypeScript coverage with strict mode +- **ERROR HANDLING**: Comprehensive error scenarios with proper logging +- **TESTING**: Unit and integration tests for critical paths +- **MONITORING**: Proper logging and error tracking +- **DOCUMENTATION**: Clear API documentation and code comments +- **PERFORMANCE**: Optimized for high-throughput message processing +- **SECURITY**: Secure by default with proper validation +- **SCALABILITY**: Design for horizontal scaling + +## Evolution API Specific Development Patterns + +### Instance Management +- **LIFECYCLE**: Proper instance creation, connection, and cleanup +- **STATE MANAGEMENT**: Track connection status and health +- **RECOVERY**: Automatic reconnection and error recovery +- **MONITORING**: Health checks and status reporting + +### Message Processing +- **QUEUE-BASED**: Use queues for message processing +- **RETRY LOGIC**: Implement exponential backoff for failures +- **MEDIA HANDLING**: Proper media upload and processing +- **WEBHOOK DELIVERY**: Reliable webhook delivery with retries + +### Integration Patterns +- **SERVICE LAYER**: Business logic in service classes +- **DTO VALIDATION**: Input validation with JSONSchema7 +- **ERROR HANDLING**: Consistent error responses +- **LOGGING**: Structured logging with correlation IDs + +### Database Patterns +- **PRISMA**: Use Prisma ORM for all database operations +- **TRANSACTIONS**: Use transactions for multi-step operations +- **MIGRATIONS**: Proper migration management +- **INDEXING**: Optimize queries with appropriate indexes \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/controller-rules.mdc b/.cursor/rules/specialized-rules/controller-rules.mdc new file mode 100644 index 000000000..4e4d666a7 --- /dev/null +++ b/.cursor/rules/specialized-rules/controller-rules.mdc @@ -0,0 +1,342 @@ +--- +description: Controller patterns for Evolution API +globs: + - "src/api/controllers/**/*.ts" + - "src/api/integrations/**/controllers/*.ts" +alwaysApply: false +--- + +# Evolution API Controller Rules + +## Controller Structure Pattern + +### Standard Controller Class +```typescript +export class ExampleController { + constructor(private readonly exampleService: ExampleService) {} + + public async createExample(instance: InstanceDto, data: ExampleDto) { + return this.exampleService.create(instance, data); + } + + public async findExample(instance: InstanceDto) { + return this.exampleService.find(instance); + } +} +``` + +## Dependency Injection Pattern + +### Service Injection +```typescript +// CORRECT - Evolution API pattern +export class ChatController { + constructor(private readonly waMonitor: WAMonitoringService) {} + + public async whatsappNumber({ instanceName }: InstanceDto, data: WhatsAppNumberDto) { + return await this.waMonitor.waInstances[instanceName].getWhatsAppNumbers(data); + } +} + +// INCORRECT - Don't inject multiple services when waMonitor is sufficient +export class ChatController { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly prismaRepository: PrismaRepository, // ❌ Unnecessary if waMonitor has access + private readonly configService: ConfigService, // ❌ Unnecessary if waMonitor has access + ) {} +} +``` + +## Method Signature Pattern + +### Instance Parameter Pattern +```typescript +// CORRECT - Evolution API pattern (destructuring instanceName) +public async fetchCatalog({ instanceName }: InstanceDto, data: getCatalogDto) { + return await this.waMonitor.waInstances[instanceName].fetchCatalog(instanceName, data); +} + +// CORRECT - Alternative pattern for full instance (when using services) +public async createTemplate(instance: InstanceDto, data: TemplateDto) { + return this.templateService.create(instance, data); +} + +// INCORRECT - Don't use generic method names +public async methodName(instance: InstanceDto, data: DataDto) { // ❌ Use specific names + return this.service.performAction(instance, data); +} +``` + +## WAMonitor Access Pattern + +### Direct WAMonitor Usage +```typescript +// CORRECT - Standard pattern in controllers +export class CallController { + constructor(private readonly waMonitor: WAMonitoringService) {} + + public async offerCall({ instanceName }: InstanceDto, data: OfferCallDto) { + return await this.waMonitor.waInstances[instanceName].offerCall(data); + } +} +``` + +## Controller Registration Pattern + +### Server Module Registration +```typescript +// In server.module.ts +export const templateController = new TemplateController(templateService); +export const businessController = new BusinessController(waMonitor); +export const chatController = new ChatController(waMonitor); +export const callController = new CallController(waMonitor); +``` + +## Error Handling in Controllers + +### Let Services Handle Errors +```typescript +// CORRECT - Let service handle errors +public async fetchCatalog(instance: InstanceDto, data: getCatalogDto) { + return await this.waMonitor.waInstances[instance.instanceName].fetchCatalog(instance.instanceName, data); +} + +// INCORRECT - Don't add try-catch in controllers unless specific handling needed +public async fetchCatalog(instance: InstanceDto, data: getCatalogDto) { + try { + return await this.waMonitor.waInstances[instance.instanceName].fetchCatalog(instance.instanceName, data); + } catch (error) { + throw error; // ❌ Unnecessary try-catch + } +} +``` + +## Complex Controller Pattern + +### Instance Controller Pattern +```typescript +export class InstanceController { + constructor( + private readonly waMonitor: WAMonitoringService, + private readonly configService: ConfigService, + private readonly prismaRepository: PrismaRepository, + private readonly eventEmitter: EventEmitter2, + private readonly chatwootService: ChatwootService, + private readonly settingsService: SettingsService, + private readonly proxyService: ProxyController, + private readonly cache: CacheService, + private readonly chatwootCache: CacheService, + private readonly baileysCache: CacheService, + private readonly providerFiles: ProviderFiles, + ) {} + + private readonly logger = new Logger('InstanceController'); + + // Multiple methods handling different aspects + public async createInstance(data: InstanceDto) { + // Complex instance creation logic + } + + public async deleteInstance({ instanceName }: InstanceDto) { + // Complex instance deletion logic + } +} +``` + +## Channel Controller Pattern + +### Base Channel Controller +```typescript +export class ChannelController { + public prismaRepository: PrismaRepository; + public waMonitor: WAMonitoringService; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + } + + // Getters and setters for dependency access + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } +} +``` + +### Extended Channel Controller +```typescript +export class EvolutionController extends ChannelController implements ChannelControllerInterface { + private readonly logger = new Logger('EvolutionController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + } + + integrationEnabled: boolean; + + public async receiveWebhook(data: any) { + const numberId = data.numberId; + + if (!numberId) { + this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found'); + return; + } + + const instance = await this.prismaRepository.instance.findFirst({ + where: { number: numberId }, + }); + + if (!instance) { + this.logger.error('WebhookService -> receiveWebhook -> instance not found'); + return; + } + + await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); + + return { + status: 'success', + }; + } +} +``` + +## Chatbot Controller Pattern + +### Base Chatbot Controller +```typescript +export abstract class BaseChatbotController + extends ChatbotController + implements ChatbotControllerInterface +{ + public readonly logger: Logger; + integrationEnabled: boolean; + + // Abstract methods to be implemented + protected abstract readonly integrationName: string; + protected abstract processBot(/* parameters */): Promise; + protected abstract getFallbackBotId(settings: any): string | undefined; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + } + + // Base implementation methods + public async createBot(instance: InstanceDto, data: BotData) { + // Common bot creation logic + } +} +``` + +## Method Naming Conventions + +### Standard Method Names +- `create*()` - Create operations +- `find*()` - Find operations +- `fetch*()` - Fetch from external APIs +- `send*()` - Send operations +- `receive*()` - Receive webhook/data +- `handle*()` - Handle specific actions +- `offer*()` - Offer services (like calls) + +## Return Patterns + +### Direct Return Pattern +```typescript +// CORRECT - Direct return from service +public async createTemplate(instance: InstanceDto, data: TemplateDto) { + return this.templateService.create(instance, data); +} + +// CORRECT - Direct return from waMonitor +public async offerCall({ instanceName }: InstanceDto, data: OfferCallDto) { + return await this.waMonitor.waInstances[instanceName].offerCall(data); +} +``` + +## Controller Testing Pattern + +### Unit Test Structure +```typescript +describe('ExampleController', () => { + let controller: ExampleController; + let service: jest.Mocked; + + beforeEach(() => { + const mockService = { + create: jest.fn(), + find: jest.fn(), + }; + + controller = new ExampleController(mockService as any); + service = mockService as any; + }); + + describe('createExample', () => { + it('should call service create method', async () => { + const instance = { instanceName: 'test' }; + const data = { test: 'data' }; + const expectedResult = { success: true }; + + service.create.mockResolvedValue(expectedResult); + + const result = await controller.createExample(instance, data); + + expect(service.create).toHaveBeenCalledWith(instance, data); + expect(result).toEqual(expectedResult); + }); + }); +}); +``` + +## Interface Implementation + +### Controller Interface Pattern +```typescript +export interface ChannelControllerInterface { + integrationEnabled: boolean; +} + +export interface ChatbotControllerInterface { + integrationEnabled: boolean; + createBot(instance: InstanceDto, data: any): Promise; + findBot(instance: InstanceDto): Promise; + // ... other methods +} +``` + +## Controller Organization + +### File Naming Convention +- `*.controller.ts` - Main controllers +- `*/*.controller.ts` - Integration-specific controllers + +### Method Organization +1. Constructor +2. Public methods (alphabetical order) +3. Private methods (if any) + +### Import Organization +```typescript +// DTOs first +import { InstanceDto } from '@api/dto/instance.dto'; +import { ExampleDto } from '@api/dto/example.dto'; + +// Services +import { ExampleService } from '@api/services/example.service'; + +// Types +import { WAMonitoringService } from '@api/services/monitor.service'; +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/dto-rules.mdc b/.cursor/rules/specialized-rules/dto-rules.mdc new file mode 100644 index 000000000..b1cae17d8 --- /dev/null +++ b/.cursor/rules/specialized-rules/dto-rules.mdc @@ -0,0 +1,433 @@ +--- +description: DTO patterns and validation for Evolution API +globs: + - "src/api/dto/**/*.ts" + - "src/api/integrations/**/dto/*.ts" +alwaysApply: false +--- + +# Evolution API DTO Rules + +## DTO Structure Pattern + +### Basic DTO Class +```typescript +export class ExampleDto { + name: string; + category: string; + allowCategoryChange: boolean; + language: string; + components: any; + webhookUrl?: string; +} +``` + +## Inheritance Pattern + +### DTO Inheritance +```typescript +// CORRECT - Evolution API pattern +export class InstanceDto extends IntegrationDto { + instanceName: string; + instanceId?: string; + qrcode?: boolean; + businessId?: string; + number?: string; + integration?: string; + token?: string; + status?: string; + ownerJid?: string; + profileName?: string; + profilePicUrl?: string; + + // Settings + rejectCall?: boolean; + msgCall?: string; + groupsIgnore?: boolean; + alwaysOnline?: boolean; + readMessages?: boolean; + readStatus?: boolean; + syncFullHistory?: boolean; + wavoipToken?: string; + + // Proxy settings + proxyHost?: string; + proxyPort?: string; + proxyProtocol?: string; + proxyUsername?: string; + proxyPassword?: string; + + // Webhook configuration + webhook?: { + enabled?: boolean; + events?: string[]; + headers?: JsonValue; + url?: string; + byEvents?: boolean; + base64?: boolean; + }; + + // Chatwoot integration + chatwootAccountId?: string; + chatwootConversationPending?: boolean; + chatwootAutoCreate?: boolean; + chatwootDaysLimitImportMessages?: number; + chatwootImportContacts?: boolean; + chatwootImportMessages?: boolean; + chatwootLogo?: string; + chatwootMergeBrazilContacts?: boolean; + chatwootNameInbox?: string; + chatwootOrganization?: string; + chatwootReopenConversation?: boolean; + chatwootSignMsg?: boolean; + chatwootToken?: string; + chatwootUrl?: string; +} +``` + +## Base DTO Pattern + +### Base Chatbot DTO +```typescript +/** + * Base DTO for all chatbot integrations + * Contains common properties shared by all chatbot types + */ +export class BaseChatbotDto { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; +} + +/** + * Base settings DTO for all chatbot integrations + */ +export class BaseChatbotSettingDto { + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; +} +``` + +## Message DTO Patterns + +### Send Message DTOs +```typescript +export class Metadata { + number: string; + delay?: number; +} + +export class SendTextDto extends Metadata { + text: string; + linkPreview?: boolean; + mentionsEveryOne?: boolean; + mentioned?: string[]; +} + +export class SendListDto extends Metadata { + title: string; + description: string; + buttonText: string; + footerText?: string; + + sections: Section[]; +} + +export class ContactMessage { + fullName: string; + wuid: string; + phoneNumber: string; + organization?: string; + email?: string; + url?: string; +} + +export class SendTemplateDto extends Metadata { + name: string; + language: string; + components: any; +} +``` + +## Simple DTO Patterns + +### Basic DTOs +```typescript +export class NumberDto { + number: string; +} + +export class LabelDto { + id?: string; + name: string; + color: string; + predefinedId?: string; +} + +export class HandleLabelDto { + number: string; + labelId: string; +} + +export class ProfileNameDto { + name: string; +} + +export class WhatsAppNumberDto { + numbers: string[]; +} +``` + +## Complex DTO Patterns + +### Business DTOs +```typescript +export class getCatalogDto { + number?: string; + limit?: number; + cursor?: string; +} + +export class getCollectionsDto { + number?: string; + limit?: number; + cursor?: string; +} + +export class NumberBusiness { + number: string; + name?: string; + description?: string; + email?: string; + websites?: string[]; + latitude?: number; + longitude?: number; + address?: string; + profilehandle?: string; +} +``` + +## Settings DTO Pattern + +### Settings Configuration +```typescript +export class SettingsDto { + rejectCall?: boolean; + msgCall?: string; + groupsIgnore?: boolean; + alwaysOnline?: boolean; + readMessages?: boolean; + readStatus?: boolean; + syncFullHistory?: boolean; + wavoipToken?: string; +} + +export class ProxyDto { + host?: string; + port?: string; + protocol?: string; + username?: string; + password?: string; +} +``` + +## Presence DTO Pattern + +### WhatsApp Presence +```typescript +export class SetPresenceDto { + presence: WAPresence; +} + +export class SendPresenceDto { + number: string; + presence: WAPresence; +} +``` + +## DTO Structure (No Decorators) + +### Simple DTO Classes (Evolution API Pattern) +```typescript +// CORRECT - Evolution API pattern (no decorators) +export class ExampleDto { + name: string; + description?: string; + enabled: boolean; + items?: string[]; + timeout?: number; +} + +// INCORRECT - Don't use class-validator decorators +export class ValidatedDto { + @IsString() // ❌ Evolution API doesn't use decorators + name: string; +} +``` + +## Type Safety Patterns + +### Prisma Type Integration +```typescript +import { JsonValue } from '@prisma/client/runtime/library'; +import { WAPresence } from 'baileys'; +import { TriggerOperator, TriggerType } from '@prisma/client'; + +export class TypeSafeDto { + presence: WAPresence; + triggerType: TriggerType; + triggerOperator?: TriggerOperator; + metadata?: JsonValue; +} +``` + +## DTO Documentation + +### JSDoc Comments +```typescript +/** + * DTO for creating WhatsApp templates + * Used by Meta Business API integration + */ +export class TemplateDto { + /** Template name - must be unique */ + name: string; + + /** Template category (MARKETING, UTILITY, AUTHENTICATION) */ + category: string; + + /** Whether category can be changed after creation */ + allowCategoryChange: boolean; + + /** Language code (e.g., 'pt_BR', 'en_US') */ + language: string; + + /** Template components (header, body, footer, buttons) */ + components: any; + + /** Optional webhook URL for template status updates */ + webhookUrl?: string; +} +``` + +## DTO Naming Conventions + +### Standard Naming Patterns +- `*Dto` - Data transfer objects +- `Create*Dto` - Creation DTOs +- `Update*Dto` - Update DTOs +- `Send*Dto` - Message sending DTOs +- `Get*Dto` - Query DTOs +- `Handle*Dto` - Action DTOs + +## File Organization + +### DTO File Structure +``` +src/api/dto/ +├── instance.dto.ts # Main instance DTO +├── template.dto.ts # Template management +├── sendMessage.dto.ts # Message sending DTOs +├── chat.dto.ts # Chat operations +├── business.dto.ts # Business API DTOs +├── group.dto.ts # Group management +├── label.dto.ts # Label management +├── proxy.dto.ts # Proxy configuration +├── settings.dto.ts # Instance settings +└── call.dto.ts # Call operations +``` + +## Integration DTO Patterns + +### Chatbot Integration DTOs +```typescript +// Base for all chatbot DTOs +export class BaseChatbotDto { + enabled?: boolean; + description: string; + // ... common properties +} + +// Specific chatbot DTOs extend base +export class TypebotDto extends BaseChatbotDto { + url: string; + typebot: string; + // ... typebot-specific properties +} + +export class OpenaiDto extends BaseChatbotDto { + apiKey: string; + model: string; + // ... openai-specific properties +} +``` + +## DTO Testing Pattern + +### DTO Validation Tests +```typescript +describe('ExampleDto', () => { + it('should validate required fields', () => { + const dto = new ExampleDto(); + dto.name = 'test'; + dto.category = 'MARKETING'; + dto.allowCategoryChange = true; + dto.language = 'pt_BR'; + dto.components = {}; + + expect(dto.name).toBe('test'); + expect(dto.category).toBe('MARKETING'); + }); + + it('should handle optional fields', () => { + const dto = new ExampleDto(); + dto.name = 'test'; + dto.category = 'MARKETING'; + dto.allowCategoryChange = true; + dto.language = 'pt_BR'; + dto.components = {}; + dto.webhookUrl = 'https://example.com/webhook'; + + expect(dto.webhookUrl).toBe('https://example.com/webhook'); + }); +}); +``` + +## DTO Transformation + +### Request to DTO Mapping (Evolution API Pattern) +```typescript +// CORRECT - Evolution API uses RouterBroker dataValidate +const response = await this.dataValidate({ + request: req, + schema: exampleSchema, // JSONSchema7 + ClassRef: ExampleDto, + execute: (instance, data) => controller.method(instance, data), +}); + +// INCORRECT - Don't use class-validator +const dto = plainToClass(ExampleDto, req.body); // ❌ Not used in Evolution API +const errors = await validate(dto); // ❌ Not used in Evolution API +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/guard-rules.mdc b/.cursor/rules/specialized-rules/guard-rules.mdc new file mode 100644 index 000000000..d85215fe9 --- /dev/null +++ b/.cursor/rules/specialized-rules/guard-rules.mdc @@ -0,0 +1,416 @@ +--- +description: Guard patterns for authentication and authorization in Evolution API +globs: + - "src/api/guards/**/*.ts" +alwaysApply: false +--- + +# Evolution API Guard Rules + +## Guard Structure Pattern + +### Standard Guard Function +```typescript +import { NextFunction, Request, Response } from 'express'; +import { Logger } from '@config/logger.config'; +import { UnauthorizedException, ForbiddenException } from '@exceptions'; + +const logger = new Logger('GUARD'); + +async function guardFunction(req: Request, _: Response, next: NextFunction) { + // Guard logic here + + if (validationFails) { + throw new UnauthorizedException(); + } + + return next(); +} + +export const guardName = { guardFunction }; +``` + +## Authentication Guard Pattern + +### API Key Authentication +```typescript +async function apikey(req: Request, _: Response, next: NextFunction) { + const env = configService.get('AUTHENTICATION').API_KEY; + const key = req.get('apikey'); + const db = configService.get('DATABASE'); + + if (!key) { + throw new UnauthorizedException(); + } + + // Global API key check + if (env.KEY === key) { + return next(); + } + + // Special routes handling + if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) { + throw new ForbiddenException('Missing global api key', 'The global api key must be set'); + } + + const param = req.params as unknown as InstanceDto; + + try { + if (param?.instanceName) { + const instance = await prismaRepository.instance.findUnique({ + where: { name: param.instanceName }, + }); + if (instance.token === key) { + return next(); + } + } else { + if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) { + const instanceByKey = await prismaRepository.instance.findFirst({ + where: { token: key }, + }); + if (instanceByKey) { + return next(); + } + } + } + } catch (error) { + logger.error(error); + } + + throw new UnauthorizedException(); +} + +export const authGuard = { apikey }; +``` + +## Instance Validation Guards + +### Instance Exists Guard +```typescript +async function getInstance(instanceName: string) { + try { + const cacheConf = configService.get('CACHE'); + + const exists = !!waMonitor.waInstances[instanceName]; + + if (cacheConf.REDIS.ENABLED && cacheConf.REDIS.SAVE_INSTANCES) { + const keyExists = await cache.has(instanceName); + return exists || keyExists; + } + + return exists || (await prismaRepository.instance.findMany({ where: { name: instanceName } })).length > 0; + } catch (error) { + throw new InternalServerErrorException(error?.toString()); + } +} + +export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) { + if (req.originalUrl.includes('/instance/create')) { + return next(); + } + + const param = req.params as unknown as InstanceDto; + if (!param?.instanceName) { + throw new BadRequestException('"instanceName" not provided.'); + } + + if (!(await getInstance(param.instanceName))) { + throw new NotFoundException(`The "${param.instanceName}" instance does not exist`); + } + + next(); +} +``` + +### Instance Logged Guard +```typescript +export async function instanceLoggedGuard(req: Request, _: Response, next: NextFunction) { + if (req.originalUrl.includes('/instance/create')) { + const instance = req.body as InstanceDto; + if (await getInstance(instance.instanceName)) { + throw new ForbiddenException(`This name "${instance.instanceName}" is already in use.`); + } + + if (waMonitor.waInstances[instance.instanceName]) { + delete waMonitor.waInstances[instance.instanceName]; + } + } + + next(); +} +``` + +## Telemetry Guard Pattern + +### Telemetry Collection +```typescript +class Telemetry { + public collectTelemetry(req: Request, res: Response, next: NextFunction): void { + // Collect telemetry data + const telemetryData = { + route: req.originalUrl, + method: req.method, + timestamp: new Date(), + userAgent: req.get('User-Agent'), + }; + + // Send telemetry asynchronously (don't block request) + setImmediate(() => { + this.sendTelemetry(telemetryData); + }); + + next(); + } + + private async sendTelemetry(data: any): Promise { + try { + // Send telemetry data + } catch (error) { + // Silently fail - don't affect main request + } + } +} + +export default Telemetry; +``` + +## Guard Composition Pattern + +### Multiple Guards Usage +```typescript +// In router setup +const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']]; + +router + .use('/instance', new InstanceRouter(configService, ...guards).router) + .use('/message', new MessageRouter(...guards).router) + .use('/chat', new ChatRouter(...guards).router); +``` + +## Error Handling in Guards + +### Proper Exception Throwing +```typescript +// CORRECT - Use proper HTTP exceptions +if (!apiKey) { + throw new UnauthorizedException('API key required'); +} + +if (instanceExists) { + throw new ForbiddenException('Instance already exists'); +} + +if (!instanceFound) { + throw new NotFoundException('Instance not found'); +} + +if (validationFails) { + throw new BadRequestException('Invalid request parameters'); +} + +// INCORRECT - Don't use generic Error +if (!apiKey) { + throw new Error('API key required'); // ❌ Use specific exceptions +} +``` + +## Configuration Access in Guards + +### Config Service Usage +```typescript +async function configAwareGuard(req: Request, _: Response, next: NextFunction) { + const authConfig = configService.get('AUTHENTICATION'); + const cacheConfig = configService.get('CACHE'); + const dbConfig = configService.get('DATABASE'); + + // Use configuration for guard logic + if (authConfig.API_KEY.KEY === providedKey) { + return next(); + } + + throw new UnauthorizedException(); +} +``` + +## Database Access in Guards + +### Prisma Repository Usage +```typescript +async function databaseGuard(req: Request, _: Response, next: NextFunction) { + try { + const param = req.params as unknown as InstanceDto; + + const instance = await prismaRepository.instance.findUnique({ + where: { name: param.instanceName }, + }); + + if (!instance) { + throw new NotFoundException('Instance not found'); + } + + // Additional validation logic + if (instance.status !== 'active') { + throw new ForbiddenException('Instance not active'); + } + + return next(); + } catch (error) { + logger.error('Database guard error:', error); + throw new InternalServerErrorException('Database access failed'); + } +} +``` + +## Cache Integration in Guards + +### Cache Service Usage +```typescript +async function cacheAwareGuard(req: Request, _: Response, next: NextFunction) { + const cacheConf = configService.get('CACHE'); + + if (cacheConf.REDIS.ENABLED) { + const cached = await cache.get(`guard:${req.params.instanceName}`); + if (cached) { + // Use cached validation result + return next(); + } + } + + // Perform validation and cache result + const isValid = await performValidation(req.params.instanceName); + + if (cacheConf.REDIS.ENABLED) { + await cache.set(`guard:${req.params.instanceName}`, isValid, 300); // 5 min TTL + } + + if (isValid) { + return next(); + } + + throw new UnauthorizedException(); +} +``` + +## Logging in Guards + +### Structured Logging +```typescript +const logger = new Logger('GUARD'); + +async function loggedGuard(req: Request, _: Response, next: NextFunction) { + logger.log(`Guard validation started for ${req.originalUrl}`); + + try { + // Guard logic + const isValid = await validateRequest(req); + + if (isValid) { + logger.log(`Guard validation successful for ${req.params.instanceName}`); + return next(); + } + + logger.warn(`Guard validation failed for ${req.params.instanceName}`); + throw new UnauthorizedException(); + } catch (error) { + logger.error(`Guard validation error: ${error.message}`, error.stack); + throw error; + } +} +``` + +## Guard Testing Pattern + +### Unit Test Structure +```typescript +describe('authGuard', () => { + let req: Partial; + let res: Partial; + let next: NextFunction; + + beforeEach(() => { + req = { + get: jest.fn(), + params: {}, + originalUrl: '/test', + }; + res = {}; + next = jest.fn(); + }); + + describe('apikey', () => { + it('should pass with valid global API key', async () => { + (req.get as jest.Mock).mockReturnValue('valid-global-key'); + + await authGuard.apikey(req as Request, res as Response, next); + + expect(next).toHaveBeenCalled(); + }); + + it('should throw UnauthorizedException with no API key', async () => { + (req.get as jest.Mock).mockReturnValue(undefined); + + await expect( + authGuard.apikey(req as Request, res as Response, next) + ).rejects.toThrow(UnauthorizedException); + }); + + it('should pass with valid instance token', async () => { + (req.get as jest.Mock).mockReturnValue('instance-token'); + req.params = { instanceName: 'test-instance' }; + + // Mock prisma repository + jest.spyOn(prismaRepository.instance, 'findUnique').mockResolvedValue({ + token: 'instance-token', + } as any); + + await authGuard.apikey(req as Request, res as Response, next); + + expect(next).toHaveBeenCalled(); + }); + }); +}); +``` + +## Guard Performance Considerations + +### Efficient Validation +```typescript +// CORRECT - Efficient guard with early returns +async function efficientGuard(req: Request, _: Response, next: NextFunction) { + // Quick checks first + if (req.originalUrl.includes('/public')) { + return next(); // Skip validation for public routes + } + + const apiKey = req.get('apikey'); + if (!apiKey) { + throw new UnauthorizedException(); // Fail fast + } + + // More expensive checks only if needed + if (apiKey === globalKey) { + return next(); // Skip database check + } + + // Database check only as last resort + const isValid = await validateInDatabase(apiKey); + if (isValid) { + return next(); + } + + throw new UnauthorizedException(); +} + +// INCORRECT - Inefficient guard +async function inefficientGuard(req: Request, _: Response, next: NextFunction) { + // Always do expensive database check first + const dbResult = await expensiveDatabaseQuery(); // ❌ Expensive operation first + + const apiKey = req.get('apikey'); + if (!apiKey && dbResult) { // ❌ Complex logic + throw new UnauthorizedException(); + } + + next(); +} +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/integration-channel-rules.mdc b/.cursor/rules/specialized-rules/integration-channel-rules.mdc new file mode 100644 index 000000000..d2b94d965 --- /dev/null +++ b/.cursor/rules/specialized-rules/integration-channel-rules.mdc @@ -0,0 +1,552 @@ +--- +description: Channel integration patterns for Evolution API +globs: + - "src/api/integrations/channel/**/*.ts" +alwaysApply: false +--- + +# Evolution API Channel Integration Rules + +## Channel Controller Pattern + +### Base Channel Controller +```typescript +export interface ChannelControllerInterface { + integrationEnabled: boolean; +} + +export class ChannelController { + public prismaRepository: PrismaRepository; + public waMonitor: WAMonitoringService; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + this.prisma = prismaRepository; + this.monitor = waMonitor; + } + + public set prisma(prisma: PrismaRepository) { + this.prismaRepository = prisma; + } + + public get prisma() { + return this.prismaRepository; + } + + public set monitor(waMonitor: WAMonitoringService) { + this.waMonitor = waMonitor; + } + + public get monitor() { + return this.waMonitor; + } + + public init(instanceData: InstanceDto, data: ChannelDataType) { + if (!instanceData.token && instanceData.integration === Integration.WHATSAPP_BUSINESS) { + throw new BadRequestException('token is required'); + } + + if (instanceData.integration === Integration.WHATSAPP_BUSINESS) { + return new BusinessStartupService(/* dependencies */); + } + + if (instanceData.integration === Integration.EVOLUTION) { + return new EvolutionStartupService(/* dependencies */); + } + + if (instanceData.integration === Integration.WHATSAPP_BAILEYS) { + return new BaileysStartupService(/* dependencies */); + } + + return null; + } +} +``` + +### Extended Channel Controller +```typescript +export class EvolutionController extends ChannelController implements ChannelControllerInterface { + private readonly logger = new Logger('EvolutionController'); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + } + + integrationEnabled: boolean; + + public async receiveWebhook(data: any) { + const numberId = data.numberId; + + if (!numberId) { + this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found'); + return; + } + + const instance = await this.prismaRepository.instance.findFirst({ + where: { number: numberId }, + }); + + if (!instance) { + this.logger.error('WebhookService -> receiveWebhook -> instance not found'); + return; + } + + await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data); + + return { + status: 'success', + }; + } +} +``` + +## Channel Service Pattern + +### Base Channel Service +```typescript +export class ChannelStartupService { + constructor( + private readonly configService: ConfigService, + private readonly eventEmitter: EventEmitter2, + private readonly prismaRepository: PrismaRepository, + public readonly cache: CacheService, + public readonly chatwootCache: CacheService, + ) {} + + public readonly logger = new Logger('ChannelStartupService'); + + public client: WASocket; + public readonly instance: wa.Instance = {}; + public readonly localChatwoot: wa.LocalChatwoot = {}; + public readonly localProxy: wa.LocalProxy = {}; + public readonly localSettings: wa.LocalSettings = {}; + public readonly localWebhook: wa.LocalWebHook = {}; + + public setInstance(instance: InstanceDto) { + this.logger.setInstance(instance.instanceName); + + this.instance.name = instance.instanceName; + this.instance.id = instance.instanceId; + this.instance.integration = instance.integration; + this.instance.number = instance.number; + this.instance.token = instance.token; + this.instance.businessId = instance.businessId; + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + this.chatwootService.eventWhatsapp( + Events.STATUS_INSTANCE, + { instanceName: this.instance.name }, + { + instance: this.instance.name, + status: 'created', + }, + ); + } + } + + public set instanceName(name: string) { + this.logger.setInstance(name); + this.instance.name = name; + } + + public get instanceName() { + return this.instance.name; + } +} +``` + +### Extended Channel Service +```typescript +export class EvolutionStartupService extends ChannelStartupService { + constructor( + configService: ConfigService, + eventEmitter: EventEmitter2, + prismaRepository: PrismaRepository, + cache: CacheService, + chatwootCache: CacheService, + ) { + super(configService, eventEmitter, prismaRepository, cache, chatwootCache); + } + + public async sendMessage(data: SendTextDto): Promise { + // Evolution-specific message sending logic + const response = await this.evolutionApiCall('/send-message', data); + return response; + } + + public async connectToWhatsapp(data: any): Promise { + // Evolution-specific connection logic + this.logger.log('Connecting to Evolution API'); + + // Set up webhook listeners + this.setupWebhookHandlers(); + + // Initialize connection + await this.initializeConnection(data); + } + + private async evolutionApiCall(endpoint: string, data: any): Promise { + const config = this.configService.get('EVOLUTION'); + + try { + const response = await axios.post(`${config.API_URL}${endpoint}`, data, { + headers: { + 'Authorization': `Bearer ${this.instance.token}`, + 'Content-Type': 'application/json', + }, + }); + + return response.data; + } catch (error) { + this.logger.error(`Evolution API call failed: ${error.message}`); + throw new InternalServerErrorException('Evolution API call failed'); + } + } + + private setupWebhookHandlers(): void { + // Set up webhook event handlers + } + + private async initializeConnection(data: any): Promise { + // Initialize connection with Evolution API + } +} +``` + +## Business API Service Pattern + +### Meta Business Service +```typescript +export class BusinessStartupService extends ChannelStartupService { + constructor( + configService: ConfigService, + eventEmitter: EventEmitter2, + prismaRepository: PrismaRepository, + cache: CacheService, + chatwootCache: CacheService, + baileysCache: CacheService, + providerFiles: ProviderFiles, + ) { + super(configService, eventEmitter, prismaRepository, cache, chatwootCache); + } + + public async sendMessage(data: SendTextDto): Promise { + const businessConfig = this.configService.get('WA_BUSINESS'); + + const payload = { + messaging_product: 'whatsapp', + to: data.number, + type: 'text', + text: { + body: data.text, + }, + }; + + try { + const response = await axios.post( + `${businessConfig.URL}/${businessConfig.VERSION}/${this.instance.businessId}/messages`, + payload, + { + headers: { + 'Authorization': `Bearer ${this.instance.token}`, + 'Content-Type': 'application/json', + }, + } + ); + + return response.data; + } catch (error) { + this.logger.error(`Business API call failed: ${error.message}`); + throw new BadRequestException('Failed to send message via Business API'); + } + } + + public async receiveWebhook(data: any): Promise { + // Process incoming webhook from Meta Business API + const { entry } = data; + + for (const entryItem of entry) { + const { changes } = entryItem; + + for (const change of changes) { + if (change.field === 'messages') { + await this.processMessage(change.value); + } + } + } + } + + private async processMessage(messageData: any): Promise { + // Process incoming message from Business API + const { messages, contacts } = messageData; + + if (messages) { + for (const message of messages) { + await this.handleIncomingMessage(message, contacts); + } + } + } + + private async handleIncomingMessage(message: any, contacts: any[]): Promise { + // Handle individual message + const contact = contacts?.find(c => c.wa_id === message.from); + + // Emit event for message processing + this.eventEmitter.emit(Events.MESSAGES_UPSERT, { + instanceName: this.instance.name, + message, + contact, + }); + } +} +``` + +## Baileys Service Pattern + +### Baileys Integration Service +```typescript +export class BaileysStartupService extends ChannelStartupService { + constructor( + configService: ConfigService, + eventEmitter: EventEmitter2, + prismaRepository: PrismaRepository, + cache: CacheService, + chatwootCache: CacheService, + baileysCache: CacheService, + providerFiles: ProviderFiles, + ) { + super(configService, eventEmitter, prismaRepository, cache, chatwootCache); + } + + public async connectToWhatsapp(): Promise { + const authPath = path.join(INSTANCE_DIR, this.instance.name); + const { state, saveCreds } = await useMultiFileAuthState(authPath); + + this.client = makeWASocket({ + auth: state, + logger: P({ level: 'error' }), + printQRInTerminal: false, + browser: ['Evolution API', 'Chrome', '4.0.0'], + defaultQueryTimeoutMs: 60000, + }); + + this.setupEventHandlers(); + this.client.ev.on('creds.update', saveCreds); + } + + private setupEventHandlers(): void { + this.client.ev.on('connection.update', (update) => { + this.handleConnectionUpdate(update); + }); + + this.client.ev.on('messages.upsert', ({ messages, type }) => { + this.handleIncomingMessages(messages, type); + }); + + this.client.ev.on('messages.update', (updates) => { + this.handleMessageUpdates(updates); + }); + + this.client.ev.on('contacts.upsert', (contacts) => { + this.handleContactsUpdate(contacts); + }); + + this.client.ev.on('chats.upsert', (chats) => { + this.handleChatsUpdate(chats); + }); + } + + private async handleConnectionUpdate(update: ConnectionUpdate): Promise { + const { connection, lastDisconnect, qr } = update; + + if (qr) { + this.instance.qrcode = { + count: this.instance.qrcode?.count ? this.instance.qrcode.count + 1 : 1, + base64: qr, + }; + + this.eventEmitter.emit(Events.QRCODE_UPDATED, { + instanceName: this.instance.name, + qrcode: this.instance.qrcode, + }); + } + + if (connection === 'close') { + const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut; + + if (shouldReconnect) { + this.logger.log('Connection closed, reconnecting...'); + await this.connectToWhatsapp(); + } else { + this.logger.log('Connection closed, logged out'); + this.eventEmitter.emit(Events.LOGOUT_INSTANCE, { + instanceName: this.instance.name, + }); + } + } + + if (connection === 'open') { + this.logger.log('Connection opened successfully'); + this.instance.wuid = this.client.user?.id; + + this.eventEmitter.emit(Events.CONNECTION_UPDATE, { + instanceName: this.instance.name, + state: 'open', + }); + } + } + + public async sendMessage(data: SendTextDto): Promise { + const jid = createJid(data.number); + + const message = { + text: data.text, + }; + + if (data.linkPreview !== undefined) { + message.linkPreview = data.linkPreview; + } + + if (data.mentionsEveryOne) { + // Handle mentions + } + + try { + const response = await this.client.sendMessage(jid, message); + return response; + } catch (error) { + this.logger.error(`Failed to send message: ${error.message}`); + throw new BadRequestException('Failed to send message'); + } + } +} +``` + +## Channel Router Pattern + +### Channel Router Structure +```typescript +export class ChannelRouter { + public readonly router: Router; + + constructor(configService: any, ...guards: any[]) { + this.router = Router(); + + this.router.use('/', new EvolutionRouter(configService).router); + this.router.use('/', new MetaRouter(configService).router); + this.router.use('/baileys', new BaileysRouter(...guards).router); + } +} +``` + +### Specific Channel Router +```typescript +export class EvolutionRouter extends RouterBroker { + constructor(private readonly configService: ConfigService) { + super(); + this.router + .post(this.routerPath('webhook'), async (req, res) => { + const response = await evolutionController.receiveWebhook(req.body); + return res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} +``` + +## Integration Types + +### Channel Data Types +```typescript +type ChannelDataType = { + configService: ConfigService; + eventEmitter: EventEmitter2; + prismaRepository: PrismaRepository; + cache: CacheService; + chatwootCache: CacheService; + baileysCache: CacheService; + providerFiles: ProviderFiles; +}; + +export enum Integration { + WHATSAPP_BUSINESS = 'WHATSAPP-BUSINESS', + WHATSAPP_BAILEYS = 'WHATSAPP-BAILEYS', + EVOLUTION = 'EVOLUTION', +} +``` + +## Error Handling in Channels + +### Channel-Specific Error Handling +```typescript +// CORRECT - Channel-specific error handling +public async sendMessage(data: SendTextDto): Promise { + try { + const response = await this.channelSpecificSend(data); + return response; + } catch (error) { + this.logger.error(`${this.constructor.name} send failed: ${error.message}`); + + if (error.response?.status === 401) { + throw new UnauthorizedException('Invalid token for channel'); + } + + if (error.response?.status === 429) { + throw new BadRequestException('Rate limit exceeded'); + } + + throw new InternalServerErrorException('Channel communication failed'); + } +} +``` + +## Channel Testing Pattern + +### Channel Service Testing +```typescript +describe('EvolutionStartupService', () => { + let service: EvolutionStartupService; + let configService: jest.Mocked; + let eventEmitter: jest.Mocked; + + beforeEach(() => { + const mockConfig = { + get: jest.fn().mockReturnValue({ + API_URL: 'https://api.evolution.com', + }), + }; + + service = new EvolutionStartupService( + mockConfig as any, + eventEmitter, + prismaRepository, + cache, + chatwootCache, + ); + }); + + describe('sendMessage', () => { + it('should send message successfully', async () => { + const data = { number: '5511999999999', text: 'Test message' }; + + // Mock axios response + jest.spyOn(axios, 'post').mockResolvedValue({ + data: { success: true, messageId: '123' }, + }); + + const result = await service.sendMessage(data); + + expect(result.success).toBe(true); + expect(axios.post).toHaveBeenCalledWith( + expect.stringContaining('/send-message'), + data, + expect.objectContaining({ + headers: expect.objectContaining({ + 'Authorization': expect.stringContaining('Bearer'), + }), + }) + ); + }); + }); +}); +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/integration-chatbot-rules.mdc b/.cursor/rules/specialized-rules/integration-chatbot-rules.mdc new file mode 100644 index 000000000..ff511754a --- /dev/null +++ b/.cursor/rules/specialized-rules/integration-chatbot-rules.mdc @@ -0,0 +1,597 @@ +--- +description: Chatbot integration patterns for Evolution API +globs: + - "src/api/integrations/chatbot/**/*.ts" +alwaysApply: false +--- + +# Evolution API Chatbot Integration Rules + +## Base Chatbot Pattern + +### Base Chatbot DTO +```typescript +/** + * Base DTO for all chatbot integrations + * Contains common properties shared by all chatbot types + */ +export class BaseChatbotDto { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; +} +``` + +### Base Chatbot Controller +```typescript +export abstract class BaseChatbotController + extends ChatbotController + implements ChatbotControllerInterface +{ + public readonly logger: Logger; + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Abstract methods to be implemented by specific chatbots + protected abstract readonly integrationName: string; + protected abstract processBot( + waInstance: any, + remoteJid: string, + bot: BotType, + session: any, + settings: ChatbotSettings, + content: string, + pushName?: string, + msg?: any, + ): Promise; + protected abstract getFallbackBotId(settings: any): string | undefined; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + this.sessionRepository = this.prismaRepository.integrationSession; + } + + // Base implementation methods + public async createBot(instance: InstanceDto, data: BotData) { + if (!data.enabled) { + throw new BadRequestException(`${this.integrationName} is disabled`); + } + + // Common bot creation logic + const bot = await this.botRepository.create({ + data: { + ...data, + instanceId: instance.instanceId, + }, + }); + + return bot; + } +} +``` + +### Base Chatbot Service +```typescript +/** + * Base class for all chatbot service implementations + * Contains common methods shared across different chatbot integrations + */ +export abstract class BaseChatbotService { + protected readonly logger: Logger; + protected readonly waMonitor: WAMonitoringService; + protected readonly prismaRepository: PrismaRepository; + protected readonly configService?: ConfigService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + loggerName: string, + configService?: ConfigService, + ) { + this.waMonitor = waMonitor; + this.prismaRepository = prismaRepository; + this.logger = new Logger(loggerName); + this.configService = configService; + } + + /** + * Check if a message contains an image + */ + protected isImageMessage(content: string): boolean { + return content.includes('imageMessage'); + } + + /** + * Extract text content from message + */ + protected getMessageContent(msg: any): string { + return getConversationMessage(msg); + } + + /** + * Send typing indicator + */ + protected async sendTyping(instanceName: string, remoteJid: string): Promise { + await this.waMonitor.waInstances[instanceName].sendPresence(remoteJid, 'composing'); + } +} +``` + +## Typebot Integration Pattern + +### Typebot Service +```typescript +export class TypebotService extends BaseChatbotService { + constructor( + waMonitor: WAMonitoringService, + configService: ConfigService, + prismaRepository: PrismaRepository, + private readonly openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'TypebotService', configService); + } + + public async sendTypebotMessage( + instanceName: string, + remoteJid: string, + typebot: TypebotModel, + content: string, + ): Promise { + try { + const response = await axios.post( + `${typebot.url}/api/v1/typebots/${typebot.typebot}/startChat`, + { + message: content, + sessionId: `${instanceName}-${remoteJid}`, + }, + { + headers: { + 'Content-Type': 'application/json', + }, + } + ); + + const { messages } = response.data; + + for (const message of messages) { + await this.processTypebotMessage(instanceName, remoteJid, message); + } + } catch (error) { + this.logger.error(`Typebot API error: ${error.message}`); + throw new InternalServerErrorException('Typebot communication failed'); + } + } + + private async processTypebotMessage( + instanceName: string, + remoteJid: string, + message: any, + ): Promise { + const waInstance = this.waMonitor.waInstances[instanceName]; + + if (message.type === 'text') { + await waInstance.sendMessage({ + number: remoteJid.split('@')[0], + text: message.content.richText[0].children[0].text, + }); + } + + if (message.type === 'image') { + await waInstance.sendMessage({ + number: remoteJid.split('@')[0], + mediaMessage: { + mediatype: 'image', + media: message.content.url, + }, + }); + } + } +} +``` + +## OpenAI Integration Pattern + +### OpenAI Service +```typescript +export class OpenaiService extends BaseChatbotService { + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + ) { + super(waMonitor, prismaRepository, 'OpenaiService', configService); + } + + public async sendOpenaiMessage( + instanceName: string, + remoteJid: string, + openai: OpenaiModel, + content: string, + pushName?: string, + ): Promise { + try { + const openaiConfig = this.configService.get('OPENAI'); + + const response = await axios.post( + 'https://api.openai.com/v1/chat/completions', + { + model: openai.model || 'gpt-3.5-turbo', + messages: [ + { + role: 'system', + content: openai.systemMessage || 'You are a helpful assistant.', + }, + { + role: 'user', + content: content, + }, + ], + max_tokens: openai.maxTokens || 1000, + temperature: openai.temperature || 0.7, + }, + { + headers: { + 'Authorization': `Bearer ${openai.apiKey || openaiConfig.API_KEY}`, + 'Content-Type': 'application/json', + }, + } + ); + + const aiResponse = response.data.choices[0].message.content; + + await this.waMonitor.waInstances[instanceName].sendMessage({ + number: remoteJid.split('@')[0], + text: aiResponse, + }); + } catch (error) { + this.logger.error(`OpenAI API error: ${error.message}`); + + // Send fallback message + await this.waMonitor.waInstances[instanceName].sendMessage({ + number: remoteJid.split('@')[0], + text: openai.unknownMessage || 'Desculpe, não consegui processar sua mensagem.', + }); + } + } +} +``` + +## Chatwoot Integration Pattern + +### Chatwoot Service +```typescript +export class ChatwootService extends BaseChatbotService { + constructor( + waMonitor: WAMonitoringService, + configService: ConfigService, + prismaRepository: PrismaRepository, + private readonly chatwootCache: CacheService, + ) { + super(waMonitor, prismaRepository, 'ChatwootService', configService); + } + + public async eventWhatsapp( + event: Events, + instanceName: { instanceName: string }, + data: any, + ): Promise { + const chatwootConfig = this.configService.get('CHATWOOT'); + + if (!chatwootConfig.ENABLED) { + return; + } + + try { + const instance = await this.prismaRepository.instance.findUnique({ + where: { name: instanceName.instanceName }, + }); + + if (!instance?.chatwootAccountId) { + return; + } + + const webhook = { + event, + instance: instanceName.instanceName, + data, + timestamp: new Date().toISOString(), + }; + + await axios.post( + `${instance.chatwootUrl}/api/v1/accounts/${instance.chatwootAccountId}/webhooks`, + webhook, + { + headers: { + 'Authorization': `Bearer ${instance.chatwootToken}`, + 'Content-Type': 'application/json', + }, + } + ); + } catch (error) { + this.logger.error(`Chatwoot webhook error: ${error.message}`); + } + } + + public async createConversation( + instanceName: string, + contact: any, + message: any, + ): Promise { + // Create conversation in Chatwoot + const instance = await this.prismaRepository.instance.findUnique({ + where: { name: instanceName }, + }); + + if (!instance?.chatwootAccountId) { + return; + } + + try { + const conversation = await axios.post( + `${instance.chatwootUrl}/api/v1/accounts/${instance.chatwootAccountId}/conversations`, + { + source_id: contact.id, + inbox_id: instance.chatwootInboxId, + contact_id: contact.chatwootContactId, + }, + { + headers: { + 'Authorization': `Bearer ${instance.chatwootToken}`, + 'Content-Type': 'application/json', + }, + } + ); + + // Cache conversation + await this.chatwootCache.set( + `conversation:${instanceName}:${contact.id}`, + conversation.data, + 3600 + ); + } catch (error) { + this.logger.error(`Chatwoot conversation creation error: ${error.message}`); + } + } +} +``` + +## Dify Integration Pattern + +### Dify Service +```typescript +export class DifyService extends BaseChatbotService { + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + private readonly openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'DifyService', configService); + } + + public async sendDifyMessage( + instanceName: string, + remoteJid: string, + dify: DifyModel, + content: string, + ): Promise { + try { + const response = await axios.post( + `${dify.apiUrl}/v1/chat-messages`, + { + inputs: {}, + query: content, + user: remoteJid, + conversation_id: `${instanceName}-${remoteJid}`, + response_mode: 'blocking', + }, + { + headers: { + 'Authorization': `Bearer ${dify.apiKey}`, + 'Content-Type': 'application/json', + }, + } + ); + + const aiResponse = response.data.answer; + + await this.waMonitor.waInstances[instanceName].sendMessage({ + number: remoteJid.split('@')[0], + text: aiResponse, + }); + } catch (error) { + this.logger.error(`Dify API error: ${error.message}`); + + // Fallback to OpenAI if configured + if (dify.fallbackOpenai && this.openaiService) { + await this.openaiService.sendOpenaiMessage(instanceName, remoteJid, dify.openaiBot, content); + } + } + } +} +``` + +## Chatbot Router Pattern + +### Chatbot Router Structure (Evolution API Real Pattern) +```typescript +export class ChatbotRouter { + public readonly router: Router; + + constructor(...guards: any[]) { + this.router = Router(); + + // Real Evolution API chatbot integrations + this.router.use('/evolutionBot', new EvolutionBotRouter(...guards).router); + this.router.use('/chatwoot', new ChatwootRouter(...guards).router); + this.router.use('/typebot', new TypebotRouter(...guards).router); + this.router.use('/openai', new OpenaiRouter(...guards).router); + this.router.use('/dify', new DifyRouter(...guards).router); + this.router.use('/flowise', new FlowiseRouter(...guards).router); + this.router.use('/n8n', new N8nRouter(...guards).router); + this.router.use('/evoai', new EvoaiRouter(...guards).router); + } +} +``` + +## Chatbot Validation Patterns + +### Chatbot Schema Validation (Evolution API Pattern) +```typescript +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...fields: string[]) => { + const properties = {}; + fields.forEach((field) => { + properties[field] = { + if: { properties: { [field]: { type: 'string' } } }, + then: { properties: { [field]: { minLength: 1 } } }, + }; + }); + + return { + allOf: Object.values(properties), + }; +}; + +export const evolutionBotSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + apiUrl: { type: 'string' }, + apiKey: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: ['enabled', 'apiUrl', 'triggerType'], + ...isNotEmpty('enabled', 'apiUrl', 'triggerType'), +}; + +function validateKeywordTrigger( + content: string, + operator: TriggerOperator, + value: string, +): boolean { + const normalizedContent = content.toLowerCase().trim(); + const normalizedValue = value.toLowerCase().trim(); + + switch (operator) { + case TriggerOperator.EQUALS: + return normalizedContent === normalizedValue; + case TriggerOperator.CONTAINS: + return normalizedContent.includes(normalizedValue); + case TriggerOperator.STARTS_WITH: + return normalizedContent.startsWith(normalizedValue); + case TriggerOperator.ENDS_WITH: + return normalizedContent.endsWith(normalizedValue); + default: + return false; + } +} +``` + +## Session Management Pattern + +### Chatbot Session Handling +```typescript +export class ChatbotSessionManager { + constructor( + private readonly prismaRepository: PrismaRepository, + private readonly cache: CacheService, + ) {} + + public async getSession( + instanceName: string, + remoteJid: string, + botId: string, + ): Promise { + const cacheKey = `session:${instanceName}:${remoteJid}:${botId}`; + + // Try cache first + let session = await this.cache.get(cacheKey); + if (session) { + return session; + } + + // Query database + session = await this.prismaRepository.integrationSession.findFirst({ + where: { + instanceId: instanceName, + remoteJid, + botId, + status: 'opened', + }, + }); + + // Cache result + if (session) { + await this.cache.set(cacheKey, session, 300); // 5 min TTL + } + + return session; + } + + public async createSession( + instanceName: string, + remoteJid: string, + botId: string, + ): Promise { + const session = await this.prismaRepository.integrationSession.create({ + data: { + instanceId: instanceName, + remoteJid, + botId, + status: 'opened', + createdAt: new Date(), + }, + }); + + // Cache new session + const cacheKey = `session:${instanceName}:${remoteJid}:${botId}`; + await this.cache.set(cacheKey, session, 300); + + return session; + } + + public async closeSession(sessionId: string): Promise { + await this.prismaRepository.integrationSession.update({ + where: { id: sessionId }, + data: { status: 'closed', updatedAt: new Date() }, + }); + + // Invalidate cache + // Note: In a real implementation, you'd need to track cache keys by session ID + } +} +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/integration-event-rules.mdc b/.cursor/rules/specialized-rules/integration-event-rules.mdc new file mode 100644 index 000000000..2687d72f0 --- /dev/null +++ b/.cursor/rules/specialized-rules/integration-event-rules.mdc @@ -0,0 +1,851 @@ +--- +description: Event integration patterns for Evolution API +globs: + - "src/api/integrations/event/**/*.ts" +alwaysApply: false +--- + +# Evolution API Event Integration Rules + +## Event Manager Pattern + +### Event Manager Structure +```typescript +import { PrismaRepository } from '@api/repository/repository.service'; +import { ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Server } from 'http'; + +export class EventManager { + private prismaRepository: PrismaRepository; + private configService: ConfigService; + private logger = new Logger('EventManager'); + + // Event integrations + private webhook: WebhookController; + private websocket: WebsocketController; + private rabbitmq: RabbitmqController; + private nats: NatsController; + private sqs: SqsController; + private pusher: PusherController; + + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + server?: Server, + ) { + this.prismaRepository = prismaRepository; + this.configService = configService; + + // Initialize event controllers + this.webhook = new WebhookController(prismaRepository, configService); + this.websocket = new WebsocketController(prismaRepository, configService, server); + this.rabbitmq = new RabbitmqController(prismaRepository, configService); + this.nats = new NatsController(prismaRepository, configService); + this.sqs = new SqsController(prismaRepository, configService); + this.pusher = new PusherController(prismaRepository, configService); + } + + public async emit(eventData: { + instanceName: string; + origin: string; + event: string; + data: Object; + serverUrl: string; + dateTime: string; + sender: string; + apiKey?: string; + local?: boolean; + integration?: string[]; + }): Promise { + this.logger.log(`Emitting event ${eventData.event} for instance ${eventData.instanceName}`); + + // Emit to all configured integrations + await Promise.allSettled([ + this.webhook.emit(eventData), + this.websocket.emit(eventData), + this.rabbitmq.emit(eventData), + this.nats.emit(eventData), + this.sqs.emit(eventData), + this.pusher.emit(eventData), + ]); + } + + public async setInstance(instanceName: string, data: any): Promise { + const promises = []; + + if (data.websocket) { + promises.push( + this.websocket.set(instanceName, { + websocket: { + enabled: true, + events: data.websocket?.events, + }, + }) + ); + } + + if (data.rabbitmq) { + promises.push( + this.rabbitmq.set(instanceName, { + rabbitmq: { + enabled: true, + events: data.rabbitmq?.events, + }, + }) + ); + } + + if (data.webhook) { + promises.push( + this.webhook.set(instanceName, { + webhook: { + enabled: true, + events: data.webhook?.events, + url: data.webhook?.url, + headers: data.webhook?.headers, + base64: data.webhook?.base64, + byEvents: data.webhook?.byEvents, + }, + }) + ); + } + + // Set other integrations... + + await Promise.allSettled(promises); + } +} +``` + +## Base Event Controller Pattern + +### Abstract Event Controller +```typescript +import { PrismaRepository } from '@api/repository/repository.service'; +import { ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; + +export type EmitData = { + instanceName: string; + origin: string; + event: string; + data: Object; + serverUrl: string; + dateTime: string; + sender: string; + apiKey?: string; + local?: boolean; + integration?: string[]; +}; + +export interface EventControllerInterface { + integrationEnabled: boolean; + emit(data: EmitData): Promise; + set(instanceName: string, data: any): Promise; +} + +export abstract class EventController implements EventControllerInterface { + protected readonly logger: Logger; + protected readonly prismaRepository: PrismaRepository; + protected readonly configService: ConfigService; + + public integrationEnabled: boolean = false; + + // Available events for all integrations + public static readonly events = [ + 'APPLICATION_STARTUP', + 'INSTANCE_CREATE', + 'INSTANCE_DELETE', + 'QRCODE_UPDATED', + 'CONNECTION_UPDATE', + 'STATUS_INSTANCE', + 'MESSAGES_SET', + 'MESSAGES_UPSERT', + 'MESSAGES_EDITED', + 'MESSAGES_UPDATE', + 'MESSAGES_DELETE', + 'SEND_MESSAGE', + 'CONTACTS_SET', + 'CONTACTS_UPSERT', + 'CONTACTS_UPDATE', + 'PRESENCE_UPDATE', + 'CHATS_SET', + 'CHATS_UPDATE', + 'CHATS_UPSERT', + 'CHATS_DELETE', + 'GROUPS_UPSERT', + 'GROUPS_UPDATE', + 'GROUP_PARTICIPANTS_UPDATE', + 'CALL', + 'TYPEBOT_START', + 'TYPEBOT_CHANGE_STATUS', + 'LABELS_EDIT', + 'LABELS_ASSOCIATION', + 'CREDS_UPDATE', + 'MESSAGING_HISTORY_SET', + 'REMOVE_INSTANCE', + 'LOGOUT_INSTANCE', + ]; + + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + loggerName: string, + ) { + this.prismaRepository = prismaRepository; + this.configService = configService; + this.logger = new Logger(loggerName); + } + + // Abstract methods to be implemented by specific integrations + public abstract emit(data: EmitData): Promise; + public abstract set(instanceName: string, data: any): Promise; + + // Helper method to check if event should be processed + protected shouldProcessEvent(eventName: string, configuredEvents?: string[]): boolean { + if (!configuredEvents || configuredEvents.length === 0) { + return true; // Process all events if none specified + } + return configuredEvents.includes(eventName); + } + + // Helper method to get instance configuration + protected async getInstanceConfig(instanceName: string): Promise { + try { + const instance = await this.prismaRepository.instance.findUnique({ + where: { name: instanceName }, + }); + return instance; + } catch (error) { + this.logger.error(`Failed to get instance config for ${instanceName}:`, error); + return null; + } + } +} +``` + +## Webhook Integration Pattern + +### Webhook Controller Implementation +```typescript +export class WebhookController extends EventController { + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + ) { + super(prismaRepository, configService, 'WebhookController'); + } + + public async emit(data: EmitData): Promise { + try { + const instance = await this.getInstanceConfig(data.instanceName); + if (!instance?.webhook?.enabled) { + return; + } + + const webhookConfig = instance.webhook; + + if (!this.shouldProcessEvent(data.event, webhookConfig.events)) { + return; + } + + const payload = { + event: data.event, + instance: data.instanceName, + data: data.data, + timestamp: data.dateTime, + sender: data.sender, + server: { + version: process.env.npm_package_version, + url: data.serverUrl, + }, + }; + + // Encode data as base64 if configured + if (webhookConfig.base64) { + payload.data = Buffer.from(JSON.stringify(payload.data)).toString('base64'); + } + + const headers = { + 'Content-Type': 'application/json', + 'User-Agent': 'Evolution-API-Webhook', + ...webhookConfig.headers, + }; + + if (webhookConfig.byEvents) { + // Send to event-specific endpoint + const eventUrl = `${webhookConfig.url}/${data.event.toLowerCase()}`; + await this.sendWebhook(eventUrl, payload, headers); + } else { + // Send to main webhook URL + await this.sendWebhook(webhookConfig.url, payload, headers); + } + + this.logger.log(`Webhook sent for event ${data.event} to instance ${data.instanceName}`); + } catch (error) { + this.logger.error(`Webhook emission failed for ${data.instanceName}:`, error); + } + } + + public async set(instanceName: string, data: any): Promise { + try { + const webhookData = data.webhook; + + await this.prismaRepository.instance.update({ + where: { name: instanceName }, + data: { + webhook: webhookData, + }, + }); + + this.logger.log(`Webhook configuration set for instance ${instanceName}`); + return { webhook: webhookData }; + } catch (error) { + this.logger.error(`Failed to set webhook config for ${instanceName}:`, error); + throw error; + } + } + + private async sendWebhook(url: string, payload: any, headers: any): Promise { + try { + const response = await axios.post(url, payload, { + headers, + timeout: 30000, + maxRedirects: 3, + }); + + if (response.status >= 200 && response.status < 300) { + this.logger.log(`Webhook delivered successfully to ${url}`); + } else { + this.logger.warn(`Webhook returned status ${response.status} for ${url}`); + } + } catch (error) { + this.logger.error(`Webhook delivery failed to ${url}:`, error.message); + + // Implement retry logic here if needed + if (error.response?.status >= 500) { + // Server error - might be worth retrying + this.logger.log(`Server error detected, webhook might be retried later`); + } + } + } +} +``` + +## WebSocket Integration Pattern + +### WebSocket Controller Implementation +```typescript +import { Server as SocketIOServer } from 'socket.io'; +import { Server } from 'http'; + +export class WebsocketController extends EventController { + private io: SocketIOServer; + + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + server?: Server, + ) { + super(prismaRepository, configService, 'WebsocketController'); + + if (server) { + this.io = new SocketIOServer(server, { + cors: { + origin: "*", + methods: ["GET", "POST"], + }, + }); + + this.setupSocketHandlers(); + } + } + + private setupSocketHandlers(): void { + this.io.on('connection', (socket) => { + this.logger.log(`WebSocket client connected: ${socket.id}`); + + socket.on('join-instance', (instanceName: string) => { + socket.join(`instance:${instanceName}`); + this.logger.log(`Client ${socket.id} joined instance ${instanceName}`); + }); + + socket.on('leave-instance', (instanceName: string) => { + socket.leave(`instance:${instanceName}`); + this.logger.log(`Client ${socket.id} left instance ${instanceName}`); + }); + + socket.on('disconnect', () => { + this.logger.log(`WebSocket client disconnected: ${socket.id}`); + }); + }); + } + + public async emit(data: EmitData): Promise { + if (!this.io) { + return; + } + + try { + const instance = await this.getInstanceConfig(data.instanceName); + if (!instance?.websocket?.enabled) { + return; + } + + const websocketConfig = instance.websocket; + + if (!this.shouldProcessEvent(data.event, websocketConfig.events)) { + return; + } + + const payload = { + event: data.event, + instance: data.instanceName, + data: data.data, + timestamp: data.dateTime, + sender: data.sender, + }; + + // Emit to specific instance room + this.io.to(`instance:${data.instanceName}`).emit('evolution-event', payload); + + // Also emit to global room for monitoring + this.io.emit('global-event', payload); + + this.logger.log(`WebSocket event ${data.event} emitted for instance ${data.instanceName}`); + } catch (error) { + this.logger.error(`WebSocket emission failed for ${data.instanceName}:`, error); + } + } + + public async set(instanceName: string, data: any): Promise { + try { + const websocketData = data.websocket; + + await this.prismaRepository.instance.update({ + where: { name: instanceName }, + data: { + websocket: websocketData, + }, + }); + + this.logger.log(`WebSocket configuration set for instance ${instanceName}`); + return { websocket: websocketData }; + } catch (error) { + this.logger.error(`Failed to set WebSocket config for ${instanceName}:`, error); + throw error; + } + } +} +``` + +## Queue Integration Patterns + +### RabbitMQ Controller Implementation +```typescript +import amqp from 'amqplib'; + +export class RabbitmqController extends EventController { + private connection: amqp.Connection | null = null; + private channel: amqp.Channel | null = null; + + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + ) { + super(prismaRepository, configService, 'RabbitmqController'); + this.initializeConnection(); + } + + private async initializeConnection(): Promise { + try { + const rabbitmqConfig = this.configService.get('RABBITMQ'); + if (!rabbitmqConfig?.ENABLED) { + return; + } + + this.connection = await amqp.connect(rabbitmqConfig.URI); + this.channel = await this.connection.createChannel(); + + // Declare exchange for Evolution API events + await this.channel.assertExchange('evolution-events', 'topic', { durable: true }); + + this.logger.log('RabbitMQ connection established'); + } catch (error) { + this.logger.error('Failed to initialize RabbitMQ connection:', error); + } + } + + public async emit(data: EmitData): Promise { + if (!this.channel) { + return; + } + + try { + const instance = await this.getInstanceConfig(data.instanceName); + if (!instance?.rabbitmq?.enabled) { + return; + } + + const rabbitmqConfig = instance.rabbitmq; + + if (!this.shouldProcessEvent(data.event, rabbitmqConfig.events)) { + return; + } + + const payload = { + event: data.event, + instance: data.instanceName, + data: data.data, + timestamp: data.dateTime, + sender: data.sender, + }; + + const routingKey = `evolution.${data.instanceName}.${data.event.toLowerCase()}`; + + await this.channel.publish( + 'evolution-events', + routingKey, + Buffer.from(JSON.stringify(payload)), + { + persistent: true, + timestamp: Date.now(), + messageId: `${data.instanceName}-${Date.now()}`, + } + ); + + this.logger.log(`RabbitMQ message published for event ${data.event} to instance ${data.instanceName}`); + } catch (error) { + this.logger.error(`RabbitMQ emission failed for ${data.instanceName}:`, error); + } + } + + public async set(instanceName: string, data: any): Promise { + try { + const rabbitmqData = data.rabbitmq; + + await this.prismaRepository.instance.update({ + where: { name: instanceName }, + data: { + rabbitmq: rabbitmqData, + }, + }); + + this.logger.log(`RabbitMQ configuration set for instance ${instanceName}`); + return { rabbitmq: rabbitmqData }; + } catch (error) { + this.logger.error(`Failed to set RabbitMQ config for ${instanceName}:`, error); + throw error; + } + } +} +``` + +### SQS Controller Implementation +```typescript +import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'; + +export class SqsController extends EventController { + private sqsClient: SQSClient | null = null; + + constructor( + prismaRepository: PrismaRepository, + configService: ConfigService, + ) { + super(prismaRepository, configService, 'SqsController'); + this.initializeSQSClient(); + } + + private initializeSQSClient(): void { + try { + const sqsConfig = this.configService.get('SQS'); + if (!sqsConfig?.ENABLED) { + return; + } + + this.sqsClient = new SQSClient({ + region: sqsConfig.REGION, + credentials: { + accessKeyId: sqsConfig.ACCESS_KEY_ID, + secretAccessKey: sqsConfig.SECRET_ACCESS_KEY, + }, + }); + + this.logger.log('SQS client initialized'); + } catch (error) { + this.logger.error('Failed to initialize SQS client:', error); + } + } + + public async emit(data: EmitData): Promise { + if (!this.sqsClient) { + return; + } + + try { + const instance = await this.getInstanceConfig(data.instanceName); + if (!instance?.sqs?.enabled) { + return; + } + + const sqsConfig = instance.sqs; + + if (!this.shouldProcessEvent(data.event, sqsConfig.events)) { + return; + } + + const payload = { + event: data.event, + instance: data.instanceName, + data: data.data, + timestamp: data.dateTime, + sender: data.sender, + }; + + const command = new SendMessageCommand({ + QueueUrl: sqsConfig.queueUrl, + MessageBody: JSON.stringify(payload), + MessageAttributes: { + event: { + DataType: 'String', + StringValue: data.event, + }, + instance: { + DataType: 'String', + StringValue: data.instanceName, + }, + }, + MessageGroupId: data.instanceName, // For FIFO queues + MessageDeduplicationId: `${data.instanceName}-${Date.now()}`, // For FIFO queues + }); + + await this.sqsClient.send(command); + + this.logger.log(`SQS message sent for event ${data.event} to instance ${data.instanceName}`); + } catch (error) { + this.logger.error(`SQS emission failed for ${data.instanceName}:`, error); + } + } + + public async set(instanceName: string, data: any): Promise { + try { + const sqsData = data.sqs; + + await this.prismaRepository.instance.update({ + where: { name: instanceName }, + data: { + sqs: sqsData, + }, + }); + + this.logger.log(`SQS configuration set for instance ${instanceName}`); + return { sqs: sqsData }; + } catch (error) { + this.logger.error(`Failed to set SQS config for ${instanceName}:`, error); + throw error; + } + } +} +``` + +## Event DTO Pattern + +### Event Configuration DTO +```typescript +import { JsonValue } from '@prisma/client/runtime/library'; + +export class EventDto { + webhook?: { + enabled?: boolean; + events?: string[]; + url?: string; + headers?: JsonValue; + byEvents?: boolean; + base64?: boolean; + }; + + websocket?: { + enabled?: boolean; + events?: string[]; + }; + + sqs?: { + enabled?: boolean; + events?: string[]; + queueUrl?: string; + }; + + rabbitmq?: { + enabled?: boolean; + events?: string[]; + exchange?: string; + }; + + nats?: { + enabled?: boolean; + events?: string[]; + subject?: string; + }; + + pusher?: { + enabled?: boolean; + appId?: string; + key?: string; + secret?: string; + cluster?: string; + useTLS?: boolean; + events?: string[]; + }; +} +``` + +## Event Router Pattern + +### Event Router Structure +```typescript +import { NatsRouter } from '@api/integrations/event/nats/nats.router'; +import { PusherRouter } from '@api/integrations/event/pusher/pusher.router'; +import { RabbitmqRouter } from '@api/integrations/event/rabbitmq/rabbitmq.router'; +import { SqsRouter } from '@api/integrations/event/sqs/sqs.router'; +import { WebhookRouter } from '@api/integrations/event/webhook/webhook.router'; +import { WebsocketRouter } from '@api/integrations/event/websocket/websocket.router'; +import { Router } from 'express'; + +export class EventRouter { + public readonly router: Router; + + constructor(configService: any, ...guards: any[]) { + this.router = Router(); + + this.router.use('/webhook', new WebhookRouter(configService, ...guards).router); + this.router.use('/websocket', new WebsocketRouter(...guards).router); + this.router.use('/rabbitmq', new RabbitmqRouter(...guards).router); + this.router.use('/nats', new NatsRouter(...guards).router); + this.router.use('/pusher', new PusherRouter(...guards).router); + this.router.use('/sqs', new SqsRouter(...guards).router); + } +} +``` + +## Event Validation Schema + +### Event Configuration Validation +```typescript +import Joi from 'joi'; +import { EventController } from '@api/integrations/event/event.controller'; + +const eventListSchema = Joi.array().items( + Joi.string().valid(...EventController.events) +).optional(); + +export const webhookSchema = Joi.object({ + enabled: Joi.boolean().required(), + url: Joi.string().when('enabled', { + is: true, + then: Joi.required().uri({ scheme: ['http', 'https'] }), + otherwise: Joi.optional(), + }), + events: eventListSchema, + headers: Joi.object().pattern(Joi.string(), Joi.string()).optional(), + byEvents: Joi.boolean().optional().default(false), + base64: Joi.boolean().optional().default(false), +}).required(); + +export const websocketSchema = Joi.object({ + enabled: Joi.boolean().required(), + events: eventListSchema, +}).required(); + +export const rabbitmqSchema = Joi.object({ + enabled: Joi.boolean().required(), + events: eventListSchema, + exchange: Joi.string().optional().default('evolution-events'), +}).required(); + +export const sqsSchema = Joi.object({ + enabled: Joi.boolean().required(), + events: eventListSchema, + queueUrl: Joi.string().when('enabled', { + is: true, + then: Joi.required().uri(), + otherwise: Joi.optional(), + }), +}).required(); + +export const eventSchema = Joi.object({ + webhook: webhookSchema.optional(), + websocket: websocketSchema.optional(), + rabbitmq: rabbitmqSchema.optional(), + sqs: sqsSchema.optional(), + nats: Joi.object({ + enabled: Joi.boolean().required(), + events: eventListSchema, + subject: Joi.string().optional().default('evolution.events'), + }).optional(), + pusher: Joi.object({ + enabled: Joi.boolean().required(), + appId: Joi.string().when('enabled', { is: true, then: Joi.required() }), + key: Joi.string().when('enabled', { is: true, then: Joi.required() }), + secret: Joi.string().when('enabled', { is: true, then: Joi.required() }), + cluster: Joi.string().when('enabled', { is: true, then: Joi.required() }), + useTLS: Joi.boolean().optional().default(true), + events: eventListSchema, + }).optional(), +}).min(1).required(); +``` + +## Event Testing Pattern + +### Event Controller Testing +```typescript +describe('WebhookController', () => { + let controller: WebhookController; + let prismaRepository: jest.Mocked; + let configService: jest.Mocked; + + beforeEach(() => { + controller = new WebhookController(prismaRepository, configService); + }); + + describe('emit', () => { + it('should send webhook when enabled', async () => { + const mockInstance = { + webhook: { + enabled: true, + url: 'https://example.com/webhook', + events: ['MESSAGES_UPSERT'], + }, + }; + + prismaRepository.instance.findUnique.mockResolvedValue(mockInstance); + jest.spyOn(axios, 'post').mockResolvedValue({ status: 200 }); + + const eventData = { + instanceName: 'test-instance', + event: 'MESSAGES_UPSERT', + data: { message: 'test' }, + origin: 'test', + serverUrl: 'http://localhost', + dateTime: new Date().toISOString(), + sender: 'test', + }; + + await controller.emit(eventData); + + expect(axios.post).toHaveBeenCalledWith( + 'https://example.com/webhook', + expect.objectContaining({ + event: 'MESSAGES_UPSERT', + instance: 'test-instance', + }), + expect.objectContaining({ + headers: expect.objectContaining({ + 'Content-Type': 'application/json', + }), + }) + ); + }); + }); +}); +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/integration-storage-rules.mdc b/.cursor/rules/specialized-rules/integration-storage-rules.mdc new file mode 100644 index 000000000..6456f5a4b --- /dev/null +++ b/.cursor/rules/specialized-rules/integration-storage-rules.mdc @@ -0,0 +1,608 @@ +--- +description: Storage integration patterns for Evolution API +globs: + - "src/api/integrations/storage/**/*.ts" +alwaysApply: false +--- + +# Evolution API Storage Integration Rules + +## Storage Service Pattern + +### Base Storage Service Structure +```typescript +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; + +export class StorageService { + constructor(private readonly prismaRepository: PrismaRepository) {} + + private readonly logger = new Logger('StorageService'); + + public async getMedia(instance: InstanceDto, query?: MediaDto) { + try { + const where: any = { + instanceId: instance.instanceId, + ...query, + }; + + const media = await this.prismaRepository.media.findMany({ + where, + select: { + id: true, + fileName: true, + type: true, + mimetype: true, + createdAt: true, + Message: true, + }, + }); + + if (!media || media.length === 0) { + throw 'Media not found'; + } + + return media; + } catch (error) { + throw new BadRequestException(error); + } + } + + public async getMediaUrl(instance: InstanceDto, data: MediaDto) { + const media = (await this.getMedia(instance, { id: data.id }))[0]; + const mediaUrl = await this.generateUrl(media.fileName, data.expiry); + return { + mediaUrl, + ...media, + }; + } + + protected abstract generateUrl(fileName: string, expiry?: number): Promise; +} +``` + +## S3/MinIO Integration Pattern + +### MinIO Client Setup +```typescript +import { ConfigService, S3 } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import * as MinIo from 'minio'; +import { join } from 'path'; +import { Readable, Transform } from 'stream'; + +const logger = new Logger('S3 Service'); +const BUCKET = new ConfigService().get('S3'); + +interface Metadata extends MinIo.ItemBucketMetadata { + instanceId: string; + messageId?: string; +} + +const minioClient = (() => { + if (BUCKET?.ENABLE) { + return new MinIo.Client({ + endPoint: BUCKET.ENDPOINT, + port: BUCKET.PORT, + useSSL: BUCKET.USE_SSL, + accessKey: BUCKET.ACCESS_KEY, + secretKey: BUCKET.SECRET_KEY, + region: BUCKET.REGION, + }); + } +})(); + +const bucketName = process.env.S3_BUCKET; +``` + +### Bucket Management Functions +```typescript +const bucketExists = async (): Promise => { + if (minioClient) { + try { + const list = await minioClient.listBuckets(); + return !!list.find((bucket) => bucket.name === bucketName); + } catch (error) { + logger.error('Error checking bucket existence:', error); + return false; + } + } + return false; +}; + +const setBucketPolicy = async (): Promise => { + if (minioClient && bucketName) { + try { + const policy = { + Version: '2012-10-17', + Statement: [ + { + Effect: 'Allow', + Principal: { AWS: ['*'] }, + Action: ['s3:GetObject'], + Resource: [`arn:aws:s3:::${bucketName}/*`], + }, + ], + }; + + await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy)); + logger.log('Bucket policy set successfully'); + } catch (error) { + logger.error('Error setting bucket policy:', error); + } + } +}; + +const createBucket = async (): Promise => { + if (minioClient && bucketName) { + try { + const exists = await bucketExists(); + if (!exists) { + await minioClient.makeBucket(bucketName, BUCKET.REGION || 'us-east-1'); + await setBucketPolicy(); + logger.log(`Bucket ${bucketName} created successfully`); + } + } catch (error) { + logger.error('Error creating bucket:', error); + } + } +}; +``` + +### File Upload Functions +```typescript +export const uploadFile = async ( + fileName: string, + buffer: Buffer, + mimetype: string, + metadata?: Metadata, +): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + await createBucket(); + + const uploadMetadata = { + 'Content-Type': mimetype, + ...metadata, + }; + + await minioClient.putObject(bucketName, fileName, buffer, buffer.length, uploadMetadata); + + logger.log(`File ${fileName} uploaded successfully`); + return fileName; + } catch (error) { + logger.error(`Error uploading file ${fileName}:`, error); + throw new BadRequestException(`Failed to upload file: ${error.message}`); + } +}; + +export const uploadStream = async ( + fileName: string, + stream: Readable, + size: number, + mimetype: string, + metadata?: Metadata, +): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + await createBucket(); + + const uploadMetadata = { + 'Content-Type': mimetype, + ...metadata, + }; + + await minioClient.putObject(bucketName, fileName, stream, size, uploadMetadata); + + logger.log(`Stream ${fileName} uploaded successfully`); + return fileName; + } catch (error) { + logger.error(`Error uploading stream ${fileName}:`, error); + throw new BadRequestException(`Failed to upload stream: ${error.message}`); + } +}; +``` + +### File Download Functions +```typescript +export const getObject = async (fileName: string): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + const stream = await minioClient.getObject(bucketName, fileName); + const chunks: Buffer[] = []; + + return new Promise((resolve, reject) => { + stream.on('data', (chunk) => chunks.push(chunk)); + stream.on('end', () => resolve(Buffer.concat(chunks))); + stream.on('error', reject); + }); + } catch (error) { + logger.error(`Error getting object ${fileName}:`, error); + throw new BadRequestException(`Failed to get object: ${error.message}`); + } +}; + +export const getObjectUrl = async (fileName: string, expiry: number = 3600): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + const url = await minioClient.presignedGetObject(bucketName, fileName, expiry); + logger.log(`Generated URL for ${fileName} with expiry ${expiry}s`); + return url; + } catch (error) { + logger.error(`Error generating URL for ${fileName}:`, error); + throw new BadRequestException(`Failed to generate URL: ${error.message}`); + } +}; + +export const getObjectStream = async (fileName: string): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + const stream = await minioClient.getObject(bucketName, fileName); + return stream; + } catch (error) { + logger.error(`Error getting object stream ${fileName}:`, error); + throw new BadRequestException(`Failed to get object stream: ${error.message}`); + } +}; +``` + +### File Management Functions +```typescript +export const deleteObject = async (fileName: string): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + await minioClient.removeObject(bucketName, fileName); + logger.log(`File ${fileName} deleted successfully`); + } catch (error) { + logger.error(`Error deleting file ${fileName}:`, error); + throw new BadRequestException(`Failed to delete file: ${error.message}`); + } +}; + +export const listObjects = async (prefix?: string): Promise => { + if (!minioClient || !bucketName) { + throw new BadRequestException('S3 storage not configured'); + } + + try { + const objects: MinIo.BucketItem[] = []; + const stream = minioClient.listObjects(bucketName, prefix, true); + + return new Promise((resolve, reject) => { + stream.on('data', (obj) => objects.push(obj)); + stream.on('end', () => resolve(objects)); + stream.on('error', reject); + }); + } catch (error) { + logger.error('Error listing objects:', error); + throw new BadRequestException(`Failed to list objects: ${error.message}`); + } +}; + +export const objectExists = async (fileName: string): Promise => { + if (!minioClient || !bucketName) { + return false; + } + + try { + await minioClient.statObject(bucketName, fileName); + return true; + } catch (error) { + return false; + } +}; +``` + +## Storage Controller Pattern + +### S3 Controller Implementation +```typescript +import { InstanceDto } from '@api/dto/instance.dto'; +import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto'; +import { S3Service } from '@api/integrations/storage/s3/services/s3.service'; + +export class S3Controller { + constructor(private readonly s3Service: S3Service) {} + + public async getMedia(instance: InstanceDto, data: MediaDto) { + return this.s3Service.getMedia(instance, data); + } + + public async getMediaUrl(instance: InstanceDto, data: MediaDto) { + return this.s3Service.getMediaUrl(instance, data); + } + + public async uploadMedia(instance: InstanceDto, data: UploadMediaDto) { + return this.s3Service.uploadMedia(instance, data); + } + + public async deleteMedia(instance: InstanceDto, data: MediaDto) { + return this.s3Service.deleteMedia(instance, data); + } +} +``` + +## Storage Router Pattern + +### Storage Router Structure +```typescript +import { S3Router } from '@api/integrations/storage/s3/routes/s3.router'; +import { Router } from 'express'; + +export class StorageRouter { + public readonly router: Router; + + constructor(...guards: any[]) { + this.router = Router(); + + this.router.use('/s3', new S3Router(...guards).router); + // Add other storage providers here + // this.router.use('/gcs', new GCSRouter(...guards).router); + // this.router.use('/azure', new AzureRouter(...guards).router); + } +} +``` + +### S3 Specific Router +```typescript +import { RouterBroker } from '@api/abstract/abstract.router'; +import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto'; +import { s3Schema, s3UrlSchema } from '@api/integrations/storage/s3/validate/s3.schema'; +import { HttpStatus } from '@api/routes/index.router'; +import { s3Controller } from '@api/server.module'; +import { RequestHandler, Router } from 'express'; + +export class S3Router extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('getMedia'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: s3Schema, + ClassRef: MediaDto, + execute: (instance, data) => s3Controller.getMedia(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('getMediaUrl'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: s3UrlSchema, + ClassRef: MediaDto, + execute: (instance, data) => s3Controller.getMediaUrl(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('uploadMedia'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: uploadSchema, + ClassRef: UploadMediaDto, + execute: (instance, data) => s3Controller.uploadMedia(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .delete(this.routerPath('deleteMedia'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: s3Schema, + ClassRef: MediaDto, + execute: (instance, data) => s3Controller.deleteMedia(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} +``` + +## Storage DTO Pattern + +### Media DTO +```typescript +export class MediaDto { + id?: string; + fileName?: string; + type?: string; + mimetype?: string; + expiry?: number; +} + +export class UploadMediaDto { + fileName: string; + mimetype: string; + buffer?: Buffer; + base64?: string; + url?: string; + metadata?: { + instanceId: string; + messageId?: string; + contactId?: string; + [key: string]: any; + }; +} +``` + +## Storage Validation Schema + +### S3 Validation Schemas +```typescript +import Joi from 'joi'; + +export const s3Schema = Joi.object({ + id: Joi.string().optional(), + fileName: Joi.string().optional(), + type: Joi.string().optional().valid('image', 'video', 'audio', 'document'), + mimetype: Joi.string().optional(), + expiry: Joi.number().optional().min(60).max(604800).default(3600), // 1 min to 7 days +}).min(1).required(); + +export const s3UrlSchema = Joi.object({ + id: Joi.string().required(), + expiry: Joi.number().optional().min(60).max(604800).default(3600), +}).required(); + +export const uploadSchema = Joi.object({ + fileName: Joi.string().required().max(255), + mimetype: Joi.string().required(), + buffer: Joi.binary().optional(), + base64: Joi.string().base64().optional(), + url: Joi.string().uri().optional(), + metadata: Joi.object({ + instanceId: Joi.string().required(), + messageId: Joi.string().optional(), + contactId: Joi.string().optional(), + }).optional(), +}).xor('buffer', 'base64', 'url').required(); // Exactly one of these must be present +``` + +## Error Handling in Storage + +### Storage-Specific Error Handling +```typescript +// CORRECT - Storage-specific error handling +public async uploadFile(fileName: string, buffer: Buffer): Promise { + try { + const result = await this.storageClient.upload(fileName, buffer); + return result; + } catch (error) { + this.logger.error(`Storage upload failed: ${error.message}`); + + if (error.code === 'NoSuchBucket') { + throw new BadRequestException('Storage bucket not found'); + } + + if (error.code === 'AccessDenied') { + throw new UnauthorizedException('Storage access denied'); + } + + if (error.code === 'EntityTooLarge') { + throw new BadRequestException('File too large'); + } + + throw new InternalServerErrorException('Storage operation failed'); + } +} +``` + +## Storage Configuration Pattern + +### Environment Configuration +```typescript +export interface S3Config { + ENABLE: boolean; + ENDPOINT: string; + PORT: number; + USE_SSL: boolean; + ACCESS_KEY: string; + SECRET_KEY: string; + REGION: string; + BUCKET: string; +} + +// Usage in service +const s3Config = this.configService.get('S3'); +if (!s3Config.ENABLE) { + throw new BadRequestException('S3 storage is disabled'); +} +``` + +## Storage Testing Pattern + +### Storage Service Testing +```typescript +describe('S3Service', () => { + let service: S3Service; + let prismaRepository: jest.Mocked; + + beforeEach(() => { + service = new S3Service(prismaRepository); + }); + + describe('getMedia', () => { + it('should return media list', async () => { + const instance = { instanceId: 'test-instance' }; + const mockMedia = [ + { id: '1', fileName: 'test.jpg', type: 'image', mimetype: 'image/jpeg' }, + ]; + + prismaRepository.media.findMany.mockResolvedValue(mockMedia); + + const result = await service.getMedia(instance); + + expect(result).toEqual(mockMedia); + expect(prismaRepository.media.findMany).toHaveBeenCalledWith({ + where: { instanceId: 'test-instance' }, + select: expect.objectContaining({ + id: true, + fileName: true, + type: true, + mimetype: true, + }), + }); + }); + + it('should throw error when no media found', async () => { + const instance = { instanceId: 'test-instance' }; + prismaRepository.media.findMany.mockResolvedValue([]); + + await expect(service.getMedia(instance)).rejects.toThrow(BadRequestException); + }); + }); +}); +``` + +## Storage Performance Considerations + +### Efficient File Handling +```typescript +// CORRECT - Stream-based upload for large files +public async uploadLargeFile(fileName: string, stream: Readable, size: number): Promise { + const uploadStream = new Transform({ + transform(chunk, encoding, callback) { + // Optional: Add compression, encryption, etc. + callback(null, chunk); + }, + }); + + return new Promise((resolve, reject) => { + stream + .pipe(uploadStream) + .on('error', reject) + .on('finish', () => resolve(fileName)); + }); +} + +// INCORRECT - Loading entire file into memory +public async uploadLargeFile(fileName: string, filePath: string): Promise { + const buffer = fs.readFileSync(filePath); // ❌ Memory intensive for large files + return await this.uploadFile(fileName, buffer); +} +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/route-rules.mdc b/.cursor/rules/specialized-rules/route-rules.mdc new file mode 100644 index 000000000..7be40849c --- /dev/null +++ b/.cursor/rules/specialized-rules/route-rules.mdc @@ -0,0 +1,416 @@ +--- +description: Router patterns for Evolution API +globs: + - "src/api/routes/**/*.ts" +alwaysApply: false +--- + +# Evolution API Route Rules + +## Router Base Pattern + +### RouterBroker Extension +```typescript +import { RouterBroker } from '@api/abstract/abstract.router'; +import { RequestHandler, Router } from 'express'; +import { HttpStatus } from './index.router'; + +export class ExampleRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .get(this.routerPath('findExample'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: null, + ClassRef: ExampleDto, + execute: (instance) => exampleController.find(instance), + }); + + return res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('createExample'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: exampleSchema, + ClassRef: ExampleDto, + execute: (instance, data) => exampleController.create(instance, data), + }); + + return res.status(HttpStatus.CREATED).json(response); + }); + } + + public readonly router: Router = Router(); +} +``` + +## Main Router Pattern + +### Index Router Structure +```typescript +import { Router } from 'express'; +import { authGuard } from '@api/guards/auth.guard'; +import { instanceExistsGuard, instanceLoggedGuard } from '@api/guards/instance.guard'; +import Telemetry from '@api/guards/telemetry.guard'; + +enum HttpStatus { + OK = 200, + CREATED = 201, + NOT_FOUND = 404, + FORBIDDEN = 403, + BAD_REQUEST = 400, + UNAUTHORIZED = 401, + INTERNAL_SERVER_ERROR = 500, +} + +const router: Router = Router(); +const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']]; +const telemetry = new Telemetry(); + +router + .use((req, res, next) => telemetry.collectTelemetry(req, res, next)) + .get('/', async (req, res) => { + res.status(HttpStatus.OK).json({ + status: HttpStatus.OK, + message: 'Welcome to the Evolution API, it is working!', + version: packageJson.version, + clientName: process.env.DATABASE_CONNECTION_CLIENT_NAME, + manager: !serverConfig.DISABLE_MANAGER ? `${req.protocol}://${req.get('host')}/manager` : undefined, + documentation: `https://doc.evolution-api.com`, + whatsappWebVersion: (await fetchLatestWaWebVersion({})).version.join('.'), + }); + }) + .use('/instance', new InstanceRouter(configService, ...guards).router) + .use('/message', new MessageRouter(...guards).router) + .use('/chat', new ChatRouter(...guards).router) + .use('/business', new BusinessRouter(...guards).router); + +export { HttpStatus, router }; +``` + +## Data Validation Pattern + +### RouterBroker dataValidate Usage +```typescript +// CORRECT - Standard validation pattern +.post(this.routerPath('createTemplate'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: templateSchema, + ClassRef: TemplateDto, + execute: (instance, data) => templateController.create(instance, data), + }); + + return res.status(HttpStatus.CREATED).json(response); +}) + +// CORRECT - No schema validation (for simple DTOs) +.get(this.routerPath('findTemplate'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: null, + ClassRef: InstanceDto, + execute: (instance) => templateController.find(instance), + }); + + return res.status(HttpStatus.OK).json(response); +}) +``` + +## Error Handling in Routes + +### Try-Catch Pattern +```typescript +// CORRECT - Error handling with utility function +.post(this.routerPath('getCatalog'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: catalogSchema, + ClassRef: NumberDto, + execute: (instance, data) => businessController.fetchCatalog(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + } catch (error) { + // Log error for debugging + console.error('Business catalog error:', error); + + // Use utility function to create standardized error response + const errorResponse = createMetaErrorResponse(error, 'business_catalog'); + return res.status(errorResponse.status).json(errorResponse); + } +}) + +// INCORRECT - Let RouterBroker handle errors (when possible) +.post(this.routerPath('simpleOperation'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: simpleSchema, + ClassRef: SimpleDto, + execute: (instance, data) => controller.simpleOperation(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + } catch (error) { + throw error; // ❌ Unnecessary - RouterBroker handles this + } +}) +``` + +## Route Path Pattern + +### routerPath Usage +```typescript +// CORRECT - Use routerPath for consistent naming +.get(this.routerPath('findLabels'), ...guards, async (req, res) => { + // Implementation +}) +.post(this.routerPath('handleLabel'), ...guards, async (req, res) => { + // Implementation +}) + +// INCORRECT - Hardcoded paths +.get('/labels', ...guards, async (req, res) => { // ❌ Use routerPath + // Implementation +}) +``` + +## Guard Application Pattern + +### Guards Usage +```typescript +// CORRECT - Apply guards to protected routes +export class ProtectedRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .get(this.routerPath('protectedAction'), ...guards, async (req, res) => { + // Protected action + }) + .post(this.routerPath('anotherAction'), ...guards, async (req, res) => { + // Another protected action + }); + } +} + +// CORRECT - No guards for public routes +export class PublicRouter extends RouterBroker { + constructor() { + super(); + this.router + .get('/health', async (req, res) => { + res.status(HttpStatus.OK).json({ status: 'healthy' }); + }) + .get('/version', async (req, res) => { + res.status(HttpStatus.OK).json({ version: packageJson.version }); + }); + } +} +``` + +## Static File Serving Pattern + +### Static Assets Route +```typescript +// CORRECT - Secure static file serving +router.get('/assets/*', (req, res) => { + const fileName = req.params[0]; + + // Security: Reject paths containing traversal patterns + if (!fileName || fileName.includes('..') || fileName.includes('\\') || path.isAbsolute(fileName)) { + return res.status(403).send('Forbidden'); + } + + const basePath = path.join(process.cwd(), 'manager', 'dist'); + const assetsPath = path.join(basePath, 'assets'); + const filePath = path.join(assetsPath, fileName); + + // Security: Ensure the resolved path is within the assets directory + const resolvedPath = path.resolve(filePath); + const resolvedAssetsPath = path.resolve(assetsPath); + + if (!resolvedPath.startsWith(resolvedAssetsPath + path.sep) && resolvedPath !== resolvedAssetsPath) { + return res.status(403).send('Forbidden'); + } + + if (fs.existsSync(resolvedPath)) { + res.set('Content-Type', mimeTypes.lookup(resolvedPath) || 'text/css'); + res.send(fs.readFileSync(resolvedPath)); + } else { + res.status(404).send('File not found'); + } +}); +``` + +## Special Route Patterns + +### Manager Route Pattern +```typescript +export class ViewsRouter extends RouterBroker { + public readonly router: Router; + + constructor() { + super(); + this.router = Router(); + + const basePath = path.join(process.cwd(), 'manager', 'dist'); + const indexPath = path.join(basePath, 'index.html'); + + this.router.use(express.static(basePath)); + + this.router.get('*', (req, res) => { + res.sendFile(indexPath); + }); + } +} +``` + +### Webhook Route Pattern +```typescript +// CORRECT - Webhook without guards +.post('/webhook/evolution', async (req, res) => { + const response = await evolutionController.receiveWebhook(req.body); + return res.status(HttpStatus.OK).json(response); +}) + +// CORRECT - Webhook with signature validation +.post('/webhook/meta', validateWebhookSignature, async (req, res) => { + const response = await metaController.receiveWebhook(req.body); + return res.status(HttpStatus.OK).json(response); +}) +``` + +## Response Pattern + +### Standard Response Format +```typescript +// CORRECT - Standard success response +return res.status(HttpStatus.OK).json(response); + +// CORRECT - Created response +return res.status(HttpStatus.CREATED).json(response); + +// CORRECT - Custom response with additional data +return res.status(HttpStatus.OK).json({ + ...response, + timestamp: new Date().toISOString(), + instanceName: req.params.instanceName, +}); +``` + +## Route Organization + +### File Structure +``` +src/api/routes/ +├── index.router.ts # Main router with all route registrations +├── instance.router.ts # Instance management routes +├── sendMessage.router.ts # Message sending routes +├── chat.router.ts # Chat operations routes +├── business.router.ts # Business API routes +├── group.router.ts # Group management routes +├── label.router.ts # Label management routes +├── proxy.router.ts # Proxy configuration routes +├── settings.router.ts # Instance settings routes +├── template.router.ts # Template management routes +├── call.router.ts # Call operations routes +└── view.router.ts # Frontend views routes +``` + +## Route Testing Pattern + +### Router Testing +```typescript +describe('ExampleRouter', () => { + let app: express.Application; + let router: ExampleRouter; + + beforeEach(() => { + app = express(); + router = new ExampleRouter(); + app.use('/api', router.router); + app.use(express.json()); + }); + + describe('GET /findExample', () => { + it('should return example data', async () => { + const response = await request(app) + .get('/api/findExample/test-instance') + .set('apikey', 'test-key') + .expect(200); + + expect(response.body).toBeDefined(); + expect(response.body.instanceName).toBe('test-instance'); + }); + + it('should return 401 without API key', async () => { + await request(app) + .get('/api/findExample/test-instance') + .expect(401); + }); + }); + + describe('POST /createExample', () => { + it('should create example successfully', async () => { + const data = { + name: 'Test Example', + description: 'Test Description', + }; + + const response = await request(app) + .post('/api/createExample/test-instance') + .set('apikey', 'test-key') + .send(data) + .expect(201); + + expect(response.body.name).toBe(data.name); + }); + + it('should validate required fields', async () => { + const data = { + description: 'Test Description', + // Missing required 'name' field + }; + + await request(app) + .post('/api/createExample/test-instance') + .set('apikey', 'test-key') + .send(data) + .expect(400); + }); + }); +}); +``` + +## Route Documentation + +### JSDoc for Routes +```typescript +/** + * @route GET /api/template/findTemplate/:instanceName + * @description Find template for instance + * @param {string} instanceName - Instance name + * @returns {TemplateDto} Template data + * @throws {404} Template not found + * @throws {401} Unauthorized + */ +.get(this.routerPath('findTemplate'), ...guards, async (req, res) => { + // Implementation +}) + +/** + * @route POST /api/template/createTemplate/:instanceName + * @description Create new template + * @param {string} instanceName - Instance name + * @body {TemplateDto} Template data + * @returns {TemplateDto} Created template + * @throws {400} Validation error + * @throws {401} Unauthorized + */ +.post(this.routerPath('createTemplate'), ...guards, async (req, res) => { + // Implementation +}) +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/service-rules.mdc b/.cursor/rules/specialized-rules/service-rules.mdc new file mode 100644 index 000000000..0f516c555 --- /dev/null +++ b/.cursor/rules/specialized-rules/service-rules.mdc @@ -0,0 +1,294 @@ +--- +description: Service layer patterns for Evolution API +globs: + - "src/api/services/**/*.ts" + - "src/api/integrations/**/services/*.ts" +alwaysApply: false +--- + +# Evolution API Service Rules + +## Service Structure Pattern + +### Standard Service Class +```typescript +export class ExampleService { + constructor(private readonly waMonitor: WAMonitoringService) {} + + private readonly logger = new Logger('ExampleService'); + + public async create(instance: InstanceDto, data: ExampleDto) { + await this.waMonitor.waInstances[instance.instanceName].setData(data); + return { example: { ...instance, data } }; + } + + public async find(instance: InstanceDto): Promise { + try { + const result = await this.waMonitor.waInstances[instance.instanceName].findData(); + + if (Object.keys(result).length === 0) { + throw new Error('Data not found'); + } + + return result; + } catch (error) { + return null; // Evolution pattern - return null on error + } + } +} +``` + +## Dependency Injection Pattern + +### Constructor Pattern +```typescript +// CORRECT - Evolution API pattern +constructor( + private readonly waMonitor: WAMonitoringService, + private readonly prismaRepository: PrismaRepository, + private readonly configService: ConfigService, +) {} + +// INCORRECT - Don't use +constructor(waMonitor, prismaRepository, configService) {} // ❌ No types +``` + +## Logger Pattern + +### Standard Logger Usage +```typescript +// CORRECT - Evolution API pattern +private readonly logger = new Logger('ServiceName'); + +// Usage +this.logger.log('Operation started'); +this.logger.error('Operation failed', error); + +// INCORRECT +console.log('Operation started'); // ❌ Use Logger +``` + +## WAMonitor Integration Pattern + +### Instance Access Pattern +```typescript +// CORRECT - Standard pattern +public async operation(instance: InstanceDto, data: DataDto) { + await this.waMonitor.waInstances[instance.instanceName].performAction(data); + return { result: { ...instance, data } }; +} + +// Instance validation +const waInstance = this.waMonitor.waInstances[instance.instanceName]; +if (!waInstance) { + throw new NotFoundException('Instance not found'); +} +``` + +## Error Handling Pattern + +### Try-Catch Pattern +```typescript +// CORRECT - Evolution API pattern +public async find(instance: InstanceDto): Promise { + try { + const result = await this.waMonitor.waInstances[instance.instanceName].findData(); + + if (Object.keys(result).length === 0) { + throw new Error('Data not found'); + } + + return result; + } catch (error) { + this.logger.error('Find operation failed', error); + return null; // Return null on error (Evolution pattern) + } +} +``` + +## Cache Integration Pattern + +### Cache Service Usage +```typescript +export class CacheAwareService { + constructor( + private readonly cache: CacheService, + private readonly chatwootCache: CacheService, + private readonly baileysCache: CacheService, + ) {} + + public async getCachedData(key: string): Promise { + const cached = await this.cache.get(key); + if (cached) return cached; + + const data = await this.fetchFromSource(key); + await this.cache.set(key, data, 300); // 5 min TTL + return data; + } +} +``` + +## Integration Service Patterns + +### Chatbot Service Base Pattern +```typescript +export class ChatbotService extends BaseChatbotService { + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + ) { + super(waMonitor, prismaRepository, 'ChatbotService', configService); + } + + protected async processBot( + waInstance: any, + remoteJid: string, + bot: BotType, + session: any, + settings: any, + content: string, + ): Promise { + // Implementation + } +} +``` + +### Channel Service Pattern +```typescript +export class ChannelService extends ChannelStartupService { + constructor( + configService: ConfigService, + eventEmitter: EventEmitter2, + prismaRepository: PrismaRepository, + cache: CacheService, + chatwootCache: CacheService, + baileysCache: CacheService, + ) { + super(configService, eventEmitter, prismaRepository, cache, chatwootCache, baileysCache); + } + + public readonly logger = new Logger('ChannelService'); + public client: WASocket; + public readonly instance: wa.Instance = {}; +} +``` + +## Service Initialization Pattern + +### Service Registration +```typescript +// In server.module.ts pattern +export const templateService = new TemplateService( + waMonitor, + prismaRepository, + configService, +); + +export const settingsService = new SettingsService(waMonitor); +``` + +## Async Operation Patterns + +### Promise Handling +```typescript +// CORRECT - Evolution API pattern +public async sendMessage(instance: InstanceDto, data: MessageDto) { + const waInstance = this.waMonitor.waInstances[instance.instanceName]; + return await waInstance.sendMessage(data); +} + +// INCORRECT - Don't use .then() +public sendMessage(instance: InstanceDto, data: MessageDto) { + return this.waMonitor.waInstances[instance.instanceName] + .sendMessage(data) + .then(result => result); // ❌ Use async/await +} +``` + +## Configuration Access Pattern + +### Config Service Usage +```typescript +// CORRECT - Evolution API pattern +const serverConfig = this.configService.get('SERVER'); +const authConfig = this.configService.get('AUTHENTICATION'); +const dbConfig = this.configService.get('DATABASE'); + +// Type-safe configuration access +if (this.configService.get('CHATWOOT').ENABLED) { + // Chatwoot logic +} +``` + +## Event Emission Pattern + +### EventEmitter2 Usage +```typescript +// CORRECT - Evolution API pattern +this.eventEmitter.emit(Events.INSTANCE_CREATE, { + instanceName: instance.name, + status: 'created', +}); + +// Chatwoot event pattern +if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + this.chatwootService.eventWhatsapp( + Events.STATUS_INSTANCE, + { instanceName: this.instance.name }, + { + instance: this.instance.name, + status: 'created', + }, + ); +} +``` + +## Service Method Naming + +### Standard Method Names +- `create()` - Create new resource +- `find()` - Find single resource +- `findAll()` - Find multiple resources +- `update()` - Update resource +- `delete()` - Delete resource +- `fetch*()` - Fetch from external API +- `send*()` - Send data/messages +- `process*()` - Process data + +## Service Testing Pattern + +### Unit Test Structure +```typescript +describe('ExampleService', () => { + let service: ExampleService; + let waMonitor: jest.Mocked; + let prismaRepository: jest.Mocked; + + beforeEach(() => { + const mockWaMonitor = { + waInstances: { + 'test-instance': { + performAction: jest.fn(), + }, + }, + }; + + service = new ExampleService( + mockWaMonitor as any, + prismaRepository, + configService, + ); + }); + + it('should perform action successfully', async () => { + const instance = { instanceName: 'test-instance' }; + const data = { test: 'data' }; + + const result = await service.create(instance, data); + + expect(result).toBeDefined(); + expect(waMonitor.waInstances['test-instance'].performAction).toHaveBeenCalledWith(data); + }); +}); +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/type-rules.mdc b/.cursor/rules/specialized-rules/type-rules.mdc new file mode 100644 index 000000000..cf7400674 --- /dev/null +++ b/.cursor/rules/specialized-rules/type-rules.mdc @@ -0,0 +1,490 @@ +--- +description: Type definitions and interfaces for Evolution API +globs: + - "src/api/types/**/*.ts" + - "src/@types/**/*.ts" +alwaysApply: false +--- + +# Evolution API Type Rules + +## Namespace Pattern + +### WhatsApp Types Namespace +```typescript +/* eslint-disable @typescript-eslint/no-namespace */ +import { JsonValue } from '@prisma/client/runtime/library'; +import { AuthenticationState, WAConnectionState } from 'baileys'; + +export declare namespace wa { + export type QrCode = { + count?: number; + pairingCode?: string; + base64?: string; + code?: string; + }; + + export type Instance = { + id?: string; + qrcode?: QrCode; + pairingCode?: string; + authState?: { state: AuthenticationState; saveCreds: () => void }; + name?: string; + wuid?: string; + profileName?: string; + profilePictureUrl?: string; + token?: string; + number?: string; + integration?: string; + businessId?: string; + }; + + export type LocalChatwoot = { + enabled?: boolean; + accountId?: string; + token?: string; + url?: string; + nameInbox?: string; + mergeBrazilContacts?: boolean; + importContacts?: boolean; + importMessages?: boolean; + daysLimitImportMessages?: number; + organization?: string; + logo?: string; + }; + + export type LocalProxy = { + enabled?: boolean; + host?: string; + port?: string; + protocol?: string; + username?: string; + password?: string; + }; + + export type LocalSettings = { + rejectCall?: boolean; + msgCall?: string; + groupsIgnore?: boolean; + alwaysOnline?: boolean; + readMessages?: boolean; + readStatus?: boolean; + syncFullHistory?: boolean; + }; + + export type LocalWebHook = { + enabled?: boolean; + url?: string; + events?: string[]; + headers?: JsonValue; + byEvents?: boolean; + base64?: boolean; + }; + + export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED'; +} +``` + +## Enum Definitions + +### Events Enum +```typescript +export enum Events { + APPLICATION_STARTUP = 'application.startup', + INSTANCE_CREATE = 'instance.create', + INSTANCE_DELETE = 'instance.delete', + QRCODE_UPDATED = 'qrcode.updated', + CONNECTION_UPDATE = 'connection.update', + STATUS_INSTANCE = 'status.instance', + MESSAGES_SET = 'messages.set', + MESSAGES_UPSERT = 'messages.upsert', + MESSAGES_EDITED = 'messages.edited', + MESSAGES_UPDATE = 'messages.update', + MESSAGES_DELETE = 'messages.delete', + SEND_MESSAGE = 'send.message', + SEND_MESSAGE_UPDATE = 'send.message.update', + CONTACTS_SET = 'contacts.set', + CONTACTS_UPSERT = 'contacts.upsert', + CONTACTS_UPDATE = 'contacts.update', + PRESENCE_UPDATE = 'presence.update', + CHATS_SET = 'chats.set', + CHATS_UPDATE = 'chats.update', + CHATS_UPSERT = 'chats.upsert', + CHATS_DELETE = 'chats.delete', + GROUPS_UPSERT = 'groups.upsert', + GROUPS_UPDATE = 'groups.update', + GROUP_PARTICIPANTS_UPDATE = 'group-participants.update', + CALL = 'call', + TYPEBOT_START = 'typebot.start', + TYPEBOT_CHANGE_STATUS = 'typebot.change-status', + LABELS_EDIT = 'labels.edit', + LABELS_ASSOCIATION = 'labels.association', + CREDS_UPDATE = 'creds.update', + MESSAGING_HISTORY_SET = 'messaging-history.set', + REMOVE_INSTANCE = 'remove.instance', + LOGOUT_INSTANCE = 'logout.instance', +} +``` + +### Integration Types +```typescript +export const Integration = { + WHATSAPP_BUSINESS: 'WHATSAPP-BUSINESS', + WHATSAPP_BAILEYS: 'WHATSAPP-BAILEYS', + EVOLUTION: 'EVOLUTION', +} as const; + +export type IntegrationType = typeof Integration[keyof typeof Integration]; +``` + +## Constant Arrays + +### Message Type Constants +```typescript +export const TypeMediaMessage = [ + 'imageMessage', + 'documentMessage', + 'audioMessage', + 'videoMessage', + 'stickerMessage', + 'ptvMessage', // Evolution API includes this +]; + +export const MessageSubtype = [ + 'ephemeralMessage', + 'documentWithCaptionMessage', + 'viewOnceMessage', + 'viewOnceMessageV2', +]; + +export type MediaMessageType = typeof TypeMediaMessage[number]; +export type MessageSubtypeType = typeof MessageSubtype[number]; +``` + +## Interface Definitions + +### Service Interfaces +```typescript +export interface ServiceInterface { + create(instance: InstanceDto, data: any): Promise; + find(instance: InstanceDto): Promise; + update?(instance: InstanceDto, data: any): Promise; + delete?(instance: InstanceDto): Promise; +} + +export interface ChannelServiceInterface extends ServiceInterface { + sendMessage(data: SendMessageDto): Promise; + connectToWhatsapp(data?: any): Promise; + receiveWebhook?(data: any): Promise; +} + +export interface ChatbotServiceInterface extends ServiceInterface { + processMessage( + instanceName: string, + remoteJid: string, + message: any, + pushName?: string, + ): Promise; +} +``` + +## Configuration Types + +### Environment Configuration Types +```typescript +export interface DatabaseConfig { + CONNECTION: { + URI: string; + DB_PREFIX_NAME: string; + CLIENT_NAME?: string; + }; + ENABLED: boolean; + SAVE_DATA: { + INSTANCE: boolean; + NEW_MESSAGE: boolean; + MESSAGE_UPDATE: boolean; + CONTACTS: boolean; + CHATS: boolean; + }; +} + +export interface AuthConfig { + TYPE: 'apikey' | 'jwt'; + API_KEY: { + KEY: string; + }; + JWT?: { + EXPIRIN_IN: number; + SECRET: string; + }; +} + +export interface CacheConfig { + REDIS: { + ENABLED: boolean; + URI: string; + PREFIX_KEY: string; + SAVE_INSTANCES: boolean; + }; + LOCAL: { + ENABLED: boolean; + TTL: number; + }; +} +``` + +## Message Types + +### Message Structure Types +```typescript +export interface MessageContent { + text?: string; + caption?: string; + media?: Buffer | string; + mediatype?: 'image' | 'video' | 'audio' | 'document' | 'sticker'; + fileName?: string; + mimetype?: string; +} + +export interface MessageOptions { + delay?: number; + presence?: 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'; + linkPreview?: boolean; + mentionsEveryOne?: boolean; + mentioned?: string[]; + quoted?: { + key: { + remoteJid: string; + fromMe: boolean; + id: string; + }; + message: any; + }; +} + +export interface SendMessageRequest { + number: string; + content: MessageContent; + options?: MessageOptions; +} +``` + +## Webhook Types + +### Webhook Payload Types +```typescript +export interface WebhookPayload { + event: Events; + instance: string; + data: any; + timestamp: string; + server?: { + version: string; + host: string; + }; +} + +export interface WebhookConfig { + enabled: boolean; + url: string; + events: Events[]; + headers?: Record; + byEvents?: boolean; + base64?: boolean; +} +``` + +## Error Types + +### Custom Error Types +```typescript +export interface ApiError { + status: number; + message: string; + error?: string; + details?: any; + timestamp: string; + path: string; +} + +export interface ValidationError extends ApiError { + status: 400; + validationErrors: Array<{ + field: string; + message: string; + value?: any; + }>; +} + +export interface AuthenticationError extends ApiError { + status: 401; + message: 'Unauthorized' | 'Invalid API Key' | 'Token Expired'; +} +``` + +## Utility Types + +### Generic Utility Types +```typescript +export type Optional = Omit & Partial>; + +export type RequiredFields = T & Required>; + +export type DeepPartial = { + [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; +}; + +export type NonEmptyArray = [T, ...T[]]; + +export type StringKeys = { + [K in keyof T]: T[K] extends string ? K : never; +}[keyof T]; +``` + +## Response Types + +### API Response Types +```typescript +export interface ApiResponse { + success: boolean; + data?: T; + message?: string; + error?: string; + timestamp: string; +} + +export interface PaginatedResponse extends ApiResponse { + pagination: { + page: number; + limit: number; + total: number; + totalPages: number; + hasNext: boolean; + hasPrev: boolean; + }; +} + +export interface InstanceResponse extends ApiResponse { + instance: { + instanceName: string; + status: 'connecting' | 'open' | 'close' | 'qr'; + qrcode?: string; + profileName?: string; + profilePicUrl?: string; + }; +} +``` + +## Integration-Specific Types + +### Baileys Types Extension +```typescript +import { WASocket, ConnectionState, DisconnectReason } from 'baileys'; + +export interface BaileysInstance { + client: WASocket; + state: ConnectionState; + qrRetry: number; + authPath: string; +} + +export interface BaileysConfig { + qrTimeout: number; + maxQrRetries: number; + authTimeout: number; + reconnectInterval: number; +} +``` + +### Business API Types +```typescript +export interface BusinessApiConfig { + version: string; + baseUrl: string; + timeout: number; + retries: number; +} + +export interface BusinessApiMessage { + messaging_product: 'whatsapp'; + to: string; + type: 'text' | 'image' | 'document' | 'audio' | 'video' | 'template'; + text?: { + body: string; + preview_url?: boolean; + }; + image?: { + link?: string; + id?: string; + caption?: string; + }; + template?: { + name: string; + language: { + code: string; + }; + components?: any[]; + }; +} +``` + +## Type Guards + +### Type Guard Functions +```typescript +export function isMediaMessage(message: any): message is MediaMessage { + return message && TypeMediaMessage.some(type => message[type]); +} + +export function isTextMessage(message: any): message is TextMessage { + return message && message.conversation; +} + +export function isValidIntegration(integration: string): integration is IntegrationType { + return Object.values(Integration).includes(integration as IntegrationType); +} + +export function isValidEvent(event: string): event is Events { + return Object.values(Events).includes(event as Events); +} +``` + +## Module Augmentation + +### Express Request Extension +```typescript +declare global { + namespace Express { + interface Request { + instanceName?: string; + instanceData?: InstanceDto; + user?: { + id: string; + apiKey: string; + }; + } + } +} +``` + +## Type Documentation + +### JSDoc Type Documentation +```typescript +/** + * WhatsApp instance configuration + * @interface InstanceConfig + * @property {string} name - Unique instance name + * @property {IntegrationType} integration - Integration type + * @property {string} [token] - API token for business integrations + * @property {WebhookConfig} [webhook] - Webhook configuration + * @property {ProxyConfig} [proxy] - Proxy configuration + */ +export interface InstanceConfig { + name: string; + integration: IntegrationType; + token?: string; + webhook?: WebhookConfig; + proxy?: ProxyConfig; +} +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/util-rules.mdc b/.cursor/rules/specialized-rules/util-rules.mdc new file mode 100644 index 000000000..6bcf7dd16 --- /dev/null +++ b/.cursor/rules/specialized-rules/util-rules.mdc @@ -0,0 +1,653 @@ +--- +description: Utility functions and helpers for Evolution API +globs: + - "src/utils/**/*.ts" +alwaysApply: false +--- + +# Evolution API Utility Rules + +## Utility Function Structure + +### Standard Utility Pattern +```typescript +import { Logger } from '@config/logger.config'; + +const logger = new Logger('UtilityName'); + +export function utilityFunction(param: ParamType): ReturnType { + try { + // Utility logic + return result; + } catch (error) { + logger.error(`Utility function failed: ${error.message}`); + throw error; + } +} + +export default utilityFunction; +``` + +## Authentication Utilities + +### Multi-File Auth State Pattern +```typescript +import { AuthenticationState } from 'baileys'; +import { CacheService } from '@api/services/cache.service'; +import fs from 'fs/promises'; +import path from 'path'; + +export default async function useMultiFileAuthStatePrisma( + sessionId: string, + cache: CacheService, +): Promise<{ + state: AuthenticationState; + saveCreds: () => Promise; +}> { + const localFolder = path.join(INSTANCE_DIR, sessionId); + const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json'); + await fs.mkdir(localFolder, { recursive: true }); + + async function writeData(data: any, key: string): Promise { + const dataString = JSON.stringify(data, BufferJSON.replacer); + + if (key !== 'creds') { + if (process.env.CACHE_REDIS_ENABLED === 'true') { + return await cache.hSet(sessionId, key, data); + } else { + await fs.writeFile(localFile(key), dataString); + return; + } + } + await saveKey(sessionId, dataString); + return; + } + + async function readData(key: string): Promise { + try { + let rawData; + + if (key !== 'creds') { + if (process.env.CACHE_REDIS_ENABLED === 'true') { + return await cache.hGet(sessionId, key); + } else { + if (!(await fileExists(localFile(key)))) return null; + rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' }); + return JSON.parse(rawData, BufferJSON.reviver); + } + } else { + rawData = await getAuthKey(sessionId); + } + + const parsedData = JSON.parse(rawData, BufferJSON.reviver); + return parsedData; + } catch (error) { + return null; + } + } + + async function removeData(key: string): Promise { + try { + if (key !== 'creds') { + if (process.env.CACHE_REDIS_ENABLED === 'true') { + return await cache.hDelete(sessionId, key); + } else { + await fs.unlink(localFile(key)); + } + } else { + await deleteAuthKey(sessionId); + } + } catch (error) { + return; + } + } + + let creds = await readData('creds'); + if (!creds) { + creds = initAuthCreds(); + await writeData(creds, 'creds'); + } + + return { + state: { + creds, + keys: { + get: async (type, ids) => { + const data = {}; + await Promise.all( + ids.map(async (id) => { + let value = await readData(`${type}-${id}`); + if (type === 'app-state-sync-key' && value) { + value = proto.Message.AppStateSyncKeyData.fromObject(value); + } + data[id] = value; + }) + ); + return data; + }, + set: async (data) => { + const tasks = []; + for (const category in data) { + for (const id in data[category]) { + const value = data[category][id]; + const key = `${category}-${id}`; + tasks.push(value ? writeData(value, key) : removeData(key)); + } + } + await Promise.all(tasks); + }, + }, + }, + saveCreds: () => writeData(creds, 'creds'), + }; +} +``` + +## Message Processing Utilities + +### Message Content Extraction +```typescript +export const getConversationMessage = (msg: any): string => { + const types = getTypeMessage(msg); + const messageContent = getMessageContent(types); + return messageContent; +}; + +const getTypeMessage = (msg: any): any => { + return Object.keys(msg?.message || msg || {})[0]; +}; + +const getMessageContent = (type: string, msg?: any): string => { + const typeKey = type?.replace('Message', ''); + + const types = { + conversation: msg?.message?.conversation, + extendedTextMessage: msg?.message?.extendedTextMessage?.text, + imageMessage: msg?.message?.imageMessage?.caption || 'Image', + videoMessage: msg?.message?.videoMessage?.caption || 'Video', + audioMessage: 'Audio', + documentMessage: msg?.message?.documentMessage?.caption || 'Document', + stickerMessage: 'Sticker', + contactMessage: 'Contact', + locationMessage: 'Location', + liveLocationMessage: 'Live Location', + viewOnceMessage: 'View Once', + reactionMessage: 'Reaction', + pollCreationMessage: 'Poll', + pollUpdateMessage: 'Poll Update', + }; + + let result = types[typeKey] || types[type] || 'Unknown'; + + if (!result || result === 'Unknown') { + result = JSON.stringify(msg); + } + + return result; +}; +``` + +### JID Creation Utility +```typescript +export const createJid = (number: string): string => { + if (number.includes('@')) { + return number; + } + + // Remove any non-numeric characters except + + let cleanNumber = number.replace(/[^\d+]/g, ''); + + // Remove + if present + if (cleanNumber.startsWith('+')) { + cleanNumber = cleanNumber.substring(1); + } + + // Add country code if missing (assuming Brazil as default) + if (cleanNumber.length === 11 && cleanNumber.startsWith('11')) { + cleanNumber = '55' + cleanNumber; + } else if (cleanNumber.length === 10) { + cleanNumber = '5511' + cleanNumber; + } + + // Determine if it's a group or individual + const isGroup = cleanNumber.includes('-'); + const domain = isGroup ? 'g.us' : 's.whatsapp.net'; + + return `${cleanNumber}@${domain}`; +}; +``` + +## Cache Utilities + +### WhatsApp Number Cache +```typescript +interface ISaveOnWhatsappCacheParams { + remoteJid: string; + lid?: string; +} + +function getAvailableNumbers(remoteJid: string): string[] { + const numbersAvailable: string[] = []; + + if (remoteJid.startsWith('+')) { + remoteJid = remoteJid.slice(1); + } + + const [number, domain] = remoteJid.split('@'); + + // Brazilian numbers + if (remoteJid.startsWith('55')) { + const numberWithDigit = + number.slice(4, 5) === '9' && number.length === 13 ? number : `${number.slice(0, 4)}9${number.slice(4)}`; + const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 4) + number.slice(5); + + numbersAvailable.push(numberWithDigit); + numbersAvailable.push(numberWithoutDigit); + } + // Mexican/Argentina numbers + else if (number.startsWith('52') || number.startsWith('54')) { + let prefix = ''; + if (number.startsWith('52')) { + prefix = '1'; + } + if (number.startsWith('54')) { + prefix = '9'; + } + + const numberWithDigit = + number.slice(2, 3) === prefix && number.length === 13 + ? number + : `${number.slice(0, 2)}${prefix}${number.slice(2)}`; + const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 2) + number.slice(3); + + numbersAvailable.push(numberWithDigit); + numbersAvailable.push(numberWithoutDigit); + } + // Other countries + else { + numbersAvailable.push(remoteJid); + } + + return numbersAvailable.map((number) => `${number}@${domain}`); +} + +export async function saveOnWhatsappCache(params: ISaveOnWhatsappCacheParams): Promise { + const { remoteJid, lid } = params; + const db = configService.get('DATABASE'); + + if (!db.SAVE_DATA.CONTACTS) { + return; + } + + try { + const numbersAvailable = getAvailableNumbers(remoteJid); + + const existingContact = await prismaRepository.contact.findFirst({ + where: { + OR: numbersAvailable.map(number => ({ id: number })), + }, + }); + + if (!existingContact) { + await prismaRepository.contact.create({ + data: { + id: remoteJid, + pushName: '', + profilePicUrl: '', + isOnWhatsapp: true, + lid: lid || null, + createdAt: new Date(), + updatedAt: new Date(), + }, + }); + } else { + await prismaRepository.contact.update({ + where: { id: existingContact.id }, + data: { + isOnWhatsapp: true, + lid: lid || existingContact.lid, + updatedAt: new Date(), + }, + }); + } + } catch (error) { + console.error('Error saving WhatsApp cache:', error); + } +} +``` + +## Search Utilities + +### Advanced Search Operators +```typescript +function normalizeString(str: string): string { + return str + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, ''); +} + +export function advancedOperatorsSearch(data: string, query: string): boolean { + const normalizedData = normalizeString(data); + const normalizedQuery = normalizeString(query); + + // Exact phrase search with quotes + if (normalizedQuery.startsWith('"') && normalizedQuery.endsWith('"')) { + const phrase = normalizedQuery.slice(1, -1); + return normalizedData.includes(phrase); + } + + // OR operator + if (normalizedQuery.includes(' OR ')) { + const terms = normalizedQuery.split(' OR '); + return terms.some(term => normalizedData.includes(term.trim())); + } + + // AND operator (default behavior) + if (normalizedQuery.includes(' AND ')) { + const terms = normalizedQuery.split(' AND '); + return terms.every(term => normalizedData.includes(term.trim())); + } + + // NOT operator + if (normalizedQuery.startsWith('NOT ')) { + const term = normalizedQuery.slice(4); + return !normalizedData.includes(term); + } + + // Wildcard search + if (normalizedQuery.includes('*')) { + const regex = new RegExp(normalizedQuery.replace(/\*/g, '.*'), 'i'); + return regex.test(normalizedData); + } + + // Default: simple contains search + return normalizedData.includes(normalizedQuery); +} +``` + +## Proxy Utilities + +### Proxy Agent Creation +```typescript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { SocksProxyAgent } from 'socks-proxy-agent'; + +type Proxy = { + host: string; + port: string; + protocol: 'http' | 'https' | 'socks4' | 'socks5'; + username?: string; + password?: string; +}; + +function selectProxyAgent(proxyUrl: string): HttpsProxyAgent | SocksProxyAgent { + const url = new URL(proxyUrl); + + if (url.protocol === 'socks4:' || url.protocol === 'socks5:') { + return new SocksProxyAgent(proxyUrl); + } else { + return new HttpsProxyAgent(proxyUrl); + } +} + +export function makeProxyAgent(proxy: Proxy): HttpsProxyAgent | SocksProxyAgent | null { + if (!proxy.host || !proxy.port) { + return null; + } + + let proxyUrl = `${proxy.protocol}://`; + + if (proxy.username && proxy.password) { + proxyUrl += `${proxy.username}:${proxy.password}@`; + } + + proxyUrl += `${proxy.host}:${proxy.port}`; + + try { + return selectProxyAgent(proxyUrl); + } catch (error) { + console.error('Failed to create proxy agent:', error); + return null; + } +} +``` + +## Telemetry Utilities + +### Telemetry Data Collection +```typescript +export interface TelemetryData { + route: string; + apiVersion: string; + timestamp: Date; + method?: string; + statusCode?: number; + responseTime?: number; + userAgent?: string; + instanceName?: string; +} + +export const sendTelemetry = async (route: string): Promise => { + try { + const telemetryData: TelemetryData = { + route, + apiVersion: packageJson.version, + timestamp: new Date(), + }; + + // Only send telemetry if enabled + if (process.env.DISABLE_TELEMETRY === 'true') { + return; + } + + // Send to telemetry service (implement as needed) + await axios.post('https://telemetry.evolution-api.com/collect', telemetryData, { + timeout: 5000, + }); + } catch (error) { + // Silently fail - don't affect main application + console.debug('Telemetry failed:', error.message); + } +}; +``` + +## Internationalization Utilities + +### i18n Setup +```typescript +import { ConfigService, Language } from '@config/env.config'; +import fs from 'fs'; +import i18next from 'i18next'; +import path from 'path'; + +const __dirname = path.resolve(process.cwd(), 'src', 'utils'); +const languages = ['en', 'pt-BR', 'es']; +const translationsPath = path.join(__dirname, 'translations'); +const configService: ConfigService = new ConfigService(); + +const resources: any = {}; + +languages.forEach((language) => { + const languagePath = path.join(translationsPath, `${language}.json`); + if (fs.existsSync(languagePath)) { + const translationContent = fs.readFileSync(languagePath, 'utf8'); + resources[language] = { + translation: JSON.parse(translationContent), + }; + } +}); + +i18next.init({ + resources, + fallbackLng: 'en', + lng: configService.get('LANGUAGE') || 'pt-BR', + interpolation: { + escapeValue: false, + }, +}); + +export const t = i18next.t.bind(i18next); +export default i18next; +``` + +## Bot Trigger Utilities + +### Bot Trigger Matching +```typescript +import { TriggerOperator, TriggerType } from '@prisma/client'; + +export function findBotByTrigger( + bots: any[], + content: string, + remoteJid: string, +): any | null { + for (const bot of bots) { + if (!bot.enabled) continue; + + // Check ignore list + if (bot.ignoreJids && bot.ignoreJids.includes(remoteJid)) { + continue; + } + + // Check trigger + if (matchesTrigger(content, bot.triggerType, bot.triggerOperator, bot.triggerValue)) { + return bot; + } + } + + return null; +} + +function matchesTrigger( + content: string, + triggerType: TriggerType, + triggerOperator: TriggerOperator, + triggerValue: string, +): boolean { + const normalizedContent = content.toLowerCase().trim(); + const normalizedValue = triggerValue.toLowerCase().trim(); + + switch (triggerType) { + case TriggerType.ALL: + return true; + + case TriggerType.KEYWORD: + return matchesKeyword(normalizedContent, triggerOperator, normalizedValue); + + case TriggerType.REGEX: + try { + const regex = new RegExp(triggerValue, 'i'); + return regex.test(content); + } catch { + return false; + } + + default: + return false; + } +} + +function matchesKeyword( + content: string, + operator: TriggerOperator, + value: string, +): boolean { + switch (operator) { + case TriggerOperator.EQUALS: + return content === value; + case TriggerOperator.CONTAINS: + return content.includes(value); + case TriggerOperator.STARTS_WITH: + return content.startsWith(value); + case TriggerOperator.ENDS_WITH: + return content.endsWith(value); + default: + return false; + } +} +``` + +## Server Utilities + +### Server Status Check +```typescript +export class ServerUP { + private static instance: ServerUP; + private isServerUp: boolean = false; + + private constructor() {} + + public static getInstance(): ServerUP { + if (!ServerUP.instance) { + ServerUP.instance = new ServerUP(); + } + return ServerUP.instance; + } + + public setServerStatus(status: boolean): void { + this.isServerUp = status; + } + + public getServerStatus(): boolean { + return this.isServerUp; + } + + public async waitForServer(timeout: number = 30000): Promise { + const startTime = Date.now(); + + while (!this.isServerUp && (Date.now() - startTime) < timeout) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + + return this.isServerUp; + } +} +``` + +## Error Response Utilities + +### Standardized Error Responses +```typescript +export function createMetaErrorResponse(error: any, context: string) { + const timestamp = new Date().toISOString(); + + if (error.response?.data) { + return { + status: error.response.status || 500, + error: { + message: error.response.data.error?.message || 'External API error', + type: error.response.data.error?.type || 'api_error', + code: error.response.data.error?.code || 'unknown_error', + context, + timestamp, + }, + }; + } + + return { + status: 500, + error: { + message: error.message || 'Internal server error', + type: 'internal_error', + code: 'server_error', + context, + timestamp, + }, + }; +} + +export function createValidationErrorResponse(errors: any[], context: string) { + return { + status: 400, + error: { + message: 'Validation failed', + type: 'validation_error', + code: 'invalid_input', + context, + details: errors, + timestamp: new Date().toISOString(), + }, + }; +} +``` \ No newline at end of file diff --git a/.cursor/rules/specialized-rules/validate-rules.mdc b/.cursor/rules/specialized-rules/validate-rules.mdc new file mode 100644 index 000000000..f6baea1b6 --- /dev/null +++ b/.cursor/rules/specialized-rules/validate-rules.mdc @@ -0,0 +1,498 @@ +--- +description: Validation schemas and patterns for Evolution API +globs: + - "src/validate/**/*.ts" +alwaysApply: false +--- + +# Evolution API Validation Rules + +## Validation Schema Structure + +### JSONSchema7 Pattern (Evolution API Standard) +```typescript +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...fields: string[]) => { + const properties = {}; + fields.forEach((field) => { + properties[field] = { + if: { properties: { [field]: { type: 'string' } } }, + then: { properties: { [field]: { minLength: 1 } } }, + }; + }); + + return { + allOf: Object.values(properties), + }; +}; + +export const exampleSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + name: { type: 'string' }, + description: { type: 'string' }, + enabled: { type: 'boolean' }, + settings: { + type: 'object', + properties: { + timeout: { type: 'number', minimum: 1000, maximum: 60000 }, + retries: { type: 'number', minimum: 0, maximum: 5 }, + }, + }, + tags: { + type: 'array', + items: { type: 'string' }, + }, + }, + required: ['name', 'enabled'], + ...isNotEmpty('name'), +}; +``` + +## Message Validation Schemas + +### Send Message Validation +```typescript +const numberDefinition = { + type: 'string', + pattern: '^\\d+[\\.@\\w-]+', + description: 'Invalid number', +}; + +export const sendTextSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + number: numberDefinition, + text: { type: 'string', minLength: 1, maxLength: 4096 }, + delay: { type: 'number', minimum: 0, maximum: 60000 }, + linkPreview: { type: 'boolean' }, + mentionsEveryOne: { type: 'boolean' }, + mentioned: { + type: 'array', + items: { type: 'string' }, + }, + }, + required: ['number', 'text'], + ...isNotEmpty('number', 'text'), +}; + +export const sendMediaSchema = Joi.object({ + number: Joi.string().required().pattern(/^\d+$/), + mediatype: Joi.string().required().valid('image', 'video', 'audio', 'document'), + media: Joi.alternatives().try( + Joi.string().uri(), + Joi.string().base64(), + ).required(), + caption: Joi.string().optional().max(1024), + fileName: Joi.string().optional().max(255), + delay: Joi.number().optional().min(0).max(60000), +}).required(); + +export const sendButtonsSchema = Joi.object({ + number: Joi.string().required().pattern(/^\d+$/), + title: Joi.string().required().max(1024), + description: Joi.string().optional().max(1024), + footer: Joi.string().optional().max(60), + buttons: Joi.array().items( + Joi.object({ + type: Joi.string().required().valid('replyButton', 'urlButton', 'callButton'), + displayText: Joi.string().required().max(20), + id: Joi.string().when('type', { + is: 'replyButton', + then: Joi.required().max(256), + otherwise: Joi.optional(), + }), + url: Joi.string().when('type', { + is: 'urlButton', + then: Joi.required().uri(), + otherwise: Joi.optional(), + }), + phoneNumber: Joi.string().when('type', { + is: 'callButton', + then: Joi.required().pattern(/^\+?\d+$/), + otherwise: Joi.optional(), + }), + }) + ).min(1).max(3).required(), +}).required(); +``` + +## Instance Validation Schemas + +### Instance Creation Validation +```typescript +export const instanceSchema = Joi.object({ + instanceName: Joi.string().required().min(1).max(100).pattern(/^[a-zA-Z0-9_-]+$/), + integration: Joi.string().required().valid('WHATSAPP-BAILEYS', 'WHATSAPP-BUSINESS', 'EVOLUTION'), + token: Joi.string().when('integration', { + is: Joi.valid('WHATSAPP-BUSINESS', 'EVOLUTION'), + then: Joi.required().min(10), + otherwise: Joi.optional(), + }), + qrcode: Joi.boolean().optional().default(false), + number: Joi.string().optional().pattern(/^\d+$/), + businessId: Joi.string().when('integration', { + is: 'WHATSAPP-BUSINESS', + then: Joi.required(), + otherwise: Joi.optional(), + }), +}).required(); + +export const settingsSchema = Joi.object({ + rejectCall: Joi.boolean().optional(), + msgCall: Joi.string().optional().max(500), + groupsIgnore: Joi.boolean().optional(), + alwaysOnline: Joi.boolean().optional(), + readMessages: Joi.boolean().optional(), + readStatus: Joi.boolean().optional(), + syncFullHistory: Joi.boolean().optional(), + wavoipToken: Joi.string().optional(), +}).optional(); + +export const proxySchema = Joi.object({ + host: Joi.string().required().hostname(), + port: Joi.string().required().pattern(/^\d+$/).custom((value) => { + const port = parseInt(value); + if (port < 1 || port > 65535) { + throw new Error('Port must be between 1 and 65535'); + } + return value; + }), + protocol: Joi.string().required().valid('http', 'https', 'socks4', 'socks5'), + username: Joi.string().optional(), + password: Joi.string().optional(), +}).optional(); +``` + +## Webhook Validation Schemas + +### Webhook Configuration Validation +```typescript +export const webhookSchema = Joi.object({ + enabled: Joi.boolean().required(), + url: Joi.string().when('enabled', { + is: true, + then: Joi.required().uri({ scheme: ['http', 'https'] }), + otherwise: Joi.optional(), + }), + events: Joi.array().items( + Joi.string().valid( + 'APPLICATION_STARTUP', + 'INSTANCE_CREATE', + 'INSTANCE_DELETE', + 'QRCODE_UPDATED', + 'CONNECTION_UPDATE', + 'STATUS_INSTANCE', + 'MESSAGES_SET', + 'MESSAGES_UPSERT', + 'MESSAGES_UPDATE', + 'MESSAGES_DELETE', + 'CONTACTS_SET', + 'CONTACTS_UPSERT', + 'CONTACTS_UPDATE', + 'CHATS_SET', + 'CHATS_UPDATE', + 'CHATS_UPSERT', + 'CHATS_DELETE', + 'GROUPS_UPSERT', + 'GROUPS_UPDATE', + 'GROUP_PARTICIPANTS_UPDATE', + 'CALL' + ) + ).min(1).when('enabled', { + is: true, + then: Joi.required(), + otherwise: Joi.optional(), + }), + headers: Joi.object().pattern( + Joi.string(), + Joi.string() + ).optional(), + byEvents: Joi.boolean().optional().default(false), + base64: Joi.boolean().optional().default(false), +}).required(); +``` + +## Chatbot Validation Schemas + +### Base Chatbot Validation +```typescript +export const baseChatbotSchema = Joi.object({ + enabled: Joi.boolean().required(), + description: Joi.string().required().min(1).max(500), + expire: Joi.number().optional().min(0).max(86400), // 24 hours in seconds + keywordFinish: Joi.string().optional().max(100), + delayMessage: Joi.number().optional().min(0).max(10000), + unknownMessage: Joi.string().optional().max(1000), + listeningFromMe: Joi.boolean().optional().default(false), + stopBotFromMe: Joi.boolean().optional().default(false), + keepOpen: Joi.boolean().optional().default(false), + debounceTime: Joi.number().optional().min(0).max(60000), + triggerType: Joi.string().required().valid('ALL', 'KEYWORD', 'REGEX'), + triggerOperator: Joi.string().when('triggerType', { + is: 'KEYWORD', + then: Joi.required().valid('EQUALS', 'CONTAINS', 'STARTS_WITH', 'ENDS_WITH'), + otherwise: Joi.optional(), + }), + triggerValue: Joi.string().when('triggerType', { + is: Joi.valid('KEYWORD', 'REGEX'), + then: Joi.required().min(1).max(500), + otherwise: Joi.optional(), + }), + ignoreJids: Joi.array().items(Joi.string()).optional(), + splitMessages: Joi.boolean().optional().default(false), + timePerChar: Joi.number().optional().min(10).max(1000).default(100), +}).required(); + +export const typebotSchema = baseChatbotSchema.keys({ + url: Joi.string().required().uri({ scheme: ['http', 'https'] }), + typebot: Joi.string().required().min(1).max(100), + apiVersion: Joi.string().optional().valid('v1', 'v2').default('v1'), +}).required(); + +export const openaiSchema = baseChatbotSchema.keys({ + apiKey: Joi.string().required().min(10), + model: Joi.string().optional().valid( + 'gpt-3.5-turbo', + 'gpt-3.5-turbo-16k', + 'gpt-4', + 'gpt-4-32k', + 'gpt-4-turbo-preview' + ).default('gpt-3.5-turbo'), + systemMessage: Joi.string().optional().max(2000), + maxTokens: Joi.number().optional().min(1).max(4000).default(1000), + temperature: Joi.number().optional().min(0).max(2).default(0.7), +}).required(); +``` + +## Business API Validation Schemas + +### Template Validation +```typescript +export const templateSchema = Joi.object({ + name: Joi.string().required().min(1).max(512).pattern(/^[a-z0-9_]+$/), + category: Joi.string().required().valid('MARKETING', 'UTILITY', 'AUTHENTICATION'), + allowCategoryChange: Joi.boolean().required(), + language: Joi.string().required().pattern(/^[a-z]{2}_[A-Z]{2}$/), // e.g., pt_BR, en_US + components: Joi.array().items( + Joi.object({ + type: Joi.string().required().valid('HEADER', 'BODY', 'FOOTER', 'BUTTONS'), + format: Joi.string().when('type', { + is: 'HEADER', + then: Joi.valid('TEXT', 'IMAGE', 'VIDEO', 'DOCUMENT'), + otherwise: Joi.optional(), + }), + text: Joi.string().when('type', { + is: Joi.valid('HEADER', 'BODY', 'FOOTER'), + then: Joi.required().min(1).max(1024), + otherwise: Joi.optional(), + }), + buttons: Joi.array().when('type', { + is: 'BUTTONS', + then: Joi.items( + Joi.object({ + type: Joi.string().required().valid('QUICK_REPLY', 'URL', 'PHONE_NUMBER'), + text: Joi.string().required().min(1).max(25), + url: Joi.string().when('type', { + is: 'URL', + then: Joi.required().uri(), + otherwise: Joi.optional(), + }), + phone_number: Joi.string().when('type', { + is: 'PHONE_NUMBER', + then: Joi.required().pattern(/^\+?\d+$/), + otherwise: Joi.optional(), + }), + }) + ).min(1).max(10), + otherwise: Joi.optional(), + }), + }) + ).min(1).required(), + webhookUrl: Joi.string().optional().uri({ scheme: ['http', 'https'] }), +}).required(); + +export const catalogSchema = Joi.object({ + number: Joi.string().optional().pattern(/^\d+$/), + limit: Joi.number().optional().min(1).max(1000).default(10), + cursor: Joi.string().optional(), +}).optional(); +``` + +## Group Validation Schemas + +### Group Management Validation +```typescript +export const createGroupSchema = Joi.object({ + subject: Joi.string().required().min(1).max(100), + description: Joi.string().optional().max(500), + participants: Joi.array().items( + Joi.string().pattern(/^\d+$/) + ).min(1).max(256).required(), + promoteParticipants: Joi.boolean().optional().default(false), +}).required(); + +export const updateGroupSchema = Joi.object({ + subject: Joi.string().optional().min(1).max(100), + description: Joi.string().optional().max(500), +}).min(1).required(); + +export const groupParticipantsSchema = Joi.object({ + participants: Joi.array().items( + Joi.string().pattern(/^\d+$/) + ).min(1).max(50).required(), + action: Joi.string().required().valid('add', 'remove', 'promote', 'demote'), +}).required(); +``` + +## Label Validation Schemas + +### Label Management Validation +```typescript +export const labelSchema = Joi.object({ + name: Joi.string().required().min(1).max(100), + color: Joi.string().required().pattern(/^#[0-9A-Fa-f]{6}$/), // Hex color + predefinedId: Joi.string().optional(), +}).required(); + +export const handleLabelSchema = Joi.object({ + number: Joi.string().required().pattern(/^\d+$/), + labelId: Joi.string().required(), + action: Joi.string().required().valid('add', 'remove'), +}).required(); +``` + +## Custom Validation Functions + +### Phone Number Validation +```typescript +export function validatePhoneNumber(number: string): boolean { + // Remove any non-digit characters + const cleaned = number.replace(/\D/g, ''); + + // Check minimum and maximum length + if (cleaned.length < 10 || cleaned.length > 15) { + return false; + } + + // Check for valid country codes (basic validation) + const validCountryCodes = ['1', '7', '20', '27', '30', '31', '32', '33', '34', '36', '39', '40', '41', '43', '44', '45', '46', '47', '48', '49', '51', '52', '53', '54', '55', '56', '57', '58', '60', '61', '62', '63', '64', '65', '66', '81', '82', '84', '86', '90', '91', '92', '93', '94', '95', '98']; + + // Check if starts with valid country code + const startsWithValidCode = validCountryCodes.some(code => cleaned.startsWith(code)); + + return startsWithValidCode; +} + +export const phoneNumberValidator = Joi.string().custom((value, helpers) => { + if (!validatePhoneNumber(value)) { + return helpers.error('any.invalid'); + } + return value; +}, 'Phone number validation'); +``` + +### Base64 Validation +```typescript +export function validateBase64(base64: string): boolean { + try { + // Check if it's a valid base64 string + const decoded = Buffer.from(base64, 'base64').toString('base64'); + return decoded === base64; + } catch { + return false; + } +} + +export const base64Validator = Joi.string().custom((value, helpers) => { + if (!validateBase64(value)) { + return helpers.error('any.invalid'); + } + return value; +}, 'Base64 validation'); +``` + +### URL Validation with Protocol Check +```typescript +export function validateWebhookUrl(url: string): boolean { + try { + const parsed = new URL(url); + return ['http:', 'https:'].includes(parsed.protocol); + } catch { + return false; + } +} + +export const webhookUrlValidator = Joi.string().custom((value, helpers) => { + if (!validateWebhookUrl(value)) { + return helpers.error('any.invalid'); + } + return value; +}, 'Webhook URL validation'); +``` + +## Validation Error Handling + +### Error Message Customization +```typescript +export const validationMessages = { + 'any.required': 'O campo {#label} é obrigatório', + 'string.empty': 'O campo {#label} não pode estar vazio', + 'string.min': 'O campo {#label} deve ter pelo menos {#limit} caracteres', + 'string.max': 'O campo {#label} deve ter no máximo {#limit} caracteres', + 'string.pattern.base': 'O campo {#label} possui formato inválido', + 'number.min': 'O campo {#label} deve ser maior ou igual a {#limit}', + 'number.max': 'O campo {#label} deve ser menor ou igual a {#limit}', + 'array.min': 'O campo {#label} deve ter pelo menos {#limit} itens', + 'array.max': 'O campo {#label} deve ter no máximo {#limit} itens', + 'any.only': 'O campo {#label} deve ser um dos valores: {#valids}', +}; + +export function formatValidationError(error: Joi.ValidationError): any { + return { + message: 'Dados de entrada inválidos', + details: error.details.map(detail => ({ + field: detail.path.join('.'), + message: detail.message, + value: detail.context?.value, + })), + }; +} +``` + +## Schema Composition + +### Reusable Schema Components +```typescript +export const commonFields = { + instanceName: Joi.string().required().min(1).max(100).pattern(/^[a-zA-Z0-9_-]+$/), + number: phoneNumberValidator.required(), + delay: Joi.number().optional().min(0).max(60000), + enabled: Joi.boolean().optional().default(true), +}; + +export const mediaFields = { + mediatype: Joi.string().required().valid('image', 'video', 'audio', 'document'), + media: Joi.alternatives().try( + Joi.string().uri(), + base64Validator, + ).required(), + caption: Joi.string().optional().max(1024), + fileName: Joi.string().optional().max(255), +}; + +// Compose schemas using common fields +export const quickMessageSchema = Joi.object({ + ...commonFields, + text: Joi.string().required().min(1).max(4096), +}).required(); + +export const quickMediaSchema = Joi.object({ + ...commonFields, + ...mediaFields, +}).required(); +``` \ No newline at end of file diff --git a/.dockerignore b/.dockerignore index 0d406464d..f8ca5d026 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,6 @@ .git *Dockerfile* *docker-compose* +.env node_modules dist \ No newline at end of file diff --git a/.env.example b/.env.example index d6412fec9..73a3b40d3 100644 --- a/.env.example +++ b/.env.example @@ -1,10 +1,36 @@ +SERVER_NAME=evolution SERVER_TYPE=http SERVER_PORT=8080 # Server URL - Set your application url SERVER_URL=http://localhost:8080 +SSL_CONF_PRIVKEY=/path/to/cert.key +SSL_CONF_FULLCHAIN=/path/to/cert.crt + SENTRY_DSN= +# Telemetry - Set to false to disable telemetry +TELEMETRY_ENABLED=true +TELEMETRY_URL= + +# Prometheus metrics - Set to true to enable Prometheus metrics +PROMETHEUS_METRICS=false +METRICS_AUTH_REQUIRED=true +METRICS_USER=prometheus +METRICS_PASSWORD=secure_random_password_here +METRICS_ALLOWED_IPS=127.0.0.1,10.0.0.100,192.168.1.50 + +# Proxy configuration (optional) +PROXY_HOST= +PROXY_PORT= +PROXY_PROTOCOL= +PROXY_USERNAME= +PROXY_PASSWORD= + +# Audio converter API (optional) +API_AUDIO_CONVERTER= +API_AUDIO_CONVERTER_KEY= + # Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' CORS_ORIGIN=* CORS_METHODS=GET,POST,PUT,DELETE @@ -24,13 +50,17 @@ EVENT_EMITTER_MAX_LISTENERS=50 # If you don't even want an expiration, enter the value false DEL_INSTANCE=false -# Provider: postgresql | mysql +# Provider: postgresql | mysql | psql_bouncer DATABASE_PROVIDER=postgresql -DATABASE_CONNECTION_URI='postgresql://user:pass@localhost:5432/evolution?schema=public' +DATABASE_CONNECTION_URI='postgresql://user:pass@postgres:5432/evolution_db?schema=evolution_api' # Client name for the database connection # It is used to separate an API installation from another that uses the same database. DATABASE_CONNECTION_CLIENT_NAME=evolution_exchange +# Bouncer connection: used only when the database provider is set to 'psql_bouncer'. +# Defines the PostgreSQL URL with pgbouncer enabled (pgbouncer=true). +# DATABASE_BOUNCER_CONNECTION_URI=postgresql://user:pass@pgbouncer:5432/evolution_db?pgbouncer=true&schema=evolution_api + # Choose the data you want to save in the application's database DATABASE_SAVE_DATA_INSTANCE=true DATABASE_SAVE_DATA_NEW_MESSAGE=true @@ -47,8 +77,11 @@ DATABASE_DELETE_MESSAGE=true RABBITMQ_ENABLED=false RABBITMQ_URI=amqp://localhost RABBITMQ_EXCHANGE_NAME=evolution +RABBITMQ_FRAME_MAX=8192 # Global events - By enabling this variable, events from all instances are sent in the same event queue. RABBITMQ_GLOBAL_ENABLED=false +# Prefix key to queue name +RABBITMQ_PREFIX_KEY=evolution # Choose the events you want to send to RabbitMQ RABBITMQ_EVENTS_APPLICATION_STARTUP=false RABBITMQ_EVENTS_INSTANCE_CREATE=false @@ -60,6 +93,7 @@ RABBITMQ_EVENTS_MESSAGES_EDITED=false RABBITMQ_EVENTS_MESSAGES_UPDATE=false RABBITMQ_EVENTS_MESSAGES_DELETE=false RABBITMQ_EVENTS_SEND_MESSAGE=false +RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE=false RABBITMQ_EVENTS_CONTACTS_SET=false RABBITMQ_EVENTS_CONTACTS_UPSERT=false RABBITMQ_EVENTS_CONTACTS_UPDATE=false @@ -85,9 +119,40 @@ SQS_SECRET_ACCESS_KEY= SQS_ACCOUNT_ID= SQS_REGION= +SQS_GLOBAL_ENABLED=false +SQS_GLOBAL_FORCE_SINGLE_QUEUE=false +SQS_GLOBAL_APPLICATION_STARTUP=false +SQS_GLOBAL_CALL=false +SQS_GLOBAL_CHATS_DELETE=false +SQS_GLOBAL_CHATS_SET=false +SQS_GLOBAL_CHATS_UPDATE=false +SQS_GLOBAL_CHATS_UPSERT=false +SQS_GLOBAL_CONNECTION_UPDATE=false +SQS_GLOBAL_CONTACTS_SET=false +SQS_GLOBAL_CONTACTS_UPDATE=false +SQS_GLOBAL_CONTACTS_UPSERT=false +SQS_GLOBAL_GROUP_PARTICIPANTS_UPDATE=false +SQS_GLOBAL_GROUPS_UPDATE=false +SQS_GLOBAL_GROUPS_UPSERT=false +SQS_GLOBAL_LABELS_ASSOCIATION=false +SQS_GLOBAL_LABELS_EDIT=false +SQS_GLOBAL_LOGOUT_INSTANCE=false +SQS_GLOBAL_MESSAGES_DELETE=false +SQS_GLOBAL_MESSAGES_EDITED=false +SQS_GLOBAL_MESSAGES_SET=false +SQS_GLOBAL_MESSAGES_UPDATE=false +SQS_GLOBAL_MESSAGES_UPSERT=false +SQS_GLOBAL_PRESENCE_UPDATE=false +SQS_GLOBAL_QRCODE_UPDATED=false +SQS_GLOBAL_REMOVE_INSTANCE=false +SQS_GLOBAL_SEND_MESSAGE=false +SQS_GLOBAL_TYPEBOT_CHANGE_STATUS=false +SQS_GLOBAL_TYPEBOT_START=false + # Websocket - Environment variables WEBSOCKET_ENABLED=false WEBSOCKET_GLOBAL_EVENTS=false +WEBSOCKET_ALLOWED_HOSTS=127.0.0.1,::1,::ffff:127.0.0.1 # Pusher - Environment variables PUSHER_ENABLED=false @@ -106,6 +171,7 @@ PUSHER_EVENTS_MESSAGES_EDITED=true PUSHER_EVENTS_MESSAGES_UPDATE=true PUSHER_EVENTS_MESSAGES_DELETE=true PUSHER_EVENTS_SEND_MESSAGE=true +PUSHER_EVENTS_SEND_MESSAGE_UPDATE=true PUSHER_EVENTS_CONTACTS_SET=true PUSHER_EVENTS_CONTACTS_UPSERT=true PUSHER_EVENTS_CONTACTS_UPDATE=true @@ -124,6 +190,60 @@ PUSHER_EVENTS_CALL=true PUSHER_EVENTS_TYPEBOT_START=false PUSHER_EVENTS_TYPEBOT_CHANGE_STATUS=false +# Kafka - Environment variables +KAFKA_ENABLED=false +KAFKA_CLIENT_ID=evolution-api +KAFKA_BROKERS=localhost:9092 +KAFKA_CONNECTION_TIMEOUT=3000 +KAFKA_REQUEST_TIMEOUT=30000 +# Global events - By enabling this variable, events from all instances are sent to global Kafka topics. +KAFKA_GLOBAL_ENABLED=false +KAFKA_CONSUMER_GROUP_ID=evolution-api-consumers +KAFKA_TOPIC_PREFIX=evolution +KAFKA_NUM_PARTITIONS=1 +KAFKA_REPLICATION_FACTOR=1 +KAFKA_AUTO_CREATE_TOPICS=false +# Choose the events you want to send to Kafka +KAFKA_EVENTS_APPLICATION_STARTUP=false +KAFKA_EVENTS_INSTANCE_CREATE=false +KAFKA_EVENTS_INSTANCE_DELETE=false +KAFKA_EVENTS_QRCODE_UPDATED=false +KAFKA_EVENTS_MESSAGES_SET=false +KAFKA_EVENTS_MESSAGES_UPSERT=false +KAFKA_EVENTS_MESSAGES_EDITED=false +KAFKA_EVENTS_MESSAGES_UPDATE=false +KAFKA_EVENTS_MESSAGES_DELETE=false +KAFKA_EVENTS_SEND_MESSAGE=false +KAFKA_EVENTS_SEND_MESSAGE_UPDATE=false +KAFKA_EVENTS_CONTACTS_SET=false +KAFKA_EVENTS_CONTACTS_UPSERT=false +KAFKA_EVENTS_CONTACTS_UPDATE=false +KAFKA_EVENTS_PRESENCE_UPDATE=false +KAFKA_EVENTS_CHATS_SET=false +KAFKA_EVENTS_CHATS_UPSERT=false +KAFKA_EVENTS_CHATS_UPDATE=false +KAFKA_EVENTS_CHATS_DELETE=false +KAFKA_EVENTS_GROUPS_UPSERT=false +KAFKA_EVENTS_GROUPS_UPDATE=false +KAFKA_EVENTS_GROUP_PARTICIPANTS_UPDATE=false +KAFKA_EVENTS_CONNECTION_UPDATE=false +KAFKA_EVENTS_LABELS_EDIT=false +KAFKA_EVENTS_LABELS_ASSOCIATION=false +KAFKA_EVENTS_CALL=false +KAFKA_EVENTS_TYPEBOT_START=false +KAFKA_EVENTS_TYPEBOT_CHANGE_STATUS=false +# SASL Authentication (optional) +KAFKA_SASL_ENABLED=false +KAFKA_SASL_MECHANISM=plain +KAFKA_SASL_USERNAME= +KAFKA_SASL_PASSWORD= +# SSL Configuration (optional) +KAFKA_SSL_ENABLED=false +KAFKA_SSL_REJECT_UNAUTHORIZED=true +KAFKA_SSL_CA= +KAFKA_SSL_KEY= +KAFKA_SSL_CERT= + # WhatsApp Business API - Environment variables # Token used to validate the webhook on the Facebook APP WA_BUSINESS_TOKEN_WEBHOOK=evolution @@ -147,6 +267,7 @@ WEBHOOK_EVENTS_MESSAGES_EDITED=true WEBHOOK_EVENTS_MESSAGES_UPDATE=true WEBHOOK_EVENTS_MESSAGES_DELETE=true WEBHOOK_EVENTS_SEND_MESSAGE=true +WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE=true WEBHOOK_EVENTS_CONTACTS_SET=true WEBHOOK_EVENTS_CONTACTS_UPSERT=true WEBHOOK_EVENTS_CONTACTS_UPDATE=true @@ -171,6 +292,15 @@ WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=false WEBHOOK_EVENTS_ERRORS=false WEBHOOK_EVENTS_ERRORS_WEBHOOK= +WEBHOOK_REQUEST_TIMEOUT_MS=60000 +WEBHOOK_RETRY_MAX_ATTEMPTS=10 +WEBHOOK_RETRY_INITIAL_DELAY_SECONDS=5 +WEBHOOK_RETRY_USE_EXPONENTIAL_BACKOFF=true +WEBHOOK_RETRY_MAX_DELAY_SECONDS=300 +WEBHOOK_RETRY_JITTER_FACTOR=0.2 +# Comma separated list of HTTP status codes that should not trigger retries +WEBHOOK_RETRY_NON_RETRYABLE_STATUS_CODES=400,401,403,404,422 + # Name that will be displayed on smartphone connection CONFIG_SESSION_PHONE_CLIENT=Evolution API # Browser Name = Chrome | Firefox | Edge | Opera | Safari @@ -178,7 +308,7 @@ CONFIG_SESSION_PHONE_NAME=Chrome # Whatsapp Web version for baileys channel # https://web.whatsapp.com/check-update?version=0&platform=web -CONFIG_SESSION_PHONE_VERSION=2.3000.1015901307 + # Set qrcode display limit QRCODE_LIMIT=30 @@ -208,6 +338,12 @@ OPENAI_ENABLED=false # Dify - Environment variables DIFY_ENABLED=false +# n8n - Environment variables +N8N_ENABLED=false + +# EvoAI - Environment variables +EVOAI_ENABLED=false + # Cache - Environment variables # Redis Cache enabled CACHE_REDIS_ENABLED=true @@ -264,4 +400,4 @@ LANGUAGE=en # PROXY_PORT=80 # PROXY_PROTOCOL=http # PROXY_USERNAME= -# PROXY_PASSWORD= \ No newline at end of file +# PROXY_PASSWORD= diff --git a/.eslintrc.js b/.eslintrc.js index 74a4c2ead..8f54a7766 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,7 +1,11 @@ module.exports = { parser: '@typescript-eslint/parser', parserOptions: { - sourceType: 'CommonJS', + project: 'tsconfig.json', + tsconfigRootDir: __dirname, + sourceType: 'module', + warnOnUnsupportedTypeScriptVersion: false, + EXPERIMENTAL_useSourceOfProjectReferenceRedirect: true, }, plugins: ['@typescript-eslint', 'simple-import-sort', 'import'], extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'], @@ -27,16 +31,9 @@ module.exports = { 'import/no-duplicates': 'error', 'simple-import-sort/imports': 'error', 'simple-import-sort/exports': 'error', - '@typescript-eslint/ban-types': [ - 'error', - { - extendDefaults: true, - types: { - '{}': false, - Object: false, - }, - }, - ], + '@typescript-eslint/no-empty-object-type': 'off', + '@typescript-eslint/no-wrapper-object-types': 'off', + '@typescript-eslint/no-unused-expressions': 'off', 'prettier/prettier': ['error', { endOfLine: 'auto' }], }, }; diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..7cdafa179 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,81 @@ +name: 🐛 Bug Report +description: Report a bug or unexpected behavior +title: "[BUG] " +labels: ["bug", "needs-triage"] +assignees: [] + +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + Please search existing issues before creating a new one. + + - type: textarea + id: description + attributes: + label: 📋 Bug Description + description: A clear and concise description of what the bug is. + placeholder: Describe the bug... + validations: + required: true + + - type: textarea + id: reproduction + attributes: + label: 🔄 Steps to Reproduce + description: Steps to reproduce the behavior + placeholder: | + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + + - type: textarea + id: expected + attributes: + label: ✅ Expected Behavior + description: A clear and concise description of what you expected to happen. + placeholder: What should happen? + validations: + required: true + + - type: textarea + id: actual + attributes: + label: ❌ Actual Behavior + description: A clear and concise description of what actually happened. + placeholder: What actually happened? + validations: + required: true + + - type: textarea + id: environment + attributes: + label: 🌍 Environment + description: Please provide information about your environment + value: | + - OS: [e.g. Ubuntu 20.04, Windows 10, macOS 12.0] + - Node.js version: [e.g. 18.17.0] + - Evolution API version: [e.g. 2.3.7] + - Database: [e.g. PostgreSQL 14, MySQL 8.0] + - Connection type: [e.g. Baileys, WhatsApp Business API] + validations: + required: true + + - type: textarea + id: logs + attributes: + label: 📋 Logs + description: If applicable, add logs to help explain your problem. + placeholder: Paste relevant logs here... + render: shell + + - type: textarea + id: additional + attributes: + label: 📝 Additional Context + description: Add any other context about the problem here. + placeholder: Any additional information... diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000..789db1eb1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,85 @@ +name: ✨ Feature Request +description: Suggest a new feature or enhancement +title: "[FEATURE] " +labels: ["enhancement", "needs-triage"] +assignees: [] + +body: + - type: markdown + attributes: + value: | + Thanks for suggesting a new feature! + Please check our [Feature Requests on Canny](https://evolutionapi.canny.io/feature-requests) first. + + - type: textarea + id: problem + attributes: + label: 🎯 Problem Statement + description: Is your feature request related to a problem? Please describe. + placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: true + + - type: textarea + id: solution + attributes: + label: 💡 Proposed Solution + description: Describe the solution you'd like + placeholder: A clear and concise description of what you want to happen. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: 🔄 Alternatives Considered + description: Describe alternatives you've considered + placeholder: A clear and concise description of any alternative solutions or features you've considered. + + - type: dropdown + id: priority + attributes: + label: 📊 Priority + description: How important is this feature to you? + options: + - Low - Nice to have + - Medium - Would be helpful + - High - Important for my use case + - Critical - Blocking my work + validations: + required: true + + - type: dropdown + id: component + attributes: + label: 🧩 Component + description: Which component does this feature relate to? + options: + - WhatsApp Integration (Baileys) + - WhatsApp Business API + - Chatwoot Integration + - Typebot Integration + - OpenAI Integration + - Dify Integration + - API Endpoints + - Database + - Authentication + - Webhooks + - File Storage + - Other + + - type: textarea + id: use_case + attributes: + label: 🎯 Use Case + description: Describe your specific use case for this feature + placeholder: How would you use this feature? What problem does it solve for you? + validations: + required: true + + - type: textarea + id: additional + attributes: + label: 📝 Additional Context + description: Add any other context, screenshots, or examples about the feature request here. + placeholder: Any additional information, mockups, or examples... diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000..e35dd9e5c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,41 @@ +## 📋 Description + + +## 🔗 Related Issue + +Closes #(issue_number) + +## 🧪 Type of Change + +- [ ] 🐛 Bug fix (non-breaking change which fixes an issue) +- [ ] ✨ New feature (non-breaking change which adds functionality) +- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] 📚 Documentation update +- [ ] 🔧 Refactoring (no functional changes) +- [ ] ⚡ Performance improvement +- [ ] 🧹 Code cleanup +- [ ] 🔒 Security fix + +## 🧪 Testing + +- [ ] Manual testing completed +- [ ] Functionality verified in development environment +- [ ] No breaking changes introduced +- [ ] Tested with different connection types (if applicable) + +## 📸 Screenshots (if applicable) + + +## ✅ Checklist + +- [ ] My code follows the project's style guidelines +- [ ] I have performed a self-review of my code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] My changes generate no new warnings +- [ ] I have manually tested my changes thoroughly +- [ ] I have verified the changes work with different scenarios +- [ ] Any dependent changes have been merged and published + +## 📝 Additional Notes + diff --git a/.github/workflows/check_code_quality.yml b/.github/workflows/check_code_quality.yml new file mode 100644 index 000000000..df156f211 --- /dev/null +++ b/.github/workflows/check_code_quality.yml @@ -0,0 +1,42 @@ +name: Check Code Quality + +on: + pull_request: + branches: [ main, develop ] + push: + branches: [ main, develop ] + +jobs: + check-lint-and-build: + runs-on: ubuntu-latest + timeout-minutes: 10 + + steps: + - uses: actions/checkout@v5 + with: + submodules: recursive + + - name: Install Node + uses: actions/setup-node@v5 + with: + node-version: 20.x + + - name: Cache node modules + uses: actions/cache@v4 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + + - name: Install packages + run: npm ci + + - name: Check linting + run: npm run lint:check + + - name: Generate Prisma client + run: npm run db:generate + + - name: Check build + run: npm run build \ No newline at end of file diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml index 68a08a313..c5a3996ed 100644 --- a/.github/workflows/publish_docker_image.yml +++ b/.github/workflows/publish_docker_image.yml @@ -14,13 +14,15 @@ jobs: packages: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 + with: + submodules: recursive - name: Docker meta id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: type=semver,pattern=v{{version}} - name: Set up QEMU @@ -37,7 +39,7 @@ jobs: - name: Build and push id: docker_build - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: platforms: linux/amd64,linux/arm64 push: true diff --git a/.github/workflows/publish_docker_image_homolog.yml b/.github/workflows/publish_docker_image_homolog.yml index 77032dc95..a76e1008b 100644 --- a/.github/workflows/publish_docker_image_homolog.yml +++ b/.github/workflows/publish_docker_image_homolog.yml @@ -14,13 +14,15 @@ jobs: packages: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 + with: + submodules: recursive - name: Docker meta id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: homolog - name: Set up QEMU @@ -37,7 +39,7 @@ jobs: - name: Build and push id: docker_build - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: platforms: linux/amd64,linux/arm64 push: true diff --git a/.github/workflows/publish_docker_image_latest.yml b/.github/workflows/publish_docker_image_latest.yml index 641dc5e01..f73fe80e4 100644 --- a/.github/workflows/publish_docker_image_latest.yml +++ b/.github/workflows/publish_docker_image_latest.yml @@ -14,13 +14,15 @@ jobs: packages: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 + with: + submodules: recursive - name: Docker meta id: meta uses: docker/metadata-action@v5 with: - images: atendai/evolution-api + images: evoapicloud/evolution-api tags: latest - name: Set up QEMU @@ -37,7 +39,7 @@ jobs: - name: Build and push id: docker_build - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: platforms: linux/amd64,linux/arm64 push: true diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 000000000..b83f0b5d9 --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,55 @@ +name: Security Scan + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + schedule: + - cron: '0 0 * * 1' # Weekly on Mondays + +jobs: + codeql: + name: CodeQL Analysis + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'javascript' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + submodules: recursive + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" + + dependency-review: + name: Dependency Review + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + steps: + - name: Checkout Repository + uses: actions/checkout@v5 + with: + submodules: recursive + - name: Dependency Review + uses: actions/dependency-review-action@v4 diff --git a/.gitignore b/.gitignore index 3c511120b..768d8afa4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,11 @@ +# Repo +Baileys # compiled output /dist /node_modules /Docker/.env -.vscode - # Logs logs/**.json *.log @@ -21,7 +21,6 @@ lerna-debug.log* # Package /yarn.lock /pnpm-lock.yaml -/package-lock.json # IDEs .vscode/* diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..ef5b3e63c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "evolution-manager-v2"] + path = evolution-manager-v2 + url = https://github.com/EvolutionAPI/evolution-manager-v2.git diff --git a/.husky/README.md b/.husky/README.md new file mode 100644 index 000000000..14d5fa8b1 --- /dev/null +++ b/.husky/README.md @@ -0,0 +1,51 @@ +# Git Hooks Configuration + +Este projeto usa [Husky](https://typicode.github.io/husky/) para automatizar verificações de qualidade de código. + +## Hooks Configurados + +### Pre-commit +- **Arquivo**: `.husky/pre-commit` +- **Executa**: `npx lint-staged` +- **Função**: Executa lint e correções automáticas apenas nos arquivos modificados + +### Pre-push +- **Arquivo**: `.husky/pre-push` +- **Executa**: `npm run build` + `npm run lint:check` +- **Função**: Verifica se o projeto compila e não tem erros de lint antes do push + +## Lint-staged Configuration + +Configurado no `package.json`: + +```json +"lint-staged": { + "src/**/*.{ts,js}": [ + "eslint --fix", + "git add" + ], + "src/**/*.ts": [ + "npm run build" + ] +} +``` + +## Como funciona + +1. **Ao fazer commit**: Executa lint apenas nos arquivos modificados +2. **Ao fazer push**: Executa build completo e verificação de lint +3. **Se houver erros**: O commit/push é bloqueado até correção + +## Comandos úteis + +```bash +# Pular hooks (não recomendado) +git commit --no-verify +git push --no-verify + +# Executar lint manualmente +npm run lint + +# Executar build manualmente +npm run build +``` diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 000000000..0a4b97de5 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +npx --no -- commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..2312dc587 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100755 index 000000000..a72538ac2 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,2 @@ +npm run build +npm run lint:check diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..143e6c748 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,355 @@ +# Evolution API - AI Agent Guidelines + +This document provides comprehensive guidelines for AI agents (Claude, GPT, Cursor, etc.) working with the Evolution API codebase. + +## Project Overview + +**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. + +## Project Structure & Module Organization + +### Core Directories +- **`src/`** – TypeScript source code with modular architecture + - `api/controllers/` – HTTP route handlers (thin layer) + - `api/services/` – Business logic (core functionality) + - `api/routes/` – Express route definitions (RouterBroker pattern) + - `api/integrations/` – External service integrations + - `channel/` – WhatsApp providers (Baileys, Business API, Evolution) + - `chatbot/` – AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot) + - `event/` – Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher) + - `storage/` – File storage (S3, MinIO) + - `dto/` – Data Transfer Objects (simple classes, no decorators) + - `guards/` – Authentication/authorization middleware + - `types/` – TypeScript type definitions + - `repository/` – Data access layer (Prisma) +- **`prisma/`** – Database schemas and migrations + - `postgresql-schema.prisma` / `mysql-schema.prisma` – Provider-specific schemas + - `postgresql-migrations/` / `mysql-migrations/` – Provider-specific migrations +- **`config/`** – Environment and application configuration +- **`utils/`** – Shared utilities and helper functions +- **`validate/`** – JSONSchema7 validation schemas +- **`exceptions/`** – Custom HTTP exception classes +- **`cache/`** – Redis and local cache implementations + +### Build & Deployment +- **`dist/`** – Build output (do not edit directly) +- **`public/`** – Static assets and media files +- **`Docker*`**, **`docker-compose*.yaml`** – Containerization and local development stack + +## Build, Test, and Development Commands + +### Development Workflow +```bash +# Development server with hot reload +npm run dev:server + +# Direct execution for testing +npm start + +# Production build and run +npm run build +npm run start:prod +``` + +### Code Quality +```bash +# Linting and formatting +npm run lint # ESLint with auto-fix +npm run lint:check # ESLint check only + +# Commit with conventional commits +npm run commit # Interactive commit with Commitizen +``` + +### Database Management +```bash +# Set database provider first (CRITICAL) +export DATABASE_PROVIDER=postgresql # or mysql + +# Generate Prisma client +npm run db:generate + +# Development migrations (with provider sync) +npm run db:migrate:dev # Unix/Mac +npm run db:migrate:dev:win # Windows + +# Production deployment +npm run db:deploy # Unix/Mac +npm run db:deploy:win # Windows + +# Database tools +npm run db:studio # Open Prisma Studio +``` + +### Docker Development +```bash +# Start local services (Redis, PostgreSQL, etc.) +docker-compose up -d + +# Full development stack +docker-compose -f docker-compose.dev.yaml up -d +``` + +## Coding Standards & Architecture Patterns + +### Code Style (Enforced by ESLint + Prettier) +- **TypeScript strict mode** with full type coverage +- **2-space indentation**, single quotes, trailing commas +- **120-character line limit** +- **Import order** via `simple-import-sort` +- **File naming**: `feature.kind.ts` (e.g., `whatsapp.baileys.service.ts`) +- **Naming conventions**: + - Classes: `PascalCase` + - Functions/variables: `camelCase` + - Constants: `UPPER_SNAKE_CASE` + - Files: `kebab-case.type.ts` + +### Architecture Patterns + +#### Service Layer Pattern +```typescript +export class ExampleService { + constructor(private readonly waMonitor: WAMonitoringService) {} + + private readonly logger = new Logger('ExampleService'); + + public async create(instance: InstanceDto, data: ExampleDto) { + // Business logic here + return { example: { ...instance, data } }; + } + + public async find(instance: InstanceDto): Promise { + try { + const result = await this.waMonitor.waInstances[instance.instanceName].findData(); + return result || null; // Return null on not found (Evolution pattern) + } catch (error) { + this.logger.error('Error finding data:', error); + return null; // Return null on error (Evolution pattern) + } + } +} +``` + +#### Controller Pattern (Thin Layer) +```typescript +export class ExampleController { + constructor(private readonly exampleService: ExampleService) {} + + public async createExample(instance: InstanceDto, data: ExampleDto) { + return this.exampleService.create(instance, data); + } +} +``` + +#### RouterBroker Pattern +```typescript +export class ExampleRouter extends RouterBroker { + constructor(...guards: any[]) { + super(); + this.router.post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: exampleSchema, // JSONSchema7 + ClassRef: ExampleDto, + execute: (instance, data) => controller.createExample(instance, data), + }); + res.status(201).json(response); + }); + } +} +``` + +#### DTO Pattern (Simple Classes) +```typescript +// CORRECT - Evolution API pattern (no decorators) +export class ExampleDto { + name: string; + description?: string; + enabled: boolean; +} + +// INCORRECT - Don't use class-validator decorators +export class BadExampleDto { + @IsString() // ❌ Evolution API doesn't use decorators + name: string; +} +``` + +#### Validation Pattern (JSONSchema7) +```typescript +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +export const exampleSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + name: { type: 'string' }, + description: { type: 'string' }, + enabled: { type: 'boolean' }, + }, + required: ['name', 'enabled'], +}; +``` + +## Multi-Tenant Architecture + +### Instance Isolation +- **CRITICAL**: All operations must be scoped by `instanceName` or `instanceId` +- **Database queries**: Always include `where: { instanceId: ... }` +- **Authentication**: Validate instance ownership before operations +- **Data isolation**: Complete separation between tenant instances + +### WhatsApp Instance Management +```typescript +// Access instance via WAMonitoringService +const waInstance = this.waMonitor.waInstances[instance.instanceName]; +if (!waInstance) { + throw new NotFoundException(`Instance ${instance.instanceName} not found`); +} +``` + +## Database Patterns + +### Multi-Provider Support +- **PostgreSQL**: Uses `@db.Integer`, `@db.JsonB`, `@default(now())` +- **MySQL**: Uses `@db.Int`, `@db.Json`, `@default(now())` +- **Environment**: Set `DATABASE_PROVIDER=postgresql` or `mysql` +- **Migrations**: Provider-specific folders auto-selected + +### Prisma Repository Pattern +```typescript +// Always use PrismaRepository for database operations +const result = await this.prismaRepository.instance.findUnique({ + where: { name: instanceName }, +}); +``` + +## Integration Patterns + +### Channel Integration (WhatsApp Providers) +- **Baileys**: WhatsApp Web with QR code authentication +- **Business API**: Official Meta WhatsApp Business API +- **Evolution API**: Custom WhatsApp integration +- **Pattern**: Extend base channel service classes + +### Chatbot Integration +- **Base classes**: Extend `BaseChatbotService` and `BaseChatbotController` +- **Trigger system**: Support keyword, regex, and advanced triggers +- **Session management**: Handle conversation state per user +- **Available integrations**: EvolutionBot, OpenAI, Dify, Typebot, Chatwoot, Flowise, N8N, EvoAI + +### Event Integration +- **Internal events**: EventEmitter2 for application events +- **External events**: WebSocket, RabbitMQ, SQS, NATS, Pusher +- **Webhook delivery**: Reliable delivery with retry logic + +## Testing Guidelines + +### Current State +- **No formal test suite** currently implemented +- **Manual testing** is the primary approach +- **Integration testing** in development environment + +### Testing Strategy +```typescript +// Place tests in test/ directory as *.test.ts +// Run: npm test (watches test/all.test.ts) + +describe('ExampleService', () => { + it('should create example', async () => { + // Mock external dependencies + // Test business logic + // Assert expected behavior + }); +}); +``` + +### Recommended Approach +- Focus on **critical business logic** in services +- **Mock external dependencies** (WhatsApp APIs, databases) +- **Integration tests** for API endpoints +- **Manual testing** for WhatsApp connection flows + +## Commit & Pull Request Guidelines + +### Conventional Commits (Enforced by commitlint) +```bash +# Use interactive commit tool +npm run commit + +# Commit format: type(scope): subject (max 100 chars) +# Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert, security +``` + +### Examples +- `feat(api): add WhatsApp message status endpoint` +- `fix(baileys): resolve connection timeout issue` +- `docs(readme): update installation instructions` +- `refactor(service): extract common message validation logic` + +### Pull Request Requirements +- **Clear description** of changes and motivation +- **Linked issues** if applicable +- **Migration impact** (specify database provider) +- **Local testing steps** with screenshots/logs +- **Breaking changes** clearly documented + +## Security & Configuration + +### Environment Setup +```bash +# Copy example environment file +cp .env.example .env + +# NEVER commit secrets to version control +# Set DATABASE_PROVIDER before database commands +export DATABASE_PROVIDER=postgresql # or mysql +``` + +### Security Best Practices +- **API key authentication** via `apikey` header +- **Input validation** with JSONSchema7 +- **Rate limiting** on all endpoints +- **Webhook signature validation** +- **Instance-based access control** +- **Secure defaults** for all configurations + +### Vulnerability Reporting +- See `SECURITY.md` for security vulnerability reporting process +- Contact: `contato@evolution-api.com` + +## Communication Standards + +### Language Requirements +- **User communication**: Always respond in Portuguese (PT-BR) +- **Code/comments**: English for technical documentation +- **API responses**: English for consistency +- **Error messages**: Portuguese for user-facing errors + +### Documentation Standards +- **Inline comments**: Document complex business logic +- **API documentation**: Document all public endpoints +- **Integration guides**: Document new integration patterns +- **Migration guides**: Document database schema changes + +## Performance & Scalability + +### Caching Strategy +- **Redis primary**: Distributed caching for production +- **Node-cache fallback**: Local caching when Redis unavailable +- **TTL strategy**: Appropriate cache expiration per data type +- **Cache invalidation**: Proper invalidation on data changes + +### Connection Management +- **Database**: Prisma connection pooling +- **WhatsApp**: One connection per instance with lifecycle management +- **Redis**: Connection pooling and retry logic +- **External APIs**: Rate limiting and retry with exponential backoff + +### Monitoring & Observability +- **Structured logging**: Pino logger with correlation IDs +- **Error tracking**: Comprehensive error scenarios +- **Health checks**: Instance status and connection monitoring +- **Telemetry**: Usage analytics (non-sensitive data only) + diff --git a/CHANGELOG.md b/CHANGELOG.md index d29a9500d..5102b5375 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,424 @@ -# 2.2.0 (develop) +# 2.3.7 (2025-12-05) + +### Features + +* **WhatsApp Business Meta Templates**: Add update and delete endpoints for Meta templates + - New endpoints to edit and delete WhatsApp Business templates + - Added DTOs and validation schemas for template management + - Enhanced template lifecycle management capabilities + +* **Events API**: Add isLatest and progress to messages.set event + - Allows consumers to know when history sync is complete (isLatest=true) + - Track sync progress percentage through webhooks + - Added extra field to EmitData type for additional payload properties + - Updated all event controllers (webhook, rabbitmq, sqs, websocket, pusher, kafka, nats) + +* **N8N Integration**: Add quotedMessage to payload in sendMessageToBot + - Support for quoted messages in N8N chatbot integration + - Enhanced message context information + +* **WebSocket**: Add wildcard "*" to allow all hosts to connect via websocket + - More flexible host configuration for WebSocket connections + - Improved host validation logic in WebsocketController + +* **Pix Support**: Handle interactive button message for pix + - Support for interactive Pix button messages + - Enhanced payment flow integration + +### Fixed + +* **Baileys Message Processor**: Fix incoming message events not working after reconnection + - Added cleanup logic in mount() to prevent memory leaks from multiple subscriptions + - Recreate messageSubject if it was completed during logout + - Remount messageProcessor in connectToWhatsapp() to ensure subscription is active + - Fixed issue where onDestroy() calls complete() on RxJS Subject, making it permanently closed + - Ensures old subscriptions are properly cleaned up before creating new ones + +* **Baileys Authentication**: Resolve "waiting for message" state after reconnection + - Fixed Redis keys not being properly removed during instance logout + - Prevented loading of old/invalid cryptographic keys on reconnection + - Fixed blocking state where instances authenticate but cannot send messages + - Ensures new credentials (creds) are properly used after reconnection + +* **OnWhatsapp Cache**: Prevent unique constraint errors and optimize database writes + - Fixed `Unique constraint failed on the fields: (remoteJid)` error when sending to groups + - Refactored query to use OR condition finding by jidOptions or remoteJid + - Added deep comparison to skip unnecessary database updates + - Replaced sequential processing with Promise.allSettled for parallel execution + - Sorted JIDs alphabetically in jidOptions for accurate change detection + - Added normalizeJid helper function for cleaner code + +* **Proxy Integration**: Fix "Media upload failed on all hosts" error when using proxy + - Created makeProxyAgentUndici() for Undici-compatible proxy agents + - Fixed compatibility with Node.js 18+ native fetch() implementation + - Replaced traditional HttpsProxyAgent/SocksProxyAgent with Undici ProxyAgent + - Maintained legacy makeProxyAgent() for Axios compatibility + - Fixed protocol handling in makeProxyAgent to prevent undefined errors + +* **WhatsApp Business API**: Fix base64, filename and caption handling + - Corrected base64 media conversion in Business API + - Fixed filename handling for document messages + - Improved caption processing for media messages + - Enhanced remoteJid validation and processing + +* **Chat Service**: Fix fetchChats and message panel errors + - Fixed cleanMessageData errors in Manager message panel + - Improved chat fetching reliability + - Enhanced message data sanitization + +* **Contact Filtering**: Apply where filters correctly in findContacts endpoint + - Fixed endpoint to process all where clause fields (id, remoteJid, pushName) + - Previously only processed remoteJid field, ignoring other filters + - Added remoteJid field to contactValidateSchema for proper validation + - Maintained multi-tenant isolation with instanceId filtering + - Allows filtering contacts by any supported field instead of returning all contacts + +* **Chatwoot and Baileys Integration**: Multiple integration improvements + - Enhanced code formatting and consistency + - Fixed integration issues between Chatwoot and Baileys services + - Improved message handling and delivery + +* **Baileys Message Loss**: Prevent message loss from WhatsApp stub placeholders + - Fixed messages being lost and not saved to database, especially for channels/newsletters (@lid) + - Detects WhatsApp stubs through messageStubParameters containing 'Message absent from node' + - Prevents adding stubs to duplicate message cache + - Allows real message to be processed when it arrives after decryption + - Maintains stub discard to avoid saving empty placeholders + +* **Database Contacts**: Respect DATABASE_SAVE_DATA_CONTACTS in contact updates + - Added missing conditional checks for DATABASE_SAVE_DATA_CONTACTS configuration + - Fixed profile picture updates attempting to save when database save is disabled + - Fixed unawaited promise in contacts.upsert handler + +* **Prisma/PostgreSQL**: Add unique constraint to Chat model + - Generated migration to add unique index on instanceId and remoteJid + - Added deduplication step before creating index to prevent constraint violations + - Prevents chat duplication in database + +* **MinIO Upload**: Handle messageContextInfo in media upload to prevent MinIO errors + - Prevents errors when uploading media with messageContextInfo metadata + - Improved error handling for media storage operations + +* **Typebot**: Fix message routing for @lid JIDs + - Typebot now responds to messages from JIDs ending with @lid + - Maintains complete JID for @lid instead of extracting only number + - Fixed condition: `remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0]` + - Handles both @s.whatsapp.net and @lid message formats + +* **Message Filtering**: Unify remoteJid filtering using OR with remoteJidAlt + - Improved message filtering with alternative JID support + - Better handling of messages with different JID formats + +* **@lid Integration**: Multiple fixes for @lid problems, message events and chatwoot errors + - Reorganized imports and improved message handling in BaileysStartupService + - Enhanced remoteJid processing to handle @lid cases + - Improved jid normalization and type safety in Chatwoot integration + - Streamlined message handling logic and cache management + - Refactored message handling and polling updates with decryption logic for poll votes + - Improved event processing flow for various message types + +* **Chatwoot Contacts**: Fix contact duplication error on import + - Resolved 'ON CONFLICT DO UPDATE command cannot affect row a second time' error + - Removed attempt to update identifier field in conflict (part of constraint) + - Changed to update only updated_at field: `updated_at = NOW()` + - Allows duplicate contacts to be updated correctly without errors + +* **Chatwoot Service**: Fix async handling in update_last_seen method + - Added missing await for chatwootRequest in read message processing + - Prevents service failure when processing read messages + +* **Metrics Access**: Fix IP validation including x-forwarded-for + - Uses all IPs including x-forwarded-for header when checking metrics access + - Improved security and access control for metrics endpoint + +### Dependencies + +* **Baileys**: Updated to version 7.0.0-rc.9 + - Latest release candidate with multiple improvements and bug fixes + +* **AWS SDK**: Updated packages to version 3.936.0 + - Enhanced functionality and compatibility + - Performance improvements + +### Code Quality & Refactoring + +* **Template Management**: Remove unused template edit/delete DTOs after refactoring +* **Proxy Utilities**: Improve makeProxyAgent for Undici compatibility +* **Code Formatting**: Enhance code formatting and consistency across services +* **BaileysStartupService**: Fix indentation and remove unnecessary blank lines +* **Event Controllers**: Guard extra spread and prevent core field override in all event controllers +* **Import Organization**: Reorganize imports for better code structure and maintainability + +# 2.3.6 (2025-10-21) + +### Features + +* **Baileys, Chatwoot, OnWhatsapp Cache**: Multiple implementations and fixes + - Fixed cache for PN, LID and g.us numbers to send correct number + - Fixed audio and document sending via Chatwoot in Baileys channel + - Multiple fixes in Chatwoot integration + - Fixed ignored messages when receiving leads + +### Fixed + +* **Baileys**: Fix buffer storage in database + - Correctly save Uint8Array values to database +* **Baileys**: Simplify logging of messageSent object + - Fixed "this.isZero not is function" error + +### Chore + +* **Version**: Bump version to 2.3.6 and update Baileys dependency to 7.0.0-rc.6 +* **Workflows**: Update checkout step to include submodules + - Added 'submodules: recursive' option to checkout step in multiple workflow files to ensure submodules are properly initialized during CI/CD processes +* **Manager**: Update asset files and install process + - Updated subproject reference in evolution-manager-v2 to the latest commit + - Enhanced the manager_install.sh script to include npm install and build steps + - Replaced old JavaScript asset file with a new version for improved performance + - Added a new CSS file for consistent styling across the application + +# 2.3.5 (2025-10-15) + +### Features + +* **Chatwoot Enhancements**: Comprehensive improvements to message handling, editing, deletion and i18n +* **Participants Data**: Add participantsData field maintaining backward compatibility for group participants +* **LID to Phone Number**: Convert LID to phoneNumber on group participants +* **Docker Configurations**: Add Kafka and frontend services to Docker configurations + +### Fixed + +* **Kafka Migration**: Fixed PostgreSQL migration error for Kafka integration + - Corrected table reference from `"public"."Instance"` to `"Instance"` in foreign key constraint + - Fixed `ERROR: relation "public.Instance" does not exist` issue in migration `20250918182355_add_kafka_integration` + - Aligned table naming convention with other Evolution API migrations for consistency + - Resolved database migration failure that prevented Kafka integration setup +* **Update Baileys Version**: v7.0.0-rc.5 with compatibility fixes + - Fixed assertSessions signature compatibility using type assertion + - Fixed incompatibility in voice call (wavoip) with new Baileys version + - Handle undefined status in update by defaulting to 'DELETED' +* **Chatwoot Improvements**: Multiple fixes for enhanced reliability + - Correct chatId extraction for non-group JIDs + - Resolve webhook timeout on deletion with 5+ images + - Improve error handling in Chatwoot messages + - Adjust conversation verification logic and cache + - Optimize conversation reopening logic and connection notification + - Fix conversation reopening and connection loop +* **Baileys Message Handling**: Enhanced message processing + - Add warning log for messages not found + - Fix message verification in Baileys service + - Simplify linkPreview handling in BaileysStartupService +* **Media Validation**: Fix media content validation +* **PostgreSQL Connection**: Refactor connection with PostgreSQL and improve message handling + +### Code Quality & Refactoring + +* **Exponential Backoff**: Implement exponential backoff patterns and extract magic numbers to constants +* **TypeScript Build**: Update TypeScript build process and dependencies + +### + +# 2.3.4 (2025-09-23) + +### Features + +* **Kafka Integration**: Added Apache Kafka event integration for real-time event streaming + - New Kafka controller, router, and schema for event publishing + - Support for instance-specific and global event topics + - Configurable SASL/SSL authentication and connection settings + - Auto-creation of topics with configurable partitions and replication + - Consumer group management for reliable event processing + - Integration with existing event manager for seamless event distribution + +* **Evolution Manager v2 Open Source**: Evolution Manager v2 is now available as open source + - Added as git submodule with HTTPS URL for easy access + - Complete open source setup with Apache 2.0 license + Evolution API custom conditions + - GitHub templates for issues, pull requests, and workflows + - Comprehensive documentation and contribution guidelines + - Docker support for development and production environments + - CI/CD workflows for code quality, security audits, and automated builds + - Multi-language support (English, Portuguese, Spanish, French) + - Modern React + TypeScript + Vite frontend with Tailwind CSS + +* **EvolutionBot Enhancements**: Improved EvolutionBot functionality and message handling + - Implemented splitMessages functionality for better message segmentation + - Added linkPreview support for enhanced message presentation + - Centralized split logic across chatbot services for consistency + - Enhanced message formatting and delivery capabilities + +### Fixed + +* **MySQL Schema**: Fixed invalid default value errors for `createdAt` fields in `Evoai` and `EvoaiSetting` models + - Changed `@default(now())` to `@default(dbgenerated("CURRENT_TIMESTAMP"))` for MySQL compatibility + - Added missing relation fields (`N8n`, `N8nSetting`, `Evoai`, `EvoaiSetting`) in Instance model + - Resolved Prisma schema validation errors for MySQL provider + +* **Prisma Schema Validation**: Fixed `instanceName` field error in message creation + - Removed invalid `instanceName` field from message objects before database insertion + - Resolved `Unknown argument 'instanceName'` Prisma validation error + - Streamlined message data structure to match Prisma schema requirements + +* **Media Message Processing**: Enhanced media handling across chatbot services + - Fixed base64 conversion in EvoAI service for proper image processing + - Converted ArrayBuffer to base64 string using `Buffer.from().toString('base64')` + - Improved media URL handling and base64 encoding for better chatbot integration + - Enhanced image message detection and processing workflow + +* **Evolution Manager v2 Linting**: Resolved ESLint configuration conflicts + - Disabled conflicting Prettier rules in ESLint configuration + - Added comprehensive rule overrides for TypeScript and React patterns + - Fixed import ordering and code formatting issues + - Updated security vulnerabilities in dependencies (Vite, esbuild) + +### Code Quality & Refactoring + +* **Chatbot Services**: Streamlined media message handling across all chatbot integrations + - Standardized base64 and mediaUrl processing patterns + - Improved code readability and maintainability in media handling logic + - Enhanced error handling for media download and conversion processes + - Unified image message detection across different chatbot services + +* **Database Operations**: Improved data consistency and validation + - Enhanced Prisma schema compliance across all message operations + - Removed redundant instance name references for better data integrity + - Optimized message creation workflow with proper field validation + +### Environment Variables + +* Added comprehensive Kafka configuration options: + - `KAFKA_ENABLED`, `KAFKA_CLIENT_ID`, `KAFKA_BROKERS` + - `KAFKA_CONSUMER_GROUP_ID`, `KAFKA_TOPIC_PREFIX` + - `KAFKA_SASL_*` and `KAFKA_SSL_*` for authentication + - `KAFKA_EVENTS_*` for event type configuration + +# 2.3.3 (2025-09-18) + +### Features + +* Add extra fields to object sent to Flowise bot +* Add Prometheus-compatible /metrics endpoint (gated by PROMETHEUS_METRICS) +* Implement linkPreview support for Evolution Bot + +### Fixed + +* Address Path Traversal vulnerability in /assets endpoint by implementing security checks +* Configure Husky and lint-staged for automated code quality checks on commits and pushes +* Convert mediaKey from media messages to avoid bad decrypt errors +* Improve code formatting for better readability in WhatsApp service files +* Format messageGroupId assignment for improved readability +* Improve linkPreview implementation based on PR feedback +* Clean up code formatting for linkPreview implementation +* Use 'unknown' as fallback for clientName label +* Remove abort process when status is paused, allowing the chatbot return after the time expires and after being paused due to human interaction (stopBotFromMe) +* Enhance message content sanitization in Baileys service and improve message retrieval logic in Chatwoot service +* Integrate Typebot status change events for webhook in chatbot controller and service +* Mimetype of videos video + +### Security + +* **CRITICAL**: Fixed Path Traversal vulnerability in /assets endpoint that allowed unauthenticated local file read +* Customizable Websockets Security + +### Testing + +* Baileys Updates: v7.0.0-rc.3 ([Link](https://github.com/WhiskeySockets/Baileys/releases/tag/v7.0.0-rc.3)) + +# 2.3.2 (2025-09-02) + +### Features + +* Add support to socks proxy + +### Fixed + +* Added key id into webhook payload in n8n service +* Enhance RabbitMQ controller with improved connection management and shutdown procedures +* Convert outgoing images to JPEG before sending with Chatwoot +* Update baileys dependency to version 6.7.19 + +# 2.3.1 (2025-07-29) + +### Feature + +* Add BaileysMessageProcessor for improved message handling and integrate rxjs for asynchronous processing +* Enhance message processing with retry logic for error handling + +### Fixed + +* Update Baileys Version +* Update Dockerhub Repository and Delete Config Session Variable +* Fixed sending variables in typebot +* Add unreadMessages in the response +* Phone number as message ID for Evo AI +* Fix upload to s3 when media message +* Simplify edited message check in BaileysStartupService +* Avoid corrupting URLs with query strings +* Removed CONFIG_SESSION_PHONE_VERSION environment variable + +# 2.3.0 (2025-06-17 09:19) + +### Feature + +* Add support to get Catalogs and Collections with new routes: '{{baseUrl}}/chat/fetchCatalogs' and '{{baseUrl}}/chat/fetchCollections' +* Add NATS integration support to the event system +* Add message location support meta +* Add S3_SKIP_POLICY env variable to disable setBucketPolicy for incompatible providers +* Add EvoAI integration with models, services, and routes +* Add N8n integration with models, services, and routes + +### Fixed + +* Shell injection vulnerability +* Update Baileys Version v6.7.18 +* Audio send duplicate from chatwoot +* Chatwoot csat creating new conversation in another language +* Refactor SQS controller to correct bug in sqs events by instance +* Adjustin cloud api send audio and video +* Preserve animation in GIF and WebP stickers +* Preventing use conversation from other inbox for the same user +* Ensure full WhatsApp compatibility for audio conversion (libopus, 48kHz, mono) +* Enhance message fetching and processing logic +* Added lid on whatsapp numbers router +* Now if the CONFIG_SESSION_PHONE_VERSION variable is not filled in it automatically searches for the most updated version + +### Security + +* Change execSync to execFileSync +* Enhance WebSocket authentication and connection handling + +# 2.2.3 (2025-02-03 11:52) + +### Fixed + +* Fix cache in local file system +* Update Baileys Version + +# 2.2.2 (2025-01-31 06:55) + +### Features + +* Added prefix key to queue name in RabbitMQ + +### Fixed + +* Update Baileys Version + +# 2.2.1 (2025-01-22 14:37) + +### Features + +* Retry system for send webhooks +* Message filtering to support timestamp range queries +* Chats filtering to support timestamp range queries + +### Fixed + +* Correction of webhook global +* Fixed send audio with whatsapp cloud api +* Refactor on fetch chats +* Refactor on Evolution Channel + +# 2.2.0 (2024-10-18 10:00) ### Features diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..7c0e87a04 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,223 @@ +# CLAUDE.md + +This file provides comprehensive guidance to Claude AI when working with the Evolution API codebase. + +## Project Overview + +**Evolution API** is a powerful, production-ready REST API for WhatsApp communication that supports multiple WhatsApp providers: +- **Baileys** (WhatsApp Web) - Open-source WhatsApp Web client +- **Meta Business API** - Official WhatsApp Business API +- **Evolution API** - Custom WhatsApp integration + +Built 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**. + +## Common Development Commands + +### Build and Run +```bash +# Development +npm run dev:server # Run in development with hot reload (tsx watch) + +# Production +npm run build # TypeScript check + tsup build +npm run start:prod # Run production build + +# Direct execution +npm start # Run with tsx +``` + +### Code Quality +```bash +npm run lint # ESLint with auto-fix +npm run lint:check # ESLint check only +npm run commit # Interactive commit with commitizen +``` + +### Database Management +```bash +# Set database provider first +export DATABASE_PROVIDER=postgresql # or mysql + +# Generate Prisma client (automatically uses DATABASE_PROVIDER env) +npm run db:generate + +# Deploy migrations (production) +npm run db:deploy # Unix/Mac +npm run db:deploy:win # Windows + +# Development migrations (with sync to provider folder) +npm run db:migrate:dev # Unix/Mac +npm run db:migrate:dev:win # Windows + +# Open Prisma Studio +npm run db:studio + +# Development migrations +npm run db:migrate:dev # Unix/Mac +npm run db:migrate:dev:win # Windows +``` + +### Testing +```bash +npm test # Run tests with watch mode +``` + +## Architecture Overview + +### Core Structure +- **Multi-tenant SaaS**: Complete instance isolation with per-tenant authentication +- **Multi-provider database**: PostgreSQL and MySQL via Prisma ORM with provider-specific schemas and migrations +- **WhatsApp integrations**: Baileys, Meta Business API, and Evolution API with unified interface +- **Event-driven architecture**: EventEmitter2 for internal events + WebSocket, RabbitMQ, SQS, NATS, Pusher for external events +- **Microservices pattern**: Modular integrations for chatbots, storage, and external services + +### Directory Layout +``` +src/ +├── api/ +│ ├── controllers/ # HTTP route handlers (thin layer) +│ ├── services/ # Business logic (core functionality) +│ ├── repository/ # Data access layer (Prisma) +│ ├── dto/ # Data Transfer Objects (simple classes) +│ ├── guards/ # Authentication/authorization middleware +│ ├── integrations/ # External service integrations +│ │ ├── channel/ # WhatsApp providers (Baileys, Business API, Evolution) +│ │ ├── chatbot/ # AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot) +│ │ ├── event/ # Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher) +│ │ └── storage/ # File storage (S3, MinIO) +│ ├── routes/ # Express route definitions (RouterBroker pattern) +│ └── types/ # TypeScript type definitions +├── config/ # Environment and app configuration +├── cache/ # Redis and local cache implementations +├── exceptions/ # Custom HTTP exception classes +├── utils/ # Shared utilities and helpers +└── validate/ # JSONSchema7 validation schemas +``` + +### Key Integration Points + +**Channel Integrations** (`src/api/integrations/channel/`): +- **Baileys**: WhatsApp Web client with QR code authentication +- **Business API**: Official Meta WhatsApp Business API +- **Evolution API**: Custom WhatsApp integration +- Connection lifecycle management per instance with automatic reconnection + +**Chatbot Integrations** (`src/api/integrations/chatbot/`): +- **EvolutionBot**: Native chatbot with trigger system +- **Chatwoot**: Customer service platform integration +- **Typebot**: Visual chatbot flow builder +- **OpenAI**: AI capabilities including GPT and Whisper (audio transcription) +- **Dify**: AI agent workflow platform +- **Flowise**: LangChain visual builder +- **N8N**: Workflow automation platform +- **EvoAI**: Custom AI integration + +**Event Integrations** (`src/api/integrations/event/`): +- **WebSocket**: Real-time Socket.io connections +- **RabbitMQ**: Message queue for async processing +- **Amazon SQS**: Cloud-based message queuing +- **NATS**: High-performance messaging system +- **Pusher**: Real-time push notifications + +**Storage Integrations** (`src/api/integrations/storage/`): +- **AWS S3**: Cloud object storage +- **MinIO**: Self-hosted S3-compatible storage +- Media file management and URL generation + +### Database Schema Management +- Separate schema files: `postgresql-schema.prisma` and `mysql-schema.prisma` +- Environment variable `DATABASE_PROVIDER` determines active database +- Migration folders are provider-specific and auto-selected during deployment + +### Authentication & Security +- **API key-based authentication** via `apikey` header (global or per-instance) +- **Instance-specific tokens** for WhatsApp connection authentication +- **Guards system** for route protection and authorization +- **Input validation** using JSONSchema7 with RouterBroker `dataValidate` +- **Rate limiting** and security middleware +- **Webhook signature validation** for external integrations + +## Important Implementation Details + +### WhatsApp Instance Management +- Each WhatsApp connection is an "instance" with unique name +- Instance data stored in database with connection state +- Session persistence in database or file system (configurable) +- Automatic reconnection handling with exponential backoff + +### Message Queue Architecture +- Supports RabbitMQ, Amazon SQS, and WebSocket for events +- Event types: message.received, message.sent, connection.update, etc. +- Configurable per instance which events to send + +### Media Handling +- Local storage or S3/Minio for media files +- Automatic media download from WhatsApp +- Media URL generation for external access +- Support for audio transcription via OpenAI + +### Multi-tenancy Support +- Instance isolation at database level +- Separate webhook configurations per instance +- Independent integration settings per instance + +## Environment Configuration + +Key environment variables are defined in `.env.example`. The system uses a strongly-typed configuration system via `src/config/env.config.ts`. + +Critical configurations: +- `DATABASE_PROVIDER`: postgresql or mysql +- `DATABASE_CONNECTION_URI`: Database connection string +- `AUTHENTICATION_API_KEY`: Global API authentication +- `REDIS_ENABLED`: Enable Redis cache +- `RABBITMQ_ENABLED`/`SQS_ENABLED`: Message queue options + +## Development Guidelines + +The project follows comprehensive development standards defined in `.cursor/rules/`: + +### Core Principles +- **Always respond in Portuguese (PT-BR)** for user communication +- **Follow established architecture patterns** (Service Layer, RouterBroker, etc.) +- **Robust error handling** with retry logic and graceful degradation +- **Multi-database compatibility** (PostgreSQL and MySQL) +- **Security-first approach** with input validation and rate limiting +- **Performance optimizations** with Redis caching and connection pooling + +### Code Standards +- **TypeScript strict mode** with full type coverage +- **JSONSchema7** for input validation (not class-validator) +- **Conventional Commits** enforced by commitlint +- **ESLint + Prettier** for code formatting +- **Service Object pattern** for business logic +- **RouterBroker pattern** for route handling with `dataValidate` + +### Architecture Patterns +- **Multi-tenant isolation** at database and instance level +- **Event-driven communication** with EventEmitter2 +- **Microservices integration** pattern for external services +- **Connection pooling** and lifecycle management +- **Caching strategy** with Redis primary and Node-cache fallback + +## Testing Approach + +Currently, the project has minimal formal testing infrastructure: +- **Manual testing** is the primary approach +- **Integration testing** in development environment +- **No unit test suite** currently implemented +- Test files can be placed in `test/` directory as `*.test.ts` +- Run `npm test` for watch mode development testing + +### Recommended Testing Strategy +- Focus on **critical business logic** in services +- **Mock external dependencies** (WhatsApp APIs, databases) +- **Integration tests** for API endpoints +- **Manual testing** for WhatsApp connection flows + +## Deployment Considerations + +- Docker support with `Dockerfile` and `docker-compose.yaml` +- Graceful shutdown handling for connections +- Health check endpoints for monitoring +- Sentry integration for error tracking +- Telemetry for usage analytics (non-sensitive data only) \ No newline at end of file diff --git a/Docker/kafka/docker-compose.yaml b/Docker/kafka/docker-compose.yaml new file mode 100644 index 000000000..dc1c794e0 --- /dev/null +++ b/Docker/kafka/docker-compose.yaml @@ -0,0 +1,51 @@ +version: '3.3' + +services: + zookeeper: + container_name: zookeeper + image: confluentinc/cp-zookeeper:7.5.0 + environment: + - ZOOKEEPER_CLIENT_PORT=2181 + - ZOOKEEPER_TICK_TIME=2000 + - ZOOKEEPER_SYNC_LIMIT=2 + volumes: + - zookeeper_data:/var/lib/zookeeper/ + ports: + - 2181:2181 + + kafka: + container_name: kafka + image: confluentinc/cp-kafka:7.5.0 + depends_on: + - zookeeper + environment: + - KAFKA_BROKER_ID=1 + - KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 + - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,OUTSIDE:PLAINTEXT + - KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092,OUTSIDE://host.docker.internal:9094 + - KAFKA_INTER_BROKER_LISTENER_NAME=PLAINTEXT + - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 + - KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 + - KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 + - KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 + - KAFKA_AUTO_CREATE_TOPICS_ENABLE=true + - KAFKA_LOG_RETENTION_HOURS=168 + - KAFKA_LOG_SEGMENT_BYTES=1073741824 + - KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS=300000 + - KAFKA_COMPRESSION_TYPE=gzip + ports: + - 29092:29092 + - 9092:9092 + - 9094:9094 + volumes: + - kafka_data:/var/lib/kafka/data + +volumes: + zookeeper_data: + kafka_data: + + +networks: + evolution-net: + name: evolution-net + driver: bridge \ No newline at end of file diff --git a/Docker/scripts/deploy_database.sh b/Docker/scripts/deploy_database.sh index fde46d120..fea58ff85 100755 --- a/Docker/scripts/deploy_database.sh +++ b/Docker/scripts/deploy_database.sh @@ -6,7 +6,7 @@ if [ "$DOCKER_ENV" != "true" ]; then export_env_vars fi -if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" ]]; then +if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" || "$DATABASE_PROVIDER" == "psql_bouncer" ]]; then export DATABASE_URL echo "Deploying migrations for $DATABASE_PROVIDER" echo "Database URL: $DATABASE_URL" diff --git a/Docker/scripts/generate_database.sh b/Docker/scripts/generate_database.sh index 892682ef5..248c6cf23 100644 --- a/Docker/scripts/generate_database.sh +++ b/Docker/scripts/generate_database.sh @@ -6,7 +6,7 @@ if [ "$DOCKER_ENV" != "true" ]; then export_env_vars fi -if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" ]]; then +if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" || "$DATABASE_PROVIDER" == "psql_bouncer" ]]; then export DATABASE_URL echo "Generating database for $DATABASE_PROVIDER" echo "Database URL: $DATABASE_URL" @@ -20,4 +20,4 @@ if [[ "$DATABASE_PROVIDER" == "postgresql" || "$DATABASE_PROVIDER" == "mysql" ]] else echo "Error: Database provider $DATABASE_PROVIDER invalid." exit 1 -fi +fi \ No newline at end of file diff --git a/Docker/swarm/evolution_api_v2.yaml b/Docker/swarm/evolution_api_v2.yaml index 41c2daa28..ccd31cdf7 100644 --- a/Docker/swarm/evolution_api_v2.yaml +++ b/Docker/swarm/evolution_api_v2.yaml @@ -2,7 +2,7 @@ version: "3.7" services: evolution_v2: - image: atendai/evolution-api:v2.1.2 + image: evoapicloud/evolution-api:v2.3.7 volumes: - evolution_instances:/evolution/instances networks: @@ -34,6 +34,7 @@ services: - RABBITMQ_EVENTS_MESSAGES_UPDATE=false - RABBITMQ_EVENTS_MESSAGES_DELETE=false - RABBITMQ_EVENTS_SEND_MESSAGE=false + - RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE=false - RABBITMQ_EVENTS_CONTACTS_SET=false - RABBITMQ_EVENTS_CONTACTS_UPSERT=false - RABBITMQ_EVENTS_CONTACTS_UPDATE=false @@ -71,6 +72,7 @@ services: - WEBHOOK_EVENTS_MESSAGES_UPDATE=true - WEBHOOK_EVENTS_MESSAGES_DELETE=true - WEBHOOK_EVENTS_SEND_MESSAGE=true + - WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE=true - WEBHOOK_EVENTS_CONTACTS_SET=true - WEBHOOK_EVENTS_CONTACTS_UPSERT=true - WEBHOOK_EVENTS_CONTACTS_UPDATE=true @@ -92,7 +94,6 @@ services: - WEBHOOK_EVENTS_ERRORS_WEBHOOK= - CONFIG_SESSION_PHONE_CLIENT=Evolution API V2 - CONFIG_SESSION_PHONE_NAME=Chrome - - CONFIG_SESSION_PHONE_VERSION=2.3000.1015901307 - QRCODE_LIMIT=30 - OPENAI_ENABLED=true - DIFY_ENABLED=true diff --git a/Dockerfile b/Dockerfile index 4c99317d4..24c4e3bc7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,17 +1,19 @@ -FROM node:20-alpine AS builder +FROM node:24-alpine AS builder RUN apk update && \ - apk add git ffmpeg wget curl bash + apk add --no-cache git ffmpeg wget curl bash openssl -LABEL version="2.2.0" description="Api to control whatsapp features through http requests." +LABEL version="2.3.1" description="Api to control whatsapp features through http requests." LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes" -LABEL contact="contato@atendai.com" +LABEL contact="contato@evolution-api.com" WORKDIR /evolution -COPY ./package.json ./tsconfig.json ./ +COPY ./package*.json ./ +COPY ./tsconfig.json ./ +COPY ./tsup.config.ts ./ -RUN npm install -f +RUN npm ci --silent COPY ./src ./src COPY ./public ./public @@ -19,7 +21,6 @@ COPY ./prisma ./prisma COPY ./manager ./manager COPY ./.env.example ./.env COPY ./runWithProvider.js ./ -COPY ./tsup.config.ts ./ COPY ./Docker ./Docker @@ -29,12 +30,13 @@ RUN ./Docker/scripts/generate_database.sh RUN npm run build -FROM node:20-alpine AS final +FROM node:24-alpine AS final RUN apk update && \ - apk add tzdata ffmpeg bash + apk add tzdata ffmpeg bash openssl ENV TZ=America/Sao_Paulo +ENV DOCKER_ENV=true WORKDIR /evolution @@ -55,4 +57,4 @@ ENV DOCKER_ENV=true EXPOSE 8080 -ENTRYPOINT ["/bin/bash", "-c", ". ./Docker/scripts/deploy_database.sh && npm run start:prod" ] \ No newline at end of file +ENTRYPOINT ["/bin/bash", "-c", ". ./Docker/scripts/deploy_database.sh && npm run start:prod" ] diff --git a/Dockerfile.metrics b/Dockerfile.metrics new file mode 100644 index 000000000..e8d46d040 --- /dev/null +++ b/Dockerfile.metrics @@ -0,0 +1,19 @@ +FROM evoapicloud/evolution-api:latest AS base +WORKDIR /evolution + +# Copiamos apenas o necessário para recompilar o dist com as mudanças locais +COPY tsconfig.json tsup.config.ts package.json ./ +COPY src ./src + +# Recompila usando os node_modules já presentes na imagem base +RUN npm run build + +# Runtime final: reaproveita a imagem oficial e apenas sobrepõe o dist +FROM evoapicloud/evolution-api:latest AS final +WORKDIR /evolution +COPY --from=base /evolution/dist ./dist + +ENV PROMETHEUS_METRICS=true + +# Entrada original da imagem oficial já sobe o app em /evolution + diff --git a/LICENSE b/LICENSE index da01e779d..18ebe6f6b 100644 --- a/LICENSE +++ b/LICENSE @@ -8,7 +8,7 @@ a. LOGO and copyright information: In the process of using Evolution API's front b. Usage Notification Requirement: If Evolution API is used as part of any project, including closed-source systems (e.g., proprietary software), the user is required to display a clear notification within the system that Evolution API is being utilized. This notification should be visible to system administrators and accessible from the system's documentation or settings page. Failure to comply with this requirement may result in the necessity for a commercial license, as determined by the producer. -Please contact contato@atendai.com to inquire about licensing matters. +Please contact contato@evolution-api.com to inquire about licensing matters. 2. As a contributor, you should agree that: @@ -17,5 +17,5 @@ b. Your contributed code may be used for commercial purposes, including but not Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0. -© 2024 Evolution API +© 2025 Evolution API diff --git a/README.md b/README.md index 93197499b..eb7e638c1 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,14 @@
+[![Docker Image](https://img.shields.io/badge/Docker-image-blue)](https://hub.docker.com/r/evoapicloud/evolution-api) [![Whatsapp Group](https://img.shields.io/badge/Group-WhatsApp-%2322BC18)](https://evolution-api.com/whatsapp) [![Discord Community](https://img.shields.io/badge/Discord-Community-blue)](https://evolution-api.com/discord) [![Postman Collection](https://img.shields.io/badge/Postman-Collection-orange)](https://evolution-api.com/postman) [![Documentation](https://img.shields.io/badge/Documentation-Official-green)](https://doc.evolution-api.com) +[![Feature Requests](https://img.shields.io/badge/Feature-Requests-purple)](https://evolutionapi.canny.io/feature-requests) +[![Roadmap](https://img.shields.io/badge/Roadmap-Community-blue)](https://evolutionapi.canny.io/feature-requests) +[![Changelog](https://img.shields.io/badge/Changelog-Updates-green)](https://evolutionapi.canny.io/changelog) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](./LICENSE) [![Support](https://img.shields.io/badge/Donation-picpay-green)](https://app.picpay.com/user/davidsongomes1998) [![Sponsors](https://img.shields.io/badge/Github-sponsor-orange)](https://github.com/sponsors/EvolutionAPI) @@ -51,6 +55,9 @@ Evolution API supports various integrations to enhance its functionality. Below - [RabbitMQ](https://www.rabbitmq.com/): - Receive events from the Evolution API via RabbitMQ. +- [Apache Kafka](https://kafka.apache.org/): + - Receive events from the Evolution API via Apache Kafka for real-time event streaming and processing. + - [Amazon SQS](https://aws.amazon.com/pt/sqs/): - Receive events from the Evolution API via Amazon SQS. @@ -66,6 +73,24 @@ Evolution API supports various integrations to enhance its functionality. Below - Amazon S3 / Minio: - Store media files received in [Amazon S3](https://aws.amazon.com/pt/s3/) or [Minio](https://min.io/). +## Community & Feedback + +We value community input and feedback to continuously improve Evolution API: + +### 🚀 Feature Requests & Roadmap +- **[Feature Requests](https://evolutionapi.canny.io/feature-requests)**: Submit new feature ideas and vote on community proposals +- **[Roadmap](https://evolutionapi.canny.io/feature-requests)**: View planned features and development progress +- **[Changelog](https://evolutionapi.canny.io/changelog)**: Stay updated with the latest releases and improvements + +### 💬 Community Support +- **[WhatsApp Group](https://evolution-api.com/whatsapp)**: Join our community for support and discussions +- **[Discord Community](https://evolution-api.com/discord)**: Real-time chat with developers and users +- **[GitHub Issues](https://github.com/EvolutionAPI/evolution-api/issues)**: Report bugs and technical issues + +### 🔒 Security +- **[Security Policy](./SECURITY.md)**: Guidelines for reporting security vulnerabilities +- **Security Contact**: contato@evolution-api.com + ## Telemetry Notice To continuously improve our services, we have implemented telemetry that collects data on the routes used, the most accessed routes, and the version of the API in use. We would like to assure you that no sensitive or personal data is collected during this process. The telemetry helps us identify improvements and provide a better experience for users. @@ -87,6 +112,7 @@ https://github.com/sponsors/EvolutionAPI We are proud to collaborate with the following content creators who have contributed valuable insights and tutorials about Evolution API: - [Promovaweb](https://www.youtube.com/@promovaweb) +- [Sandeco](https://www.youtube.com/@canalsandeco) - [Comunidade ZDG](https://www.youtube.com/@ComunidadeZDG) - [Francis MNO](https://www.youtube.com/@FrancisMNO) - [Pablo Cabral](https://youtube.com/@pablocabral) @@ -111,8 +137,8 @@ Evolution API is licensed under the Apache License 2.0, with the following addit 2. **Usage Notification Requirement**: If Evolution API is used as part of any project, including closed-source systems (e.g., proprietary software), the user is required to display a clear notification within the system that Evolution API is being utilized. This notification should be visible to system administrators and accessible from the system's documentation or settings page. Failure to comply with this requirement may result in the necessity for a commercial license, as determined by the producer. -Please contact contato@atendai.com to inquire about licensing matters. +Please contact contato@evolution-api.com to inquire about licensing matters. Apart from the specific conditions mentioned above, all other rights and restrictions follow the Apache License 2.0. Detailed information about the Apache License 2.0 can be found at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0). -© 2024 Evolution API \ No newline at end of file +© 2025 Evolution API diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..0e3189d2f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,99 @@ +# Security Policy + +## Supported Versions + +We actively support the following versions of Evolution API with security updates: + +| Version | Supported | +| ------- | ------------------ | +| 2.3.x | ✅ Yes | +| 2.2.x | ✅ Yes | +| 2.1.x | ⚠️ Critical fixes only | +| < 2.1 | ❌ No | + +## Reporting a Vulnerability + +We take security vulnerabilities seriously. If you discover a security vulnerability in Evolution API, please help us by reporting it responsibly. + +### 🔒 Private Disclosure Process + +**Please DO NOT create a public GitHub issue for security vulnerabilities.** + +Instead, please report security vulnerabilities via email to: + +**📧 contato@evolution-api.com** + +### 📋 What to Include + +When reporting a vulnerability, please include: + +- **Description**: A clear description of the vulnerability +- **Impact**: What an attacker could achieve by exploiting this vulnerability +- **Steps to Reproduce**: Detailed steps to reproduce the issue +- **Proof of Concept**: If possible, include a minimal proof of concept +- **Environment**: Version of Evolution API, OS, Node.js version, etc. +- **Suggested Fix**: If you have ideas for how to fix the issue + +### 🕐 Response Timeline + +We will acknowledge receipt of your vulnerability report within **48 hours** and will send you regular updates about our progress. + +- **Initial Response**: Within 48 hours +- **Status Update**: Within 7 days +- **Resolution Timeline**: Varies based on complexity, typically 30-90 days + +### 🎯 Scope + +This security policy applies to: + +- Evolution API core application +- Official Docker images +- Documentation that could lead to security issues + +### 🚫 Out of Scope + +The following are generally considered out of scope: + +- Third-party integrations (Chatwoot, Typebot, etc.) - please report to respective projects +- Issues in dependencies - please report to the dependency maintainers +- Social engineering attacks +- Physical attacks +- Denial of Service attacks + +### 🏆 Recognition + +We believe in recognizing security researchers who help us keep Evolution API secure: + +- We will acknowledge your contribution in our security advisories (unless you prefer to remain anonymous) +- For significant vulnerabilities, we may feature you in our Hall of Fame +- We will work with you on coordinated disclosure timing + +### 📚 Security Best Practices + +For users deploying Evolution API: + +- Always use the latest supported version +- Keep your dependencies up to date +- Use strong authentication methods +- Implement proper network security +- Monitor your logs for suspicious activity +- Follow the principle of least privilege + +### 🔄 Security Updates + +Security updates will be: + +- Released as patch versions (e.g., 2.3.1 → 2.3.2) +- Documented in our [CHANGELOG.md](./CHANGELOG.md) +- Announced in our community channels +- Tagged with security labels in GitHub releases + +## Contact + +For any questions about this security policy, please contact: + +- **Email**: contato@evolution-api.com + +--- + +Thank you for helping keep Evolution API and our community safe! 🛡️ diff --git a/commitlint.config.js b/commitlint.config.js new file mode 100644 index 000000000..9beb860bf --- /dev/null +++ b/commitlint.config.js @@ -0,0 +1,34 @@ +module.exports = { + extends: ['@commitlint/config-conventional'], + rules: { + 'type-enum': [ + 2, + 'always', + [ + 'feat', // New feature + 'fix', // Bug fix + 'docs', // Documentation changes + 'style', // Code style changes (formatting, etc) + 'refactor', // Code refactoring + 'perf', // Performance improvements + 'test', // Adding or updating tests + 'chore', // Maintenance tasks + 'ci', // CI/CD changes + 'build', // Build system changes + 'revert', // Reverting changes + 'security', // Security fixes + ], + ], + 'type-case': [2, 'always', 'lower-case'], + 'type-empty': [2, 'never'], + 'scope-case': [2, 'always', 'lower-case'], + 'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']], + 'subject-empty': [2, 'never'], + 'subject-full-stop': [2, 'never', '.'], + 'header-max-length': [2, 'always', 100], + 'body-leading-blank': [1, 'always'], + 'body-max-line-length': [0, 'always', 150], + 'footer-leading-blank': [1, 'always'], + 'footer-max-line-length': [0, 'always', 150], + }, +}; diff --git a/docker-compose.dev.yaml b/docker-compose.dev.yaml index 2ca3424e5..35868ab71 100644 --- a/docker-compose.dev.yaml +++ b/docker-compose.dev.yaml @@ -15,6 +15,16 @@ services: expose: - 8080 + frontend: + container_name: evolution_frontend + image: evolution/manager:local + build: ./evolution-manager-v2 + restart: always + ports: + - "3000:80" + networks: + - evolution-net + volumes: evolution_instances: diff --git a/docker-compose.yaml b/docker-compose.yaml index b286919c7..e0edee656 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,57 +1,84 @@ +version: "3.8" + services: api: container_name: evolution_api - image: atendai/evolution-api:homolog + image: evoapicloud/evolution-api:latest restart: always depends_on: - redis - - postgres + - evolution-postgres ports: - - 8080:8080 + - "127.0.0.1:8080:8080" volumes: - evolution_instances:/evolution/instances networks: - evolution-net + - dokploy-network env_file: - .env expose: - - 8080 + - "8080" - redis: - image: redis:latest + frontend: + container_name: evolution_frontend + image: evoapicloud/evolution-manager:latest + restart: always + ports: + - "3000:80" networks: - evolution-net - container_name: redis + + redis: + container_name: evolution_redis + image: redis:latest + restart: always command: > redis-server --port 6379 --appendonly yes volumes: - evolution_redis:/data - ports: - - 6379:6379 + networks: + evolution-net: + aliases: + - evolution-redis + dokploy-network: + aliases: + - evolution-redis + expose: + - "6379" - postgres: - container_name: postgres + evolution-postgres: + container_name: evolution_postgres image: postgres:15 - networks: - - evolution-net - command: ["postgres", "-c", "max_connections=1000"] restart: always - ports: - - 5432:5432 + env_file: + - .env + command: + - postgres + - -c + - max_connections=1000 + - -c + - listen_addresses=* environment: - - POSTGRES_PASSWORD=PASSWORD + - POSTGRES_DB=${POSTGRES_DATABASE} + - POSTGRES_USER=${POSTGRES_USERNAME} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data + networks: + - evolution-net + - dokploy-network expose: - - 5432 + - "5432" volumes: evolution_instances: evolution_redis: postgres_data: - networks: evolution-net: name: evolution-net driver: bridge + dokploy-network: + external: true \ No newline at end of file diff --git a/env.example b/env.example new file mode 100644 index 000000000..5fe448b82 --- /dev/null +++ b/env.example @@ -0,0 +1,302 @@ +# =========================================== +# EVOLUTION API - CONFIGURAÇÃO DE AMBIENTE +# =========================================== + +# =========================================== +# SERVIDOR +# =========================================== +SERVER_NAME=evolution +SERVER_TYPE=http +SERVER_PORT=8080 +SERVER_URL=http://localhost:8080 +SERVER_DISABLE_DOCS=false +SERVER_DISABLE_MANAGER=false + +# =========================================== +# CORS +# =========================================== +CORS_ORIGIN=* +CORS_METHODS=POST,GET,PUT,DELETE +CORS_CREDENTIALS=true + +# =========================================== +# SSL (opcional) +# =========================================== +SSL_CONF_PRIVKEY= +SSL_CONF_FULLCHAIN= + +# =========================================== +# BANCO DE DADOS +# =========================================== +DATABASE_PROVIDER=postgresql +DATABASE_CONNECTION_URI=postgresql://username:password@localhost:5432/evolution_api +DATABASE_CONNECTION_CLIENT_NAME=evolution + +# Configurações de salvamento de dados +DATABASE_SAVE_DATA_INSTANCE=true +DATABASE_SAVE_DATA_NEW_MESSAGE=true +DATABASE_SAVE_MESSAGE_UPDATE=true +DATABASE_SAVE_DATA_CONTACTS=true +DATABASE_SAVE_DATA_CHATS=true +DATABASE_SAVE_DATA_HISTORIC=true +DATABASE_SAVE_DATA_LABELS=true +DATABASE_SAVE_IS_ON_WHATSAPP=true +DATABASE_SAVE_IS_ON_WHATSAPP_DAYS=7 +DATABASE_DELETE_MESSAGE=false + +# =========================================== +# REDIS +# =========================================== +CACHE_REDIS_ENABLED=true +CACHE_REDIS_URI=redis://localhost:6379 +CACHE_REDIS_PREFIX_KEY=evolution-cache +CACHE_REDIS_TTL=604800 +CACHE_REDIS_SAVE_INSTANCES=true + +# Cache local (fallback) +CACHE_LOCAL_ENABLED=true +CACHE_LOCAL_TTL=86400 + +# =========================================== +# AUTENTICAÇÃO +# =========================================== +AUTHENTICATION_API_KEY=BQYHJGJHJ +AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=false + +# =========================================== +# LOGS +# =========================================== +LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS,WEBSOCKET +LOG_COLOR=true +LOG_BAILEYS=error + +# =========================================== +# INSTÂNCIAS +# =========================================== +DEL_INSTANCE=false +DEL_TEMP_INSTANCES=true + +# =========================================== +# IDIOMA +# =========================================== +LANGUAGE=pt-BR + +# =========================================== +# WEBHOOK +# =========================================== +WEBHOOK_GLOBAL_URL= +WEBHOOK_GLOBAL_ENABLED=false +WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false + +# Eventos de webhook +WEBHOOK_EVENTS_APPLICATION_STARTUP=false +WEBHOOK_EVENTS_INSTANCE_CREATE=false +WEBHOOK_EVENTS_INSTANCE_DELETE=false +WEBHOOK_EVENTS_QRCODE_UPDATED=false +WEBHOOK_EVENTS_MESSAGES_SET=false +WEBHOOK_EVENTS_MESSAGES_UPSERT=false +WEBHOOK_EVENTS_MESSAGES_EDITED=false +WEBHOOK_EVENTS_MESSAGES_UPDATE=false +WEBHOOK_EVENTS_MESSAGES_DELETE=false +WEBHOOK_EVENTS_SEND_MESSAGE=false +WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE=false +WEBHOOK_EVENTS_CONTACTS_SET=false +WEBHOOK_EVENTS_CONTACTS_UPDATE=false +WEBHOOK_EVENTS_CONTACTS_UPSERT=false +WEBHOOK_EVENTS_PRESENCE_UPDATE=false +WEBHOOK_EVENTS_CHATS_SET=false +WEBHOOK_EVENTS_CHATS_UPDATE=false +WEBHOOK_EVENTS_CHATS_UPSERT=false +WEBHOOK_EVENTS_CHATS_DELETE=false +WEBHOOK_EVENTS_CONNECTION_UPDATE=false +WEBHOOK_EVENTS_LABELS_EDIT=false +WEBHOOK_EVENTS_LABELS_ASSOCIATION=false +WEBHOOK_EVENTS_GROUPS_UPSERT=false +WEBHOOK_EVENTS_GROUPS_UPDATE=false +WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=false +WEBHOOK_EVENTS_CALL=false +WEBHOOK_EVENTS_TYPEBOT_START=false +WEBHOOK_EVENTS_TYPEBOT_CHANGE_STATUS=false +WEBHOOK_EVENTS_ERRORS=false +WEBHOOK_EVENTS_ERRORS_WEBHOOK= + +# Configurações de webhook +WEBHOOK_REQUEST_TIMEOUT_MS=30000 +WEBHOOK_RETRY_MAX_ATTEMPTS=10 +WEBHOOK_RETRY_INITIAL_DELAY_SECONDS=5 +WEBHOOK_RETRY_USE_EXPONENTIAL_BACKOFF=true +WEBHOOK_RETRY_MAX_DELAY_SECONDS=300 +WEBHOOK_RETRY_JITTER_FACTOR=0.2 +WEBHOOK_RETRY_NON_RETRYABLE_STATUS_CODES=400,401,403,404,422 + +# =========================================== +# WEBSOCKET +# =========================================== +WEBSOCKET_ENABLED=true +WEBSOCKET_GLOBAL_EVENTS=true +WEBSOCKET_ALLOWED_HOSTS= + +# =========================================== +# RABBITMQ +# =========================================== +RABBITMQ_ENABLED=false +RABBITMQ_GLOBAL_ENABLED=false +RABBITMQ_PREFIX_KEY= +RABBITMQ_EXCHANGE_NAME=evolution_exchange +RABBITMQ_URI= +RABBITMQ_FRAME_MAX=8192 + +# =========================================== +# NATS +# =========================================== +NATS_ENABLED=false +NATS_GLOBAL_ENABLED=false +NATS_PREFIX_KEY= +NATS_EXCHANGE_NAME=evolution_exchange +NATS_URI= + +# =========================================== +# SQS +# =========================================== +SQS_ENABLED=false +SQS_GLOBAL_ENABLED=false +SQS_GLOBAL_FORCE_SINGLE_QUEUE=false +SQS_GLOBAL_PREFIX_NAME=global +SQS_ACCESS_KEY_ID= +SQS_SECRET_ACCESS_KEY= +SQS_ACCOUNT_ID= +SQS_REGION= +SQS_MAX_PAYLOAD_SIZE=1048576 + +# =========================================== +# PUSHER +# =========================================== +PUSHER_ENABLED=false +PUSHER_GLOBAL_ENABLED=false +PUSHER_GLOBAL_APP_ID= +PUSHER_GLOBAL_KEY= +PUSHER_GLOBAL_SECRET= +PUSHER_GLOBAL_CLUSTER= +PUSHER_GLOBAL_USE_TLS=false + +# =========================================== +# WHATSAPP BUSINESS +# =========================================== +WA_BUSINESS_TOKEN_WEBHOOK=evolution +WA_BUSINESS_URL=https://graph.facebook.com +WA_BUSINESS_VERSION=v18.0 +WA_BUSINESS_LANGUAGE=en + +# =========================================== +# CONFIGURAÇÕES DE SESSÃO +# =========================================== +CONFIG_SESSION_PHONE_CLIENT=Evolution API +CONFIG_SESSION_PHONE_NAME=Chrome + +# =========================================== +# QR CODE +# =========================================== +QRCODE_LIMIT=30 +QRCODE_COLOR=#198754 + +# =========================================== +# INTEGRAÇÕES +# =========================================== + +# Typebot +TYPEBOT_ENABLED=false +TYPEBOT_API_VERSION=old +TYPEBOT_SEND_MEDIA_BASE64=false + +# Chatwoot +CHATWOOT_ENABLED=false +CHATWOOT_MESSAGE_DELETE=false +CHATWOOT_MESSAGE_READ=false +CHATWOOT_BOT_CONTACT=true +CHATWOOT_IMPORT_DATABASE_CONNECTION_URI= +CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=false + +# OpenAI +OPENAI_ENABLED=false +OPENAI_API_KEY_GLOBAL= + +# Dify +DIFY_ENABLED=false + +# N8N +N8N_ENABLED=false + +# EvoAI +EVOAI_ENABLED=false + +# Flowise +FLOWISE_ENABLED=false + +# =========================================== +# S3 / MINIO +# =========================================== +S3_ENABLED=false +S3_ACCESS_KEY= +S3_SECRET_KEY= +S3_ENDPOINT= +S3_BUCKET= +S3_PORT=9000 +S3_USE_SSL=false +S3_REGION= +S3_SKIP_POLICY=false +S3_SAVE_VIDEO=false + +# =========================================== +# MÉTRICAS +# =========================================== +PROMETHEUS_METRICS=false +METRICS_AUTH_REQUIRED=false +METRICS_USER= +METRICS_PASSWORD= +METRICS_ALLOWED_IPS= + +# =========================================== +# TELEMETRIA +# =========================================== +TELEMETRY_ENABLED=true +TELEMETRY_URL= + +# =========================================== +# PROXY +# =========================================== +PROXY_HOST= +PROXY_PORT= +PROXY_PROTOCOL= +PROXY_USERNAME= +PROXY_PASSWORD= + +# =========================================== +# CONVERSOR DE ÁUDIO +# =========================================== +API_AUDIO_CONVERTER= +API_AUDIO_CONVERTER_KEY= + +# =========================================== +# FACEBOOK +# =========================================== +FACEBOOK_APP_ID= +FACEBOOK_CONFIG_ID= +FACEBOOK_USER_TOKEN= + +# =========================================== +# SENTRY +# =========================================== +SENTRY_DSN= + +# =========================================== +# EVENT EMITTER +# =========================================== +EVENT_EMITTER_MAX_LISTENERS=50 + +# =========================================== +# PROVIDER +# =========================================== +PROVIDER_ENABLED=false +PROVIDER_HOST= +PROVIDER_PORT=5656 +PROVIDER_PREFIX=evolution diff --git a/evolution-manager-v2 b/evolution-manager-v2 new file mode 160000 index 000000000..f054b9bc2 --- /dev/null +++ b/evolution-manager-v2 @@ -0,0 +1 @@ +Subproject commit f054b9bc28083152d4948f835e3346fd0add39db diff --git a/grafana-dashboard.json.example b/grafana-dashboard.json.example new file mode 100644 index 000000000..f85eb9d6c --- /dev/null +++ b/grafana-dashboard.json.example @@ -0,0 +1,238 @@ +{ + "dashboard": { + "id": null, + "title": "Evolution API Monitoring", + "tags": ["evolution-api", "whatsapp", "monitoring"], + "style": "dark", + "timezone": "browser", + "panels": [ + { + "id": 1, + "title": "API Status", + "type": "stat", + "targets": [ + { + "expr": "up{job=\"evolution-api\"}", + "legendFormat": "API Status" + } + ], + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "0": { + "text": "DOWN", + "color": "red" + }, + "1": { + "text": "UP", + "color": "green" + } + }, + "type": "value" + } + ] + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + } + }, + { + "id": 2, + "title": "Total Instances", + "type": "stat", + "targets": [ + { + "expr": "evolution_instances_total", + "legendFormat": "Total Instances" + } + ], + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + } + }, + { + "id": 3, + "title": "Instance Status Overview", + "type": "piechart", + "targets": [ + { + "expr": "sum by (state) (evolution_instance_state)", + "legendFormat": "{{ state }}" + } + ], + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 8 + } + }, + { + "id": 4, + "title": "Instances by Integration Type", + "type": "piechart", + "targets": [ + { + "expr": "sum by (integration) (evolution_instance_up)", + "legendFormat": "{{ integration }}" + } + ], + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 8 + } + }, + { + "id": 5, + "title": "Instance Uptime", + "type": "table", + "targets": [ + { + "expr": "evolution_instance_up", + "format": "table", + "instant": true + } + ], + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true + }, + "renameByName": { + "instance": "Instance Name", + "integration": "Integration Type", + "Value": "Status" + } + } + } + ], + "fieldConfig": { + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "Status" + }, + "properties": [ + { + "id": "mappings", + "value": [ + { + "options": { + "0": { + "text": "DOWN", + "color": "red" + }, + "1": { + "text": "UP", + "color": "green" + } + }, + "type": "value" + } + ] + } + ] + } + ] + }, + "gridPos": { + "h": 9, + "w": 24, + "x": 0, + "y": 17 + } + }, + { + "id": 6, + "title": "Instance Status Timeline", + "type": "timeseries", + "targets": [ + { + "expr": "evolution_instance_up", + "legendFormat": "{{ instance }} ({{ integration }})" + } + ], + "fieldConfig": { + "defaults": { + "custom": { + "drawStyle": "line", + "lineInterpolation": "stepAfter", + "lineWidth": 2, + "fillOpacity": 10, + "gradientMode": "none", + "spanNulls": false, + "insertNulls": false, + "showPoints": "never", + "pointSize": 5, + "stacking": { + "mode": "none", + "group": "A" + }, + "axisPlacement": "auto", + "axisLabel": "", + "scaleDistribution": { + "type": "linear" + }, + "hideFrom": { + "legend": false, + "tooltip": false, + "vis": false + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "min": 0, + "max": 1 + } + }, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 26 + } + } + ], + "time": { + "from": "now-1h", + "to": "now" + }, + "timepicker": {}, + "templating": { + "list": [] + }, + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": "-- Grafana --", + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "refresh": "30s", + "schemaVersion": 27, + "version": 0, + "links": [] + } +} diff --git a/local_install.sh b/local_install.sh new file mode 100755 index 000000000..529a2c4be --- /dev/null +++ b/local_install.sh @@ -0,0 +1,150 @@ +#!/bin/bash + +# Definir cores para melhor legibilidade +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Função para log +log() { + echo -e "${GREEN}[INFO]${NC} $1" +} +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} +log_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +# Verificar se está rodando como root +if [ "$(id -u)" = "0" ]; then + log_error "Este script não deve ser executado como root" + exit 1 +fi + +# Verificar sistema operacional +OS="$(uname -s)" +case "${OS}" in + Linux*) + if [ ! -x "$(command -v curl)" ]; then + log_warning "Curl não está instalado. Tentando instalar..." + if [ -x "$(command -v apt-get)" ]; then + sudo apt-get update && sudo apt-get install -y curl + elif [ -x "$(command -v yum)" ]; then + sudo yum install -y curl + else + log_error "Não foi possível instalar curl automaticamente. Por favor, instale manualmente." + exit 1 + fi + fi + ;; + Darwin*) + if [ ! -x "$(command -v curl)" ]; then + log_error "Curl não está instalado. Por favor, instale o Xcode Command Line Tools." + exit 1 + fi + ;; + *) + log_error "Sistema operacional não suportado: ${OS}" + exit 1 + ;; +esac + +# Verificar conexão com a internet antes de prosseguir +if ! ping -c 1 8.8.8.8 &> /dev/null; then + log_error "Sem conexão com a internet. Por favor, verifique sua conexão." + exit 1 +fi + +# Adicionar verificação de espaço em disco +REQUIRED_SPACE=1000000 # 1GB em KB +AVAILABLE_SPACE=$(df -k . | awk 'NR==2 {print $4}') +if [ $AVAILABLE_SPACE -lt $REQUIRED_SPACE ]; then + log_error "Espaço em disco insuficiente. Necessário pelo menos 1GB livre." + exit 1 +fi + +# Adicionar tratamento de erro para comandos npm +npm_install_with_retry() { + local max_attempts=3 + local attempt=1 + + while [ $attempt -le $max_attempts ]; do + log "Tentativa $attempt de $max_attempts para npm install" + if npm install; then + return 0 + fi + attempt=$((attempt + 1)) + [ $attempt -le $max_attempts ] && log_warning "Falha na instalação. Tentando novamente em 5 segundos..." && sleep 5 + done + + log_error "Falha ao executar npm install após $max_attempts tentativas" + return 1 +} + +# Adicionar timeout para comandos +execute_with_timeout() { + timeout 300 $@ || log_error "Comando excedeu o tempo limite de 5 minutos: $@" +} + +# Verificar se o NVM já está instalado +if [ -d "$HOME/.nvm" ]; then + log "NVM já está instalado." +else + log "Instalando NVM..." + curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash +fi + +# Carregar o NVM no ambiente atual +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" +[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" + +# Verificar se a versão do Node.js já está instalada +if command -v node >/dev/null 2>&1 && [ "$(node -v)" = "v20.10.0" ]; then + log "Node.js v20.10.0 já está instalado." +else + log "Instalando Node.js v20.10.0..." + nvm install v20.10.0 +fi + +nvm use v20.10.0 + +# Verificar as versões instaladas +log "Verificando as versões instaladas:" +log "Node.js: $(node -v)" +log "npm: $(npm -v)" + +# Instala dependências do projeto +log "Instalando dependências do projeto..." +rm -rf node_modules +npm install + +# Deploy do banco de dados +log "Deploy do banco de dados..." +npm run db:generate +npm run db:deploy + +# Iniciar o projeto +log "Iniciando o projeto..." +if [ "$1" = "-dev" ]; then + npm run dev:server +else + npm run build + npm run start:prod +fi + +log "Instalação concluída com sucesso!" + +# Criar arquivo de log +LOGFILE="./installation_log_$(date +%Y%m%d_%H%M%S).log" +exec 1> >(tee -a "$LOGFILE") +exec 2>&1 + +# Adicionar trap para limpeza em caso de interrupção +cleanup() { + log "Limpando recursos temporários..." + # Adicione comandos de limpeza aqui +} +trap cleanup EXIT diff --git a/manager/dist/assets/images/evolution-logo.png b/manager/dist/assets/images/evolution-logo.png index bd9b3850a..57a1994f3 100644 Binary files a/manager/dist/assets/images/evolution-logo.png and b/manager/dist/assets/images/evolution-logo.png differ diff --git a/manager/dist/assets/index-CFAZX6IV.js b/manager/dist/assets/index-CFAZX6IV.js deleted file mode 100644 index ffa565ffb..000000000 --- a/manager/dist/assets/index-CFAZX6IV.js +++ /dev/null @@ -1,381 +0,0 @@ -var Ww=e=>{throw TypeError(e)};var qI=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var sm=(e,t,n)=>t.has(e)||Ww("Cannot "+n);var R=(e,t,n)=>(sm(e,t,"read from private field"),n?n.call(e):t.get(e)),Ie=(e,t,n)=>t.has(e)?Ww("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),xe=(e,t,n,r)=>(sm(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Je=(e,t,n)=>(sm(e,t,"access private method"),n);var uf=(e,t,n,r)=>({set _(s){xe(e,t,s,n)},get _(){return R(e,t,r)}});var kse=qI((ao,io)=>{function jE(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function jb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var RE={exports:{}},Oh={},PE={exports:{}},ot={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Dd=Symbol.for("react.element"),WI=Symbol.for("react.portal"),GI=Symbol.for("react.fragment"),JI=Symbol.for("react.strict_mode"),QI=Symbol.for("react.profiler"),ZI=Symbol.for("react.provider"),YI=Symbol.for("react.context"),XI=Symbol.for("react.forward_ref"),eD=Symbol.for("react.suspense"),tD=Symbol.for("react.memo"),nD=Symbol.for("react.lazy"),Gw=Symbol.iterator;function rD(e){return e===null||typeof e!="object"?null:(e=Gw&&e[Gw]||e["@@iterator"],typeof e=="function"?e:null)}var ME={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},OE=Object.assign,NE={};function iu(e,t,n){this.props=e,this.context=t,this.refs=NE,this.updater=n||ME}iu.prototype.isReactComponent={};iu.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};iu.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function IE(){}IE.prototype=iu.prototype;function Rb(e,t,n){this.props=e,this.context=t,this.refs=NE,this.updater=n||ME}var Pb=Rb.prototype=new IE;Pb.constructor=Rb;OE(Pb,iu.prototype);Pb.isPureReactComponent=!0;var Jw=Array.isArray,DE=Object.prototype.hasOwnProperty,Mb={current:null},AE={key:!0,ref:!0,__self:!0,__source:!0};function FE(e,t,n){var r,s={},o=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)DE.call(t,r)&&!AE.hasOwnProperty(r)&&(s[r]=t[r]);var l=arguments.length-2;if(l===1)s.children=n;else if(1{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Kl=typeof window>"u"||"Deno"in globalThis;function Or(){}function hD(e,t){return typeof e=="function"?e(t):e}function Tv(e){return typeof e=="number"&&e>=0&&e!==1/0}function BE(e,t){return Math.max(e+(t||0)-Date.now(),0)}function bl(e,t){return typeof e=="function"?e(t):e}function Qr(e,t){return typeof e=="function"?e(t):e}function Zw(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:a,stale:l}=e;if(a){if(r){if(t.queryHash!==Nb(a,t.options))return!1}else if(!Dc(t.queryKey,a))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||s&&s!==t.state.fetchStatus||o&&!o(t))}function Yw(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(gi(t.options.mutationKey)!==gi(o))return!1}else if(!Dc(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Nb(e,t){return((t==null?void 0:t.queryKeyHashFn)||gi)(e)}function gi(e){return JSON.stringify(e,(t,n)=>kv(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Dc(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Dc(e[n],t[n])):!1}function zE(e,t){if(e===t)return e;const n=Xw(e)&&Xw(t);if(n||kv(e)&&kv(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),a=o.length,l=n?[]:{};let c=0;for(let i=0;i{setTimeout(t,e)})}function _v(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?zE(e,t):t}function mD(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function vD(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var UE=Symbol();function VE(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===UE?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var ei,Ko,Ol,yE,yD=(yE=class extends lu{constructor(){super();Ie(this,ei);Ie(this,Ko);Ie(this,Ol);xe(this,Ol,t=>{if(!Kl&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,Ko)||this.setEventListener(R(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,Ko))==null||t.call(this),xe(this,Ko,void 0))}setEventListener(t){var n;xe(this,Ol,t),(n=R(this,Ko))==null||n.call(this),xe(this,Ko,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,ei)!==t&&(xe(this,ei,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,ei)=="boolean"?R(this,ei):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ei=new WeakMap,Ko=new WeakMap,Ol=new WeakMap,yE),Ib=new yD,Nl,qo,Il,bE,bD=(bE=class extends lu{constructor(){super();Ie(this,Nl,!0);Ie(this,qo);Ie(this,Il);xe(this,Il,t=>{if(!Kl&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,qo)||this.setEventListener(R(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,qo))==null||t.call(this),xe(this,qo,void 0))}setEventListener(t){var n;xe(this,Il,t),(n=R(this,qo))==null||n.call(this),xe(this,qo,t(this.setOnline.bind(this)))}setOnline(t){R(this,Nl)!==t&&(xe(this,Nl,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,Nl)}},Nl=new WeakMap,qo=new WeakMap,Il=new WeakMap,bE),kp=new bD;function xD(e){return Math.min(1e3*2**e,3e4)}function HE(e){return(e??"online")==="online"?kp.isOnline():!0}var KE=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function am(e){return e instanceof KE}function qE(e){let t=!1,n=0,r=!1,s,o,a;const l=new Promise((b,y)=>{o=b,a=y}),c=b=>{var y;r||(g(new KE(b)),(y=e.abort)==null||y.call(e))},i=()=>{t=!0},d=()=>{t=!1},p=()=>Ib.isFocused()&&(e.networkMode==="always"||kp.isOnline())&&e.canRun(),f=()=>HE(e.networkMode)&&e.canRun(),h=b=>{var y;r||(r=!0,(y=e.onSuccess)==null||y.call(e,b),s==null||s(),o(b))},g=b=>{var y;r||(r=!0,(y=e.onError)==null||y.call(e,b),s==null||s(),a(b))},m=()=>new Promise(b=>{var y;s=w=>{(r||p())&&b(w)},(y=e.onPause)==null||y.call(e)}).then(()=>{var b;s=void 0,r||(b=e.onContinue)==null||b.call(e)}),x=()=>{if(r)return;let b;const y=n===0?e.initialPromise:void 0;try{b=y??e.fn()}catch(w){b=Promise.reject(w)}Promise.resolve(b).then(h).catch(w=>{var T;if(r)return;const S=e.retry??(Kl?0:3),E=e.retryDelay??xD,C=typeof E=="function"?E(n,w):E,k=S===!0||typeof S=="number"&&np()?void 0:m()).then(()=>{t?g(w):x()})})};return{promise:l,cancel:c,continue:()=>(s==null||s(),l),cancelRetry:i,continueRetry:d,canStart:f,start:()=>(f()?x():m().then(x),l)}}function wD(){let e=[],t=0,n=f=>{f()},r=f=>{f()},s=f=>setTimeout(f,0);const o=f=>{s=f},a=f=>{let h;t++;try{h=f()}finally{t--,t||i()}return h},l=f=>{t?e.push(f):s(()=>{n(f)})},c=f=>(...h)=>{l(()=>{f(...h)})},i=()=>{const f=e;e=[],f.length&&s(()=>{r(()=>{f.forEach(h=>{n(h)})})})};return{batch:a,batchCalls:c,schedule:l,setNotifyFunction:f=>{n=f},setBatchNotifyFunction:f=>{r=f},setScheduler:o}}var cn=wD(),ti,xE,WE=(xE=class{constructor(){Ie(this,ti)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Tv(this.gcTime)&&xe(this,ti,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Kl?1/0:5*60*1e3))}clearGcTimeout(){R(this,ti)&&(clearTimeout(R(this,ti)),xe(this,ti,void 0))}},ti=new WeakMap,xE),Dl,Al,Mr,On,Md,ni,Wr,Js,wE,SD=(wE=class extends WE{constructor(t){super();Ie(this,Wr);Ie(this,Dl);Ie(this,Al);Ie(this,Mr);Ie(this,On);Ie(this,Md);Ie(this,ni);xe(this,ni,!1),xe(this,Md,t.defaultOptions),this.setOptions(t.options),this.observers=[],xe(this,Mr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,xe(this,Dl,CD(this.options)),this.state=t.state??R(this,Dl),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=R(this,On))==null?void 0:t.promise}setOptions(t){this.options={...R(this,Md),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,Mr).remove(this)}setData(t,n){const r=_v(this.state.data,t,this.options);return Je(this,Wr,Js).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Je(this,Wr,Js).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=R(this,On))==null?void 0:r.promise;return(s=R(this,On))==null||s.cancel(t),n?n.then(Or).catch(Or):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(R(this,Dl))}isActive(){return this.observers.some(t=>Qr(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(t=0){return this.state.isInvalidated||this.state.data===void 0||!BE(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,On))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,On))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,Mr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,On)&&(R(this,ni)?R(this,On).cancel({revert:!0}):R(this,On).cancelRetry()),this.scheduleGc()),R(this,Mr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Je(this,Wr,Js).call(this,{type:"invalidate"})}fetch(t,n){var c,i,d;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,On))return R(this,On).continueRetry(),R(this,On).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,s=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>(xe(this,ni,!0),r.signal)})},o=()=>{const p=VE(this.options,n),f={queryKey:this.queryKey,meta:this.meta};return s(f),xe(this,ni,!1),this.options.persister?this.options.persister(p,f,this):p(f)},a={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:o};s(a),(c=this.options.behavior)==null||c.onFetch(a,this),xe(this,Al,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((i=a.fetchOptions)==null?void 0:i.meta))&&Je(this,Wr,Js).call(this,{type:"fetch",meta:(d=a.fetchOptions)==null?void 0:d.meta});const l=p=>{var f,h,g,m;am(p)&&p.silent||Je(this,Wr,Js).call(this,{type:"error",error:p}),am(p)||((h=(f=R(this,Mr).config).onError)==null||h.call(f,p,this),(m=(g=R(this,Mr).config).onSettled)==null||m.call(g,this.state.data,p,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return xe(this,On,qE({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,h,g,m;if(p===void 0){l(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(x){l(x);return}(h=(f=R(this,Mr).config).onSuccess)==null||h.call(f,p,this),(m=(g=R(this,Mr).config).onSettled)==null||m.call(g,p,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:l,onFail:(p,f)=>{Je(this,Wr,Js).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Je(this,Wr,Js).call(this,{type:"pause"})},onContinue:()=>{Je(this,Wr,Js).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),R(this,On).start()}},Dl=new WeakMap,Al=new WeakMap,Mr=new WeakMap,On=new WeakMap,Md=new WeakMap,ni=new WeakMap,Wr=new WeakSet,Js=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...GE(r.data,this.options),fetchMeta:t.meta??null};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=t.error;return am(s)&&s.revert&&R(this,Al)?{...R(this,Al),fetchStatus:"idle"}:{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),cn.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,Mr).notify({query:this,type:"updated",action:t})})},wE);function GE(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:HE(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function CD(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ss,SE,ED=(SE=class extends lu{constructor(t={}){super();Ie(this,Ss);this.config=t,xe(this,Ss,new Map)}build(t,n,r){const s=n.queryKey,o=n.queryHash??Nb(s,n);let a=this.get(o);return a||(a=new SD({cache:this,queryKey:s,queryHash:o,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){R(this,Ss).has(t.queryHash)||(R(this,Ss).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Ss).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Ss).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Ss).get(t)}getAll(){return[...R(this,Ss).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Zw(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Zw(t,r)):n}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){cn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){cn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ss=new WeakMap,SE),Cs,Ln,ri,Es,Ao,CE,TD=(CE=class extends WE{constructor(t){super();Ie(this,Es);Ie(this,Cs);Ie(this,Ln);Ie(this,ri);this.mutationId=t.mutationId,xe(this,Ln,t.mutationCache),xe(this,Cs,[]),this.state=t.state||JE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Cs).includes(t)||(R(this,Cs).push(t),this.clearGcTimeout(),R(this,Ln).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){xe(this,Cs,R(this,Cs).filter(n=>n!==t)),this.scheduleGc(),R(this,Ln).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Cs).length||(this.state.status==="pending"?this.scheduleGc():R(this,Ln).remove(this))}continue(){var t;return((t=R(this,ri))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var s,o,a,l,c,i,d,p,f,h,g,m,x,b,y,w,S,E,C,k;xe(this,ri,qE({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(T,P)=>{Je(this,Es,Ao).call(this,{type:"failed",failureCount:T,error:P})},onPause:()=>{Je(this,Es,Ao).call(this,{type:"pause"})},onContinue:()=>{Je(this,Es,Ao).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,Ln).canRun(this)}));const n=this.state.status==="pending",r=!R(this,ri).canStart();try{if(!n){Je(this,Es,Ao).call(this,{type:"pending",variables:t,isPaused:r}),await((o=(s=R(this,Ln).config).onMutate)==null?void 0:o.call(s,t,this));const P=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,t));P!==this.state.context&&Je(this,Es,Ao).call(this,{type:"pending",context:P,variables:t,isPaused:r})}const T=await R(this,ri).start();return await((i=(c=R(this,Ln).config).onSuccess)==null?void 0:i.call(c,T,t,this.state.context,this)),await((p=(d=this.options).onSuccess)==null?void 0:p.call(d,T,t,this.state.context)),await((h=(f=R(this,Ln).config).onSettled)==null?void 0:h.call(f,T,null,this.state.variables,this.state.context,this)),await((m=(g=this.options).onSettled)==null?void 0:m.call(g,T,null,t,this.state.context)),Je(this,Es,Ao).call(this,{type:"success",data:T}),T}catch(T){try{throw await((b=(x=R(this,Ln).config).onError)==null?void 0:b.call(x,T,t,this.state.context,this)),await((w=(y=this.options).onError)==null?void 0:w.call(y,T,t,this.state.context)),await((E=(S=R(this,Ln).config).onSettled)==null?void 0:E.call(S,void 0,T,this.state.variables,this.state.context,this)),await((k=(C=this.options).onSettled)==null?void 0:k.call(C,void 0,T,t,this.state.context)),T}finally{Je(this,Es,Ao).call(this,{type:"error",error:T})}}finally{R(this,Ln).runNext(this)}}},Cs=new WeakMap,Ln=new WeakMap,ri=new WeakMap,Es=new WeakSet,Ao=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),cn.batch(()=>{R(this,Cs).forEach(r=>{r.onMutationUpdate(t)}),R(this,Ln).notify({mutation:this,type:"updated",action:t})})},CE);function JE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lr,Od,EE,kD=(EE=class extends lu{constructor(t={}){super();Ie(this,lr);Ie(this,Od);this.config=t,xe(this,lr,new Map),xe(this,Od,Date.now())}build(t,n,r){const s=new TD({mutationCache:this,mutationId:++uf(this,Od)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){const n=df(t),r=R(this,lr).get(n)??[];r.push(t),R(this,lr).set(n,r),this.notify({type:"added",mutation:t})}remove(t){var r;const n=df(t);if(R(this,lr).has(n)){const s=(r=R(this,lr).get(n))==null?void 0:r.filter(o=>o!==t);s&&(s.length===0?R(this,lr).delete(n):R(this,lr).set(n,s))}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s.state.status==="pending");return!n||n===t}runNext(t){var r;const n=(r=R(this,lr).get(df(t)))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}clear(){cn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}getAll(){return[...R(this,lr).values()].flat()}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Yw(n,r))}findAll(t={}){return this.getAll().filter(n=>Yw(t,n))}notify(t){cn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return cn.batch(()=>Promise.all(t.map(n=>n.continue().catch(Or))))}},lr=new WeakMap,Od=new WeakMap,EE);function df(e){var t;return((t=e.options.scope)==null?void 0:t.id)??String(e.mutationId)}function _D(e){return{onFetch:(t,n)=>{const r=async()=>{var g,m,x,b,y;const s=t.options,o=(x=(m=(g=t.fetchOptions)==null?void 0:g.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,a=((b=t.state.data)==null?void 0:b.pages)||[],l=((y=t.state.data)==null?void 0:y.pageParams)||[],c={pages:[],pageParams:[]};let i=!1;const d=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?i=!0:t.signal.addEventListener("abort",()=>{i=!0}),t.signal)})},p=VE(t.options,t.fetchOptions),f=async(w,S,E)=>{if(i)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const C={queryKey:t.queryKey,pageParam:S,direction:E?"backward":"forward",meta:t.options.meta};d(C);const k=await p(C),{maxPages:T}=t.options,P=E?vD:mD;return{pages:P(w.pages,k,T),pageParams:P(w.pageParams,S,T)}};let h;if(o&&a.length){const w=o==="backward",S=w?jD:tS,E={pages:a,pageParams:l},C=S(s,E);h=await f(E,C,w)}else{h=await f(c,l[0]??s.initialPageParam);const w=e??a.length;for(let S=1;S{var s,o;return(o=(s=t.options).persister)==null?void 0:o.call(s,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function jD(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Ht,Wo,Go,Fl,Ll,Jo,$l,Bl,TE,RD=(TE=class{constructor(e={}){Ie(this,Ht);Ie(this,Wo);Ie(this,Go);Ie(this,Fl);Ie(this,Ll);Ie(this,Jo);Ie(this,$l);Ie(this,Bl);xe(this,Ht,e.queryCache||new ED),xe(this,Wo,e.mutationCache||new kD),xe(this,Go,e.defaultOptions||{}),xe(this,Fl,new Map),xe(this,Ll,new Map),xe(this,Jo,0)}mount(){uf(this,Jo)._++,R(this,Jo)===1&&(xe(this,$l,Ib.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onFocus())})),xe(this,Bl,kp.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ht).onOnline())})))}unmount(){var e,t;uf(this,Jo)._--,R(this,Jo)===0&&((e=R(this,$l))==null||e.call(this),xe(this,$l,void 0),(t=R(this,Bl))==null||t.call(this),xe(this,Bl,void 0))}isFetching(e){return R(this,Ht).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,Wo).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);if(t===void 0)return this.fetchQuery(e);{const n=this.defaultQueryOptions(e),r=R(this,Ht).build(this,n);return e.revalidateIfStale&&r.isStaleByTime(bl(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(t)}}getQueriesData(e){return R(this,Ht).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=R(this,Ht).get(r.queryHash),o=s==null?void 0:s.state.data,a=hD(t,o);if(a!==void 0)return R(this,Ht).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return cn.batch(()=>R(this,Ht).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ht).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Ht);cn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Ht),r={type:"active",...e};return cn.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=cn.batch(()=>R(this,Ht).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Or).catch(Or)}invalidateQueries(e={},t={}){return cn.batch(()=>{if(R(this,Ht).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=cn.batch(()=>R(this,Ht).findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(Or)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(Or)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,Ht).build(this,t);return n.isStaleByTime(bl(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Or).catch(Or)}fetchInfiniteQuery(e){return e.behavior=_D(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Or).catch(Or)}resumePausedMutations(){return kp.isOnline()?R(this,Wo).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ht)}getMutationCache(){return R(this,Wo)}getDefaultOptions(){return R(this,Go)}setDefaultOptions(e){xe(this,Go,e)}setQueryDefaults(e,t){R(this,Fl).set(gi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,Fl).values()];let n={};return t.forEach(r=>{Dc(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){R(this,Ll).set(gi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,Ll).values()];let n={};return t.forEach(r=>{Dc(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,Go).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Nb(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===UE&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,Go).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ht).clear(),R(this,Wo).clear()}},Ht=new WeakMap,Wo=new WeakMap,Go=new WeakMap,Fl=new WeakMap,Ll=new WeakMap,Jo=new WeakMap,$l=new WeakMap,Bl=new WeakMap,TE),Qn,at,Nd,$n,si,zl,Ts,Id,Ul,Vl,oi,ai,Qo,Hl,gt,oc,jv,Rv,Pv,Mv,Ov,Nv,Iv,QE,kE,PD=(kE=class extends lu{constructor(t,n){super();Ie(this,gt);Ie(this,Qn);Ie(this,at);Ie(this,Nd);Ie(this,$n);Ie(this,si);Ie(this,zl);Ie(this,Ts);Ie(this,Id);Ie(this,Ul);Ie(this,Vl);Ie(this,oi);Ie(this,ai);Ie(this,Qo);Ie(this,Hl,new Set);this.options=n,xe(this,Qn,t),xe(this,Ts,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,at).addObserver(this),nS(R(this,at),this.options)?Je(this,gt,oc).call(this):this.updateResult(),Je(this,gt,Mv).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Dv(R(this,at),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Dv(R(this,at),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Je(this,gt,Ov).call(this),Je(this,gt,Nv).call(this),R(this,at).removeObserver(this)}setOptions(t,n){const r=this.options,s=R(this,at);if(this.options=R(this,Qn).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Qr(this.options.enabled,R(this,at))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Je(this,gt,Iv).call(this),R(this,at).setOptions(this.options),r._defaulted&&!Tp(this.options,r)&&R(this,Qn).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,at),observer:this});const o=this.hasListeners();o&&rS(R(this,at),s,this.options,r)&&Je(this,gt,oc).call(this),this.updateResult(n),o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||bl(this.options.staleTime,R(this,at))!==bl(r.staleTime,R(this,at)))&&Je(this,gt,jv).call(this);const a=Je(this,gt,Rv).call(this);o&&(R(this,at)!==s||Qr(this.options.enabled,R(this,at))!==Qr(r.enabled,R(this,at))||a!==R(this,Qo))&&Je(this,gt,Pv).call(this,a)}getOptimisticResult(t){const n=R(this,Qn).getQueryCache().build(R(this,Qn),t),r=this.createResult(n,t);return OD(this,r)&&(xe(this,$n,r),xe(this,zl,this.options),xe(this,si,R(this,at).state)),r}getCurrentResult(){return R(this,$n)}trackResult(t,n){const r={};return Object.keys(t).forEach(s=>{Object.defineProperty(r,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),n==null||n(s),t[s])})}),r}trackProp(t){R(this,Hl).add(t)}getCurrentQuery(){return R(this,at)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,Qn).defaultQueryOptions(t),r=R(this,Qn).getQueryCache().build(R(this,Qn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Je(this,gt,oc).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,$n)))}createResult(t,n){var k;const r=R(this,at),s=this.options,o=R(this,$n),a=R(this,si),l=R(this,zl),i=t!==r?t.state:R(this,Nd),{state:d}=t;let p={...d},f=!1,h;if(n._optimisticResults){const T=this.hasListeners(),P=!T&&nS(t,n),N=T&&rS(t,r,n,s);(P||N)&&(p={...p,...GE(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:g,errorUpdatedAt:m,status:x}=p;if(n.select&&p.data!==void 0)if(o&&p.data===(a==null?void 0:a.data)&&n.select===R(this,Id))h=R(this,Ul);else try{xe(this,Id,n.select),h=n.select(p.data),h=_v(o==null?void 0:o.data,h,n),xe(this,Ul,h),xe(this,Ts,null)}catch(T){xe(this,Ts,T)}else h=p.data;if(n.placeholderData!==void 0&&h===void 0&&x==="pending"){let T;if(o!=null&&o.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))T=o.data;else if(T=typeof n.placeholderData=="function"?n.placeholderData((k=R(this,Vl))==null?void 0:k.state.data,R(this,Vl)):n.placeholderData,n.select&&T!==void 0)try{T=n.select(T),xe(this,Ts,null)}catch(P){xe(this,Ts,P)}T!==void 0&&(x="success",h=_v(o==null?void 0:o.data,T,n),f=!0)}R(this,Ts)&&(g=R(this,Ts),h=R(this,Ul),m=Date.now(),x="error");const b=p.fetchStatus==="fetching",y=x==="pending",w=x==="error",S=y&&b,E=h!==void 0;return{status:x,fetchStatus:p.fetchStatus,isPending:y,isSuccess:x==="success",isError:w,isInitialLoading:S,isLoading:S,data:h,dataUpdatedAt:p.dataUpdatedAt,error:g,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>i.dataUpdateCount||p.errorUpdateCount>i.errorUpdateCount,isFetching:b,isRefetching:b&&!y,isLoadingError:w&&!E,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:w&&E,isStale:Db(t,n),refetch:this.refetch}}updateResult(t){const n=R(this,$n),r=this.createResult(R(this,at),this.options);if(xe(this,si,R(this,at).state),xe(this,zl,this.options),R(this,si).data!==void 0&&xe(this,Vl,R(this,at)),Tp(r,n))return;xe(this,$n,r);const s={},o=()=>{if(!n)return!0;const{notifyOnChangeProps:a}=this.options,l=typeof a=="function"?a():a;if(l==="all"||!l&&!R(this,Hl).size)return!0;const c=new Set(l??R(this,Hl));return this.options.throwOnError&&c.add("error"),Object.keys(R(this,$n)).some(i=>{const d=i;return R(this,$n)[d]!==n[d]&&c.has(d)})};(t==null?void 0:t.listeners)!==!1&&o()&&(s.listeners=!0),Je(this,gt,QE).call(this,{...s,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Je(this,gt,Mv).call(this)}},Qn=new WeakMap,at=new WeakMap,Nd=new WeakMap,$n=new WeakMap,si=new WeakMap,zl=new WeakMap,Ts=new WeakMap,Id=new WeakMap,Ul=new WeakMap,Vl=new WeakMap,oi=new WeakMap,ai=new WeakMap,Qo=new WeakMap,Hl=new WeakMap,gt=new WeakSet,oc=function(t){Je(this,gt,Iv).call(this);let n=R(this,at).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Or)),n},jv=function(){Je(this,gt,Ov).call(this);const t=bl(this.options.staleTime,R(this,at));if(Kl||R(this,$n).isStale||!Tv(t))return;const r=BE(R(this,$n).dataUpdatedAt,t)+1;xe(this,oi,setTimeout(()=>{R(this,$n).isStale||this.updateResult()},r))},Rv=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,at)):this.options.refetchInterval)??!1},Pv=function(t){Je(this,gt,Nv).call(this),xe(this,Qo,t),!(Kl||Qr(this.options.enabled,R(this,at))===!1||!Tv(R(this,Qo))||R(this,Qo)===0)&&xe(this,ai,setInterval(()=>{(this.options.refetchIntervalInBackground||Ib.isFocused())&&Je(this,gt,oc).call(this)},R(this,Qo)))},Mv=function(){Je(this,gt,jv).call(this),Je(this,gt,Pv).call(this,Je(this,gt,Rv).call(this))},Ov=function(){R(this,oi)&&(clearTimeout(R(this,oi)),xe(this,oi,void 0))},Nv=function(){R(this,ai)&&(clearInterval(R(this,ai)),xe(this,ai,void 0))},Iv=function(){const t=R(this,Qn).getQueryCache().build(R(this,Qn),this.options);if(t===R(this,at))return;const n=R(this,at);xe(this,at,t),xe(this,Nd,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},QE=function(t){cn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,$n))}),R(this,Qn).getQueryCache().notify({query:R(this,at),type:"observerResultsUpdated"})})},kE);function MD(e,t){return Qr(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nS(e,t){return MD(e,t)||e.state.data!==void 0&&Dv(e,t,t.refetchOnMount)}function Dv(e,t,n){if(Qr(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Db(e,t)}return!1}function rS(e,t,n,r){return(e!==t||Qr(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Db(e,n)}function Db(e,t){return Qr(t.enabled,e)!==!1&&e.isStaleByTime(bl(t.staleTime,e))}function OD(e,t){return!Tp(e.getCurrentResult(),t)}var Zo,Yo,Zn,to,co,Xf,Av,_E,ND=(_E=class extends lu{constructor(n,r){super();Ie(this,co);Ie(this,Zo);Ie(this,Yo);Ie(this,Zn);Ie(this,to);xe(this,Zo,n),this.setOptions(r),this.bindMethods(),Je(this,co,Xf).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var s;const r=this.options;this.options=R(this,Zo).defaultMutationOptions(n),Tp(this.options,r)||R(this,Zo).getMutationCache().notify({type:"observerOptionsUpdated",mutation:R(this,Zn),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&gi(r.mutationKey)!==gi(this.options.mutationKey)?this.reset():((s=R(this,Zn))==null?void 0:s.state.status)==="pending"&&R(this,Zn).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=R(this,Zn))==null||n.removeObserver(this)}onMutationUpdate(n){Je(this,co,Xf).call(this),Je(this,co,Av).call(this,n)}getCurrentResult(){return R(this,Yo)}reset(){var n;(n=R(this,Zn))==null||n.removeObserver(this),xe(this,Zn,void 0),Je(this,co,Xf).call(this),Je(this,co,Av).call(this)}mutate(n,r){var s;return xe(this,to,r),(s=R(this,Zn))==null||s.removeObserver(this),xe(this,Zn,R(this,Zo).getMutationCache().build(R(this,Zo),this.options)),R(this,Zn).addObserver(this),R(this,Zn).execute(n)}},Zo=new WeakMap,Yo=new WeakMap,Zn=new WeakMap,to=new WeakMap,co=new WeakSet,Xf=function(){var r;const n=((r=R(this,Zn))==null?void 0:r.state)??JE();xe(this,Yo,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Av=function(n){cn.batch(()=>{var r,s,o,a,l,c,i,d;if(R(this,to)&&this.hasListeners()){const p=R(this,Yo).variables,f=R(this,Yo).context;(n==null?void 0:n.type)==="success"?((s=(r=R(this,to)).onSuccess)==null||s.call(r,n.data,p,f),(a=(o=R(this,to)).onSettled)==null||a.call(o,n.data,null,p,f)):(n==null?void 0:n.type)==="error"&&((c=(l=R(this,to)).onError)==null||c.call(l,n.error,p,f),(d=(i=R(this,to)).onSettled)==null||d.call(i,void 0,n.error,p,f))}this.listeners.forEach(p=>{p(R(this,Yo))})})},_E),ZE=v.createContext(void 0),Ab=e=>{const t=v.useContext(ZE);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ID=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),u.jsx(ZE.Provider,{value:e,children:t})),YE=v.createContext(!1),DD=()=>v.useContext(YE);YE.Provider;function AD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var FD=v.createContext(AD()),LD=()=>v.useContext(FD);function XE(e,t){return typeof e=="function"?e(...t):!!e}function $D(){}var BD=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},zD=e=>{v.useEffect(()=>{e.clearReset()},[e])},UD=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&XE(n,[e.error,r]),VD=e=>{e.suspense&&(typeof e.staleTime!="number"&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},HD=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,KD=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function qD(e,t,n){var i,d,p,f;const r=Ab(),s=DD(),o=LD(),a=r.defaultQueryOptions(e);(d=(i=r.getDefaultOptions().queries)==null?void 0:i._experimental_beforeQuery)==null||d.call(i,a),a._optimisticResults=s?"isRestoring":"optimistic",VD(a),BD(a,o),zD(o);const[l]=v.useState(()=>new t(r,a)),c=l.getOptimisticResult(a);if(v.useSyncExternalStore(v.useCallback(h=>{const g=s?()=>{}:l.subscribe(cn.batchCalls(h));return l.updateResult(),g},[l,s]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(a,{listeners:!1})},[a,l]),HD(a,c))throw KD(a,l,o);if(UD({result:c,errorResetBoundary:o,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash)}))throw c.error;return(f=(p=r.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,a,c),a.notifyOnChangeProps?c:l.trackResult(c)}function lt(e,t){return qD(e,PD)}function WD(e,t){const n=Ab(),[r]=v.useState(()=>new ND(n,e));v.useEffect(()=>{r.setOptions(e)},[r,e]);const s=v.useSyncExternalStore(v.useCallback(a=>r.subscribe(cn.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=v.useCallback((a,l)=>{r.mutate(a,l).catch($D)},[r]);if(s.error&&XE(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}var Fv={},eT={exports:{}},Cr={},tT={exports:{}},nT={};/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */(function(e){function t(F,A){var Y=F.length;F.push(A);e:for(;0>>1,z=F[de];if(0>>1;des(ie,Y))oes(J,ie)?(F[de]=J,F[oe]=Y,de=oe):(F[de]=ie,F[ne]=Y,de=ne);else if(oes(J,Y))F[de]=J,F[oe]=Y,de=oe;else break e}}return A}function s(F,A){var Y=F.sortIndex-A.sortIndex;return Y!==0?Y:F.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,l=a.now();e.unstable_now=function(){return a.now()-l}}var c=[],i=[],d=1,p=null,f=3,h=!1,g=!1,m=!1,x=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(F){for(var A=n(i);A!==null;){if(A.callback===null)r(i);else if(A.startTime<=F)r(i),A.sortIndex=A.expirationTime,t(c,A);else break;A=n(i)}}function S(F){if(m=!1,w(F),!g)if(n(c)!==null)g=!0,ee(E);else{var A=n(i);A!==null&&W(S,A.startTime-F)}}function E(F,A){g=!1,m&&(m=!1,b(T),T=-1),h=!0;var Y=f;try{for(w(A),p=n(c);p!==null&&(!(p.expirationTime>A)||F&&!U());){var de=p.callback;if(typeof de=="function"){p.callback=null,f=p.priorityLevel;var z=de(p.expirationTime<=A);A=e.unstable_now(),typeof z=="function"?p.callback=z:p===n(c)&&r(c),w(A)}else r(c);p=n(c)}if(p!==null)var se=!0;else{var ne=n(i);ne!==null&&W(S,ne.startTime-A),se=!1}return se}finally{p=null,f=Y,h=!1}}var C=!1,k=null,T=-1,P=5,N=-1;function U(){return!(e.unstable_now()-NF||125de?(F.sortIndex=Y,t(i,F),n(c)===null&&F===n(i)&&(m?(b(T),T=-1):m=!0,W(S,Y-de))):(F.sortIndex=z,t(c,F),g||h||(g=!0,ee(E))),F},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(F){var A=f;return function(){var Y=f;f=A;try{return F.apply(this,arguments)}finally{f=Y}}}})(nT);tT.exports=nT;var GD=tT.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var JD=v,br=GD;function te(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Lv=Object.prototype.hasOwnProperty,QD=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,sS={},oS={};function ZD(e){return Lv.call(oS,e)?!0:Lv.call(sS,e)?!1:QD.test(e)?oS[e]=!0:(sS[e]=!0,!1)}function YD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function XD(e,t,n,r){if(t===null||typeof t>"u"||YD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Wn(e,t,n,r,s,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var Tn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Tn[e]=new Wn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Tn[t]=new Wn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Tn[e]=new Wn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Tn[e]=new Wn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Tn[e]=new Wn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Tn[e]=new Wn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Tn[e]=new Wn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Tn[e]=new Wn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Fb=/[\-:]([a-z])/g;function Lb(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Fb,Lb);Tn[t]=new Wn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!1,!1)});Tn.xlinkHref=new Wn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Tn[e]=new Wn(e,1,!1,e.toLowerCase(),null,!0,!0)});function $b(e,t,n,r){var s=Tn.hasOwnProperty(t)?Tn[t]:null;(s!==null?s.type!==0:r||!(2l||s[a]!==o[l]){var c=` -`+s[a].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=a&&0<=l);break}}}finally{lm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ac(e):""}function eA(e){switch(e.tag){case 5:return ac(e.type);case 16:return ac("Lazy");case 13:return ac("Suspense");case 19:return ac("SuspenseList");case 0:case 2:case 15:return e=um(e.type,!1),e;case 11:return e=um(e.type.render,!1),e;case 1:return e=um(e.type,!0),e;default:return""}}function Uv(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case sl:return"Fragment";case rl:return"Portal";case $v:return"Profiler";case Bb:return"StrictMode";case Bv:return"Suspense";case zv:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case oT:return(e.displayName||"Context")+".Consumer";case sT:return(e._context.displayName||"Context")+".Provider";case zb:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ub:return t=e.displayName||null,t!==null?t:Uv(e.type)||"Memo";case $o:t=e._payload,e=e._init;try{return Uv(e(t))}catch{}}return null}function tA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Uv(t);case 8:return t===Bb?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function da(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function iT(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nA(e){var t=iT(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function pf(e){e._valueTracker||(e._valueTracker=nA(e))}function lT(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=iT(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _p(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Vv(e,t){var n=t.checked;return Bt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function iS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=da(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function uT(e,t){t=t.checked,t!=null&&$b(e,"checked",t,!1)}function Hv(e,t){uT(e,t);var n=da(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Kv(e,t.type,n):t.hasOwnProperty("defaultValue")&&Kv(e,t.type,da(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function lS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Kv(e,t,n){(t!=="number"||_p(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ic=Array.isArray;function xl(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=hf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fc(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rA=["Webkit","ms","Moz","O"];Object.keys(yc).forEach(function(e){rA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yc[t]=yc[e]})});function pT(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yc.hasOwnProperty(e)&&yc[e]?(""+t).trim():t+"px"}function hT(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=pT(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var sA=Bt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Gv(e,t){if(t){if(sA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(te(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(te(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(te(61))}if(t.style!=null&&typeof t.style!="object")throw Error(te(62))}}function Jv(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Qv=null;function Vb(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Zv=null,wl=null,Sl=null;function dS(e){if(e=Ld(e)){if(typeof Zv!="function")throw Error(te(280));var t=e.stateNode;t&&(t=Lh(t),Zv(e.stateNode,e.type,t))}}function gT(e){wl?Sl?Sl.push(e):Sl=[e]:wl=e}function mT(){if(wl){var e=wl,t=Sl;if(Sl=wl=null,dS(e),t)for(e=0;e>>=0,e===0?32:31-(gA(e)/mA|0)|0}var gf=64,mf=4194304;function lc(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Mp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,a=n&268435455;if(a!==0){var l=a&~s;l!==0?r=lc(l):(o&=a,o!==0&&(r=lc(o)))}else a=n&~s,a!==0?r=lc(a):o!==0&&(r=lc(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ad(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ts(t),e[t]=n}function xA(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=xc),xS=" ",wS=!1;function AT(e,t){switch(e){case"keyup":return GA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function FT(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ol=!1;function QA(e,t){switch(e){case"compositionend":return FT(t);case"keypress":return t.which!==32?null:(wS=!0,xS);case"textInput":return e=t.data,e===xS&&wS?null:e;default:return null}}function ZA(e,t){if(ol)return e==="compositionend"||!Zb&&AT(e,t)?(e=IT(),tp=Gb=Xo=null,ol=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=TS(n)}}function zT(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?zT(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function UT(){for(var e=window,t=_p();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_p(e.document)}return t}function Yb(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function aF(e){var t=UT(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&zT(n.ownerDocument.documentElement,n)){if(r!==null&&Yb(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=kS(n,o);var a=kS(n,r);s&&a&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,al=null,ry=null,Sc=null,sy=!1;function _S(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;sy||al==null||al!==_p(r)||(r=al,"selectionStart"in r&&Yb(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Sc&&Vc(Sc,r)||(Sc=r,r=Ip(ry,"onSelect"),0ul||(e.current=cy[ul],cy[ul]=null,ul--)}function Et(e,t){ul++,cy[ul]=e.current,e.current=t}var fa={},In=Ea(fa),tr=Ea(!1),mi=fa;function Wl(e,t){var n=e.type.contextTypes;if(!n)return fa;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function nr(e){return e=e.childContextTypes,e!=null}function Ap(){Pt(tr),Pt(In)}function IS(e,t,n){if(In.current!==fa)throw Error(te(168));Et(In,t),Et(tr,n)}function ZT(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(te(108,tA(e)||"Unknown",s));return Bt({},n,r)}function Fp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||fa,mi=In.current,Et(In,e),Et(tr,tr.current),!0}function DS(e,t,n){var r=e.stateNode;if(!r)throw Error(te(169));n?(e=ZT(e,t,mi),r.__reactInternalMemoizedMergedChildContext=e,Pt(tr),Pt(In),Et(In,e)):Pt(tr),Et(tr,n)}var eo=null,$h=!1,Cm=!1;function YT(e){eo===null?eo=[e]:eo.push(e)}function yF(e){$h=!0,YT(e)}function Ta(){if(!Cm&&eo!==null){Cm=!0;var e=0,t=vt;try{var n=eo;for(vt=1;e>=a,s-=a,ro=1<<32-ts(t)+s|n<T?(P=k,k=null):P=k.sibling;var N=f(b,k,w[T],S);if(N===null){k===null&&(k=P);break}e&&k&&N.alternate===null&&t(b,k),y=o(N,y,T),C===null?E=N:C.sibling=N,C=N,k=P}if(T===w.length)return n(b,k),Ot&&$a(b,T),E;if(k===null){for(;TT?(P=k,k=null):P=k.sibling;var U=f(b,k,N.value,S);if(U===null){k===null&&(k=P);break}e&&k&&U.alternate===null&&t(b,k),y=o(U,y,T),C===null?E=U:C.sibling=U,C=U,k=P}if(N.done)return n(b,k),Ot&&$a(b,T),E;if(k===null){for(;!N.done;T++,N=w.next())N=p(b,N.value,S),N!==null&&(y=o(N,y,T),C===null?E=N:C.sibling=N,C=N);return Ot&&$a(b,T),E}for(k=r(b,k);!N.done;T++,N=w.next())N=h(k,b,T,N.value,S),N!==null&&(e&&N.alternate!==null&&k.delete(N.key===null?T:N.key),y=o(N,y,T),C===null?E=N:C.sibling=N,C=N);return e&&k.forEach(function(I){return t(b,I)}),Ot&&$a(b,T),E}function x(b,y,w,S){if(typeof w=="object"&&w!==null&&w.type===sl&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case ff:e:{for(var E=w.key,C=y;C!==null;){if(C.key===E){if(E=w.type,E===sl){if(C.tag===7){n(b,C.sibling),y=s(C,w.props.children),y.return=b,b=y;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===$o&&LS(E)===C.type){n(b,C.sibling),y=s(C,w.props),y.ref=Uu(b,C,w),y.return=b,b=y;break e}n(b,C);break}else t(b,C);C=C.sibling}w.type===sl?(y=li(w.props.children,b.mode,S,w.key),y.return=b,b=y):(S=up(w.type,w.key,w.props,null,b.mode,S),S.ref=Uu(b,y,w),S.return=b,b=S)}return a(b);case rl:e:{for(C=w.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(b,y.sibling),y=s(y,w.children||[]),y.return=b,b=y;break e}else{n(b,y);break}else t(b,y);y=y.sibling}y=Mm(w,b.mode,S),y.return=b,b=y}return a(b);case $o:return C=w._init,x(b,y,C(w._payload),S)}if(ic(w))return g(b,y,w,S);if(Fu(w))return m(b,y,w,S);Cf(b,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(b,y.sibling),y=s(y,w),y.return=b,b=y):(n(b,y),y=Pm(w,b.mode,S),y.return=b,b=y),a(b)):n(b,y)}return x}var Jl=nk(!0),rk=nk(!1),Bp=Ea(null),zp=null,fl=null,nx=null;function rx(){nx=fl=zp=null}function sx(e){var t=Bp.current;Pt(Bp),e._currentValue=t}function py(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function El(e,t){zp=e,nx=fl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(er=!0),e.firstContext=null)}function Br(e){var t=e._currentValue;if(nx!==e)if(e={context:e,memoizedValue:t,next:null},fl===null){if(zp===null)throw Error(te(308));fl=e,zp.dependencies={lanes:0,firstContext:e}}else fl=fl.next=e;return t}var Ha=null;function ox(e){Ha===null?Ha=[e]:Ha.push(e)}function sk(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ox(t)):(n.next=s.next,s.next=n),t.interleaved=n,ho(e,r)}function ho(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Bo=!1;function ax(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ok(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lo(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ia(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ct&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ho(e,n)}return s=r.interleaved,s===null?(t.next=t,ox(r)):(t.next=s.next,s.next=t),r.interleaved=t,ho(e,n)}function rp(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}function $S(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=a:o=o.next=a,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Up(e,t,n,r){var s=e.updateQueue;Bo=!1;var o=s.firstBaseUpdate,a=s.lastBaseUpdate,l=s.shared.pending;if(l!==null){s.shared.pending=null;var c=l,i=c.next;c.next=null,a===null?o=i:a.next=i,a=c;var d=e.alternate;d!==null&&(d=d.updateQueue,l=d.lastBaseUpdate,l!==a&&(l===null?d.firstBaseUpdate=i:l.next=i,d.lastBaseUpdate=c))}if(o!==null){var p=s.baseState;a=0,d=i=c=null,l=o;do{var f=l.lane,h=l.eventTime;if((r&f)===f){d!==null&&(d=d.next={eventTime:h,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var g=e,m=l;switch(f=t,h=n,m.tag){case 1:if(g=m.payload,typeof g=="function"){p=g.call(h,p,f);break e}p=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=m.payload,f=typeof g=="function"?g.call(h,p,f):g,f==null)break e;p=Bt({},p,f);break e;case 2:Bo=!0}}l.callback!==null&&l.lane!==0&&(e.flags|=64,f=s.effects,f===null?s.effects=[l]:f.push(l))}else h={eventTime:h,lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},d===null?(i=d=h,c=p):d=d.next=h,a|=f;if(l=l.next,l===null){if(l=s.shared.pending,l===null)break;f=l,l=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(c=p),s.baseState=c,s.firstBaseUpdate=i,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do a|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);bi|=a,e.lanes=a,e.memoizedState=p}}function BS(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Tm.transition;Tm.transition={};try{e(!1),t()}finally{vt=n,Tm.transition=r}}function Sk(){return zr().memoizedState}function SF(e,t,n){var r=ua(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ck(e))Ek(t,n);else if(n=sk(e,t,n,r),n!==null){var s=Hn();ns(n,e,r,s),Tk(n,t,r)}}function CF(e,t,n){var r=ua(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ck(e))Ek(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,l=o(a,n);if(s.hasEagerState=!0,s.eagerState=l,us(l,a)){var c=t.interleaved;c===null?(s.next=s,ox(t)):(s.next=c.next,c.next=s),t.interleaved=s;return}}catch{}finally{}n=sk(e,t,s,r),n!==null&&(s=Hn(),ns(n,e,r,s),Tk(n,t,r))}}function Ck(e){var t=e.alternate;return e===Lt||t!==null&&t===Lt}function Ek(e,t){Cc=Hp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Kb(e,n)}}var Kp={readContext:Br,useCallback:jn,useContext:jn,useEffect:jn,useImperativeHandle:jn,useInsertionEffect:jn,useLayoutEffect:jn,useMemo:jn,useReducer:jn,useRef:jn,useState:jn,useDebugValue:jn,useDeferredValue:jn,useTransition:jn,useMutableSource:jn,useSyncExternalStore:jn,useId:jn,unstable_isNewReconciler:!1},EF={readContext:Br,useCallback:function(e,t){return ws().memoizedState=[e,t===void 0?null:t],e},useContext:Br,useEffect:US,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,op(4194308,4,vk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return op(4194308,4,e,t)},useInsertionEffect:function(e,t){return op(4,2,e,t)},useMemo:function(e,t){var n=ws();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ws();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SF.bind(null,Lt,e),[r.memoizedState,e]},useRef:function(e){var t=ws();return e={current:e},t.memoizedState=e},useState:zS,useDebugValue:hx,useDeferredValue:function(e){return ws().memoizedState=e},useTransition:function(){var e=zS(!1),t=e[0];return e=wF.bind(null,e[1]),ws().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Lt,s=ws();if(Ot){if(n===void 0)throw Error(te(407));n=n()}else{if(n=t(),vn===null)throw Error(te(349));yi&30||uk(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,US(dk.bind(null,r,o,e),[e]),r.flags|=2048,Zc(9,ck.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=ws(),t=vn.identifierPrefix;if(Ot){var n=so,r=ro;n=(r&~(1<<32-ts(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Jc++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[ks]=t,e[qc]=r,Dk(e,t,!1,!1),t.stateNode=e;e:{switch(a=Jv(n,r),n){case"dialog":jt("cancel",e),jt("close",e),s=r;break;case"iframe":case"object":case"embed":jt("load",e),s=r;break;case"video":case"audio":for(s=0;sYl&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304)}else{if(!r)if(e=Vp(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Vu(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Ot)return Rn(t),null}else 2*Jt()-o.renderingStartTime>Yl&&n!==1073741824&&(t.flags|=128,r=!0,Vu(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(n=o.last,n!==null?n.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Jt(),t.sibling=null,n=Ft.current,Et(Ft,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return xx(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?cr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(te(156,t.tag))}function OF(e,t){switch(ex(t),t.tag){case 1:return nr(t.type)&&Ap(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ql(),Pt(tr),Pt(In),ux(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return lx(t),null;case 13:if(Pt(Ft),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(te(340));Gl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Pt(Ft),null;case 4:return Ql(),null;case 10:return sx(t.type._context),null;case 22:case 23:return xx(),null;case 24:return null;default:return null}}var Tf=!1,Nn=!1,NF=typeof WeakSet=="function"?WeakSet:Set,we=null;function pl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Kt(e,t,r)}else n.current=null}function Sy(e,t,n){try{n()}catch(r){Kt(e,t,r)}}var XS=!1;function IF(e,t){if(oy=Op,e=UT(),Yb(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var a=0,l=-1,c=-1,i=0,d=0,p=e,f=null;t:for(;;){for(var h;p!==n||s!==0&&p.nodeType!==3||(l=a+s),p!==o||r!==0&&p.nodeType!==3||(c=a+r),p.nodeType===3&&(a+=p.nodeValue.length),(h=p.firstChild)!==null;)f=p,p=h;for(;;){if(p===e)break t;if(f===n&&++i===s&&(l=a),f===o&&++d===r&&(c=a),(h=p.nextSibling)!==null)break;p=f,f=p.parentNode}p=h}n=l===-1||c===-1?null:{start:l,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(ay={focusedElem:e,selectionRange:n},Op=!1,we=t;we!==null;)if(t=we,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,we=e;else for(;we!==null;){t=we;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var m=g.memoizedProps,x=g.memoizedState,b=t.stateNode,y=b.getSnapshotBeforeUpdate(t.elementType===t.type?m:qr(t.type,m),x);b.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(S){Kt(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,we=e;break}we=t.return}return g=XS,XS=!1,g}function Ec(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&Sy(t,n,o)}s=s.next}while(s!==r)}}function Uh(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Cy(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Lk(e){var t=e.alternate;t!==null&&(e.alternate=null,Lk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ks],delete t[qc],delete t[uy],delete t[mF],delete t[vF])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function $k(e){return e.tag===5||e.tag===3||e.tag===4}function e0(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||$k(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ey(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Dp));else if(r!==4&&(e=e.child,e!==null))for(Ey(e,t,n),e=e.sibling;e!==null;)Ey(e,t,n),e=e.sibling}function Ty(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ty(e,t,n),e=e.sibling;e!==null;)Ty(e,t,n),e=e.sibling}var Sn=null,Gr=!1;function Mo(e,t,n){for(n=n.child;n!==null;)Bk(e,t,n),n=n.sibling}function Bk(e,t,n){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(Ih,n)}catch{}switch(n.tag){case 5:Nn||pl(n,t);case 6:var r=Sn,s=Gr;Sn=null,Mo(e,t,n),Sn=r,Gr=s,Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Sn.removeChild(n.stateNode));break;case 18:Sn!==null&&(Gr?(e=Sn,n=n.stateNode,e.nodeType===8?Sm(e.parentNode,n):e.nodeType===1&&Sm(e,n),zc(e)):Sm(Sn,n.stateNode));break;case 4:r=Sn,s=Gr,Sn=n.stateNode.containerInfo,Gr=!0,Mo(e,t,n),Sn=r,Gr=s;break;case 0:case 11:case 14:case 15:if(!Nn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Sy(n,t,a),s=s.next}while(s!==r)}Mo(e,t,n);break;case 1:if(!Nn&&(pl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Kt(n,t,l)}Mo(e,t,n);break;case 21:Mo(e,t,n);break;case 22:n.mode&1?(Nn=(r=Nn)||n.memoizedState!==null,Mo(e,t,n),Nn=r):Mo(e,t,n);break;default:Mo(e,t,n)}}function t0(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new NF),t.forEach(function(r){var s=VF.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Kr(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=a),r&=~o}if(r=s,r=Jt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*AF(r/1960))-r,10e?16:e,ea===null)var r=!1;else{if(e=ea,ea=null,Gp=0,ct&6)throw Error(te(331));var s=ct;for(ct|=4,we=e.current;we!==null;){var o=we,a=o.child;if(we.flags&16){var l=o.deletions;if(l!==null){for(var c=0;cJt()-yx?ii(e,0):vx|=n),rr(e,t)}function Gk(e,t){t===0&&(e.mode&1?(t=mf,mf<<=1,!(mf&130023424)&&(mf=4194304)):t=1);var n=Hn();e=ho(e,t),e!==null&&(Ad(e,t,n),rr(e,n))}function UF(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gk(e,n)}function VF(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(te(314))}r!==null&&r.delete(t),Gk(e,n)}var Jk;Jk=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||tr.current)er=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return er=!1,PF(e,t,n);er=!!(e.flags&131072)}else er=!1,Ot&&t.flags&1048576&&XT(t,$p,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ap(e,t),e=t.pendingProps;var s=Wl(t,In.current);El(t,n),s=dx(null,t,r,e,s,n);var o=fx();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,nr(r)?(o=!0,Fp(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ax(t),s.updater=zh,t.stateNode=s,s._reactInternals=t,gy(t,r,e,n),t=yy(null,t,r,!0,o,n)):(t.tag=0,Ot&&o&&Xb(t),zn(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ap(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=KF(r),e=qr(r,e),s){case 0:t=vy(null,t,r,e,n);break e;case 1:t=QS(null,t,r,e,n);break e;case 11:t=GS(null,t,r,e,n);break e;case 14:t=JS(null,t,r,qr(r.type,e),n);break e}throw Error(te(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),vy(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),QS(e,t,r,s,n);case 3:e:{if(Ok(t),e===null)throw Error(te(387));r=t.pendingProps,o=t.memoizedState,s=o.element,ok(e,t),Up(t,r,null,n);var a=t.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=Zl(Error(te(423)),t),t=ZS(e,t,r,n,s);break e}else if(r!==s){s=Zl(Error(te(424)),t),t=ZS(e,t,r,n,s);break e}else for(hr=aa(t.stateNode.containerInfo.firstChild),mr=t,Ot=!0,Zr=null,n=rk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Gl(),r===s){t=go(e,t,n);break e}zn(e,t,r,n)}t=t.child}return t;case 5:return ak(t),e===null&&fy(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,a=s.children,iy(r,s)?a=null:o!==null&&iy(r,o)&&(t.flags|=32),Mk(e,t),zn(e,t,a,n),t.child;case 6:return e===null&&fy(t),null;case 13:return Nk(e,t,n);case 4:return ix(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Jl(t,null,r,n):zn(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),GS(e,t,r,s,n);case 7:return zn(e,t,t.pendingProps,n),t.child;case 8:return zn(e,t,t.pendingProps.children,n),t.child;case 12:return zn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,a=s.value,Et(Bp,r._currentValue),r._currentValue=a,o!==null)if(us(o.value,a)){if(o.children===s.children&&!tr.current){t=go(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var l=o.dependencies;if(l!==null){a=o.child;for(var c=l.firstContext;c!==null;){if(c.context===r){if(o.tag===1){c=lo(-1,n&-n),c.tag=2;var i=o.updateQueue;if(i!==null){i=i.shared;var d=i.pending;d===null?c.next=c:(c.next=d.next,d.next=c),i.pending=c}}o.lanes|=n,c=o.alternate,c!==null&&(c.lanes|=n),py(o.return,n,t),l.lanes|=n;break}c=c.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(te(341));a.lanes|=n,l=a.alternate,l!==null&&(l.lanes|=n),py(a,n,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}zn(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,El(t,n),s=Br(s),r=r(s),t.flags|=1,zn(e,t,r,n),t.child;case 14:return r=t.type,s=qr(r,t.pendingProps),s=qr(r.type,s),JS(e,t,r,s,n);case 15:return Rk(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:qr(r,s),ap(e,t),t.tag=1,nr(r)?(e=!0,Fp(t)):e=!1,El(t,n),kk(t,r,s),gy(t,r,s,n),yy(null,t,r,!0,e,n);case 19:return Ik(e,t,n);case 22:return Pk(e,t,n)}throw Error(te(156,t.tag))};function Qk(e,t){return CT(e,t)}function HF(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ar(e,t,n,r){return new HF(e,t,n,r)}function Sx(e){return e=e.prototype,!(!e||!e.isReactComponent)}function KF(e){if(typeof e=="function")return Sx(e)?1:0;if(e!=null){if(e=e.$$typeof,e===zb)return 11;if(e===Ub)return 14}return 2}function ca(e,t){var n=e.alternate;return n===null?(n=Ar(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function up(e,t,n,r,s,o){var a=2;if(r=e,typeof e=="function")Sx(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case sl:return li(n.children,s,o,t);case Bb:a=8,s|=8;break;case $v:return e=Ar(12,n,t,s|2),e.elementType=$v,e.lanes=o,e;case Bv:return e=Ar(13,n,t,s),e.elementType=Bv,e.lanes=o,e;case zv:return e=Ar(19,n,t,s),e.elementType=zv,e.lanes=o,e;case aT:return Hh(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case sT:a=10;break e;case oT:a=9;break e;case zb:a=11;break e;case Ub:a=14;break e;case $o:a=16,r=null;break e}throw Error(te(130,e==null?e:typeof e,""))}return t=Ar(a,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function li(e,t,n,r){return e=Ar(7,e,r,t),e.lanes=n,e}function Hh(e,t,n,r){return e=Ar(22,e,r,t),e.elementType=aT,e.lanes=n,e.stateNode={isHidden:!1},e}function Pm(e,t,n){return e=Ar(6,e,null,t),e.lanes=n,e}function Mm(e,t,n){return t=Ar(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qF(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=dm(0),this.expirationTimes=dm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=dm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Cx(e,t,n,r,s,o,a,l,c){return e=new qF(e,t,n,l,c),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Ar(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ax(o),e}function WF(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e_)}catch(e){console.error(e)}}e_(),eT.exports=Cr;var ka=eT.exports;const t_=jb(ka),YF=jE({__proto__:null,default:t_},[ka]);var u0=ka;Fv.createRoot=u0.createRoot,Fv.hydrateRoot=u0.hydrateRoot;const XF=(...e)=>{console!=null&&console.warn&&(ui(e[0])&&(e[0]=`react-i18next:: ${e[0]}`),console.warn(...e))},c0={},Py=(...e)=>{ui(e[0])&&c0[e[0]]||(ui(e[0])&&(c0[e[0]]=new Date),XF(...e))},n_=(e,t)=>()=>{if(e.isInitialized)t();else{const n=()=>{setTimeout(()=>{e.off("initialized",n)},0),t()};e.on("initialized",n)}},d0=(e,t,n)=>{e.loadNamespaces(t,n_(e,n))},f0=(e,t,n,r)=>{ui(n)&&(n=[n]),n.forEach(s=>{e.options.ns.indexOf(s)<0&&e.options.ns.push(s)}),e.loadLanguages(t,n_(e,r))},e2=(e,t,n={})=>!t.languages||!t.languages.length?(Py("i18n.languages were undefined or empty",t.languages),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(r,s)=>{var o;if(((o=n.bindI18n)==null?void 0:o.indexOf("languageChanging"))>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,e))return!1}}),ui=e=>typeof e=="string",t2=e=>typeof e=="object"&&e!==null,n2=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,r2={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},s2=e=>r2[e],o2=e=>e.replace(n2,s2);let My={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:o2};const a2=(e={})=>{My={...My,...e}},i2=()=>My;let r_;const l2=e=>{r_=e},u2=()=>r_,c2={type:"3rdParty",init(e){a2(e.options.react),l2(e)}},s_=v.createContext();class d2{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(n=>{var r;(r=this.usedNamespaces)[n]??(r[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const f2=(e,t)=>{const n=v.useRef();return v.useEffect(()=>{n.current=e},[e,t]),n.current},o_=(e,t,n,r)=>e.getFixedT(t,n,r),p2=(e,t,n,r)=>v.useCallback(o_(e,t,n,r),[e,t,n,r]),ze=(e,t={})=>{var S,E,C,k;const{i18n:n}=t,{i18n:r,defaultNS:s}=v.useContext(s_)||{},o=n||r||u2();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new d2),!o){Py("You will need to pass in an i18next instance by using initReactI18next");const T=(N,U)=>ui(U)?U:t2(U)&&ui(U.defaultValue)?U.defaultValue:Array.isArray(N)?N[N.length-1]:N,P=[T,{},!1];return P.t=T,P.i18n={},P.ready=!1,P}(S=o.options.react)!=null&&S.wait&&Py("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const a={...i2(),...o.options.react,...t},{useSuspense:l,keyPrefix:c}=a;let i=s||((E=o.options)==null?void 0:E.defaultNS);i=ui(i)?[i]:i||["translation"],(k=(C=o.reportNamespaces).addUsedNamespaces)==null||k.call(C,i);const d=(o.isInitialized||o.initializedStoreOnce)&&i.every(T=>e2(T,o,a)),p=p2(o,t.lng||null,a.nsMode==="fallback"?i:i[0],c),f=()=>p,h=()=>o_(o,t.lng||null,a.nsMode==="fallback"?i:i[0],c),[g,m]=v.useState(f);let x=i.join();t.lng&&(x=`${t.lng}${x}`);const b=f2(x),y=v.useRef(!0);v.useEffect(()=>{const{bindI18n:T,bindI18nStore:P}=a;y.current=!0,!d&&!l&&(t.lng?f0(o,t.lng,i,()=>{y.current&&m(h)}):d0(o,i,()=>{y.current&&m(h)})),d&&b&&b!==x&&y.current&&m(h);const N=()=>{y.current&&m(h)};return T&&(o==null||o.on(T,N)),P&&(o==null||o.store.on(P,N)),()=>{y.current=!1,o&&(T==null||T.split(" ").forEach(U=>o.off(U,N))),P&&o&&P.split(" ").forEach(U=>o.store.off(U,N))}},[o,x]),v.useEffect(()=>{y.current&&d&&m(f)},[o,c,d]);const w=[g,o,d];if(w.t=g,w.i18n=o,w.ready=d,d||!d&&!l)return w;throw new Promise(T=>{t.lng?f0(o,t.lng,i,()=>T()):d0(o,i,()=>T())})};function h2({i18n:e,defaultNS:t,children:n}){const r=v.useMemo(()=>({i18n:e,defaultNS:t}),[e,t]);return v.createElement(s_.Provider,{value:r},n)}/** - * @remix-run/router v1.18.0 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function At(){return At=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Xl(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function m2(){return Math.random().toString(36).substr(2,8)}function h0(e,t){return{usr:e.state,key:e.key,idx:t}}function Xc(e,t,n,r){return n===void 0&&(n=null),At({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?_a(t):t,{state:n,key:t&&t.key||r||m2()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function _a(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function v2(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,a=s.history,l=en.Pop,c=null,i=d();i==null&&(i=0,a.replaceState(At({},a.state,{idx:i}),""));function d(){return(a.state||{idx:null}).idx}function p(){l=en.Pop;let x=d(),b=x==null?null:x-i;i=x,c&&c({action:l,location:m.location,delta:b})}function f(x,b){l=en.Push;let y=Xc(m.location,x,b);i=d()+1;let w=h0(y,i),S=m.createHref(y);try{a.pushState(w,"",S)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;s.location.assign(S)}o&&c&&c({action:l,location:m.location,delta:1})}function h(x,b){l=en.Replace;let y=Xc(m.location,x,b);i=d();let w=h0(y,i),S=m.createHref(y);a.replaceState(w,"",S),o&&c&&c({action:l,location:m.location,delta:0})}function g(x){let b=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof x=="string"?x:wi(x);return y=y.replace(/ $/,"%20"),Ze(b,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,b)}let m={get action(){return l},get location(){return e(s,a)},listen(x){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(p0,p),c=x,()=>{s.removeEventListener(p0,p),c=null}},createHref(x){return t(s,x)},createURL:g,encodeLocation(x){let b=g(x);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:f,replace:h,go(x){return a.go(x)}};return m}var Ct;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Ct||(Ct={}));const y2=new Set(["lazy","caseSensitive","path","id","index","children"]);function b2(e){return e.index===!0}function ed(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((s,o)=>{let a=[...n,String(o)],l=typeof s.id=="string"?s.id:a.join("-");if(Ze(s.index!==!0||!s.children,"Cannot specify children on an index route"),Ze(!r[l],'Found a route id collision on id "'+l+`". Route id's must be globally unique within Data Router usages`),b2(s)){let c=At({},s,t(s),{id:l});return r[l]=c,c}else{let c=At({},s,t(s),{id:l,children:void 0});return r[l]=c,s.children&&(c.children=ed(s.children,t,a,r)),c}})}function Ua(e,t,n){return n===void 0&&(n="/"),cp(e,t,n,!1)}function cp(e,t,n,r){let s=typeof t=="string"?_a(t):t,o=du(s.pathname||"/",n);if(o==null)return null;let a=a_(e);w2(a);let l=null;for(let c=0;l==null&&c{let c={relativePath:l===void 0?o.path||"":l,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};c.relativePath.startsWith("/")&&(Ze(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let i=uo([r,c.relativePath]),d=n.concat(c);o.children&&o.children.length>0&&(Ze(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+i+'".')),a_(o.children,t,d,i)),!(o.path==null&&!o.index)&&t.push({path:i,score:j2(i,o.index),routesMeta:d})};return e.forEach((o,a)=>{var l;if(o.path===""||!((l=o.path)!=null&&l.includes("?")))s(o,a);else for(let c of i_(o.path))s(o,a,c)}),t}function i_(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let a=i_(r.join("/")),l=[];return l.push(...a.map(c=>c===""?o:[o,c].join("/"))),s&&l.push(...a),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function w2(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:R2(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const S2=/^:[\w-]+$/,C2=3,E2=2,T2=1,k2=10,_2=-2,g0=e=>e==="*";function j2(e,t){let n=e.split("/"),r=n.length;return n.some(g0)&&(r+=_2),t&&(r+=E2),n.filter(s=>!g0(s)).reduce((s,o)=>s+(S2.test(o)?C2:o===""?T2:k2),r)}function R2(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function P2(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,s={},o="/",a=[];for(let l=0;l{let{paramName:f,isOptional:h}=d;if(f==="*"){let m=l[p]||"";a=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const g=l[p];return h&&!g?i[f]=void 0:i[f]=(g||"").replace(/%2F/g,"/"),i},{}),pathname:o,pathnameBase:a,pattern:e}}function M2(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Xl(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function O2(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Xl(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function du(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function N2(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?_a(e):e;return{pathname:n?n.startsWith("/")?n:I2(n,t):t,search:A2(r),hash:F2(s)}}function I2(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Om(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function l_(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Jh(e,t){let n=l_(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Qh(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=_a(e):(s=At({},e),Ze(!s.pathname||!s.pathname.includes("?"),Om("?","pathname","search",s)),Ze(!s.pathname||!s.pathname.includes("#"),Om("#","pathname","hash",s)),Ze(!s.search||!s.search.includes("#"),Om("#","search","hash",s)));let o=e===""||s.pathname==="",a=o?"/":s.pathname,l;if(a==null)l=n;else{let p=t.length-1;if(!r&&a.startsWith("..")){let f=a.split("/");for(;f[0]==="..";)f.shift(),p-=1;s.pathname=f.join("/")}l=p>=0?t[p]:"/"}let c=N2(s,l),i=a&&a!=="/"&&a.endsWith("/"),d=(o||a===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(i||d)&&(c.pathname+="/"),c}const uo=e=>e.join("/").replace(/\/\/+/g,"/"),D2=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),A2=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,F2=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class _x{constructor(t,n,r,s){s===void 0&&(s=!1),this.status=t,this.statusText=n||"",this.internal=s,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function Zh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const u_=["post","put","patch","delete"],L2=new Set(u_),$2=["get",...u_],B2=new Set($2),z2=new Set([301,302,303,307,308]),U2=new Set([307,308]),Nm={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},V2={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Ku={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},jx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,H2=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),c_="remix-router-transitions";function K2(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ze(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let s;if(e.mapRouteProperties)s=e.mapRouteProperties;else if(e.detectErrorBoundary){let M=e.detectErrorBoundary;s=O=>({hasErrorBoundary:M(O)})}else s=H2;let o={},a=ed(e.routes,s,void 0,o),l,c=e.basename||"/",i=e.unstable_dataStrategy||Q2,d=e.unstable_patchRoutesOnMiss,p=At({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),f=null,h=new Set,g=null,m=null,x=null,b=e.hydrationData!=null,y=Ua(a,e.history.location,c),w=null;if(y==null&&!d){let M=Bn(404,{pathname:e.history.location.pathname}),{matches:O,route:L}=k0(a);y=O,w={[L.id]:M}}y&&d&&!e.hydrationData&&rm(y,a,e.history.location.pathname).active&&(y=null);let S;if(!y)S=!1,y=[];else if(y.some(M=>M.route.lazy))S=!1;else if(!y.some(M=>M.route.loader))S=!0;else if(p.v7_partialHydration){let M=e.hydrationData?e.hydrationData.loaderData:null,O=e.hydrationData?e.hydrationData.errors:null,L=H=>H.route.loader?typeof H.route.loader=="function"&&H.route.loader.hydrate===!0?!1:M&&M[H.route.id]!==void 0||O&&O[H.route.id]!==void 0:!0;if(O){let H=y.findIndex(ye=>O[ye.route.id]!==void 0);S=y.slice(0,H+1).every(L)}else S=y.every(L)}else S=e.hydrationData!=null;let E,C={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,navigation:Nm,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||w,fetchers:new Map,blockers:new Map},k=en.Pop,T=!1,P,N=!1,U=new Map,I=null,Z=!1,V=!1,Q=[],ee=[],W=new Map,F=0,A=-1,Y=new Map,de=new Set,z=new Map,se=new Map,ne=new Set,ie=new Map,oe=new Map,J=new Map,Ce=!1;function Pe(){if(f=e.history.listen(M=>{let{action:O,location:L,delta:H}=M;if(Ce){Ce=!1;return}Xl(oe.size===0||H!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ye=Ro({currentLocation:C.location,nextLocation:L,historyAction:O});if(ye&&H!=null){Ce=!0,e.history.go(H*-1),ms(ye,{state:"blocked",location:L,proceed(){ms(ye,{state:"proceeding",proceed:void 0,reset:void 0,location:L}),e.history.go(H)},reset(){let _e=new Map(C.blockers);_e.set(ye,Ku),me({blockers:_e})}});return}return Wt(O,L)}),n){uL(t,U);let M=()=>cL(t,U);t.addEventListener("pagehide",M),I=()=>t.removeEventListener("pagehide",M)}return C.initialized||Wt(en.Pop,C.location,{initialHydration:!0}),E}function Le(){f&&f(),I&&I(),h.clear(),P&&P.abort(),C.fetchers.forEach((M,O)=>gs(O)),C.blockers.forEach((M,O)=>_n(O))}function Me(M){return h.add(M),()=>h.delete(M)}function me(M,O){O===void 0&&(O={}),C=At({},C,M);let L=[],H=[];p.v7_fetcherPersist&&C.fetchers.forEach((ye,_e)=>{ye.state==="idle"&&(ne.has(_e)?H.push(_e):L.push(_e))}),[...h].forEach(ye=>ye(C,{deletedFetchers:H,unstable_viewTransitionOpts:O.viewTransitionOpts,unstable_flushSync:O.flushSync===!0})),p.v7_fetcherPersist&&(L.forEach(ye=>C.fetchers.delete(ye)),H.forEach(ye=>gs(ye)))}function rt(M,O,L){var H,ye;let{flushSync:_e}=L===void 0?{}:L,$e=C.actionData!=null&&C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&C.navigation.state==="loading"&&((H=M.state)==null?void 0:H._isRedirect)!==!0,fe;O.actionData?Object.keys(O.actionData).length>0?fe=O.actionData:fe=null:$e?fe=C.actionData:fe=null;let qe=O.loaderData?E0(C.loaderData,O.loaderData,O.matches||[],O.errors):C.loaderData,Re=C.blockers;Re.size>0&&(Re=new Map(Re),Re.forEach((mt,bt)=>Re.set(bt,Ku)));let Oe=T===!0||C.navigation.formMethod!=null&&Jr(C.navigation.formMethod)&&((ye=M.state)==null?void 0:ye._isRedirect)!==!0;l&&(a=l,l=void 0),Z||k===en.Pop||(k===en.Push?e.history.push(M,M.state):k===en.Replace&&e.history.replace(M,M.state));let yt;if(k===en.Pop){let mt=U.get(C.location.pathname);mt&&mt.has(M.pathname)?yt={currentLocation:C.location,nextLocation:M}:U.has(M.pathname)&&(yt={currentLocation:M,nextLocation:C.location})}else if(N){let mt=U.get(C.location.pathname);mt?mt.add(M.pathname):(mt=new Set([M.pathname]),U.set(C.location.pathname,mt)),yt={currentLocation:C.location,nextLocation:M}}me(At({},O,{actionData:fe,loaderData:qe,historyAction:k,location:M,initialized:!0,navigation:Nm,revalidation:"idle",restoreScrollPosition:Kw(M,O.matches||C.matches),preventScrollReset:Oe,blockers:Re}),{viewTransitionOpts:yt,flushSync:_e===!0}),k=en.Pop,T=!1,N=!1,Z=!1,V=!1,Q=[],ee=[]}async function It(M,O){if(typeof M=="number"){e.history.go(M);return}let L=Oy(C.location,C.matches,c,p.v7_prependBasename,M,p.v7_relativeSplatPath,O==null?void 0:O.fromRouteId,O==null?void 0:O.relative),{path:H,submission:ye,error:_e}=v0(p.v7_normalizeFormMethod,!1,L,O),$e=C.location,fe=Xc(C.location,H,O&&O.state);fe=At({},fe,e.history.encodeLocation(fe));let qe=O&&O.replace!=null?O.replace:void 0,Re=en.Push;qe===!0?Re=en.Replace:qe===!1||ye!=null&&Jr(ye.formMethod)&&ye.formAction===C.location.pathname+C.location.search&&(Re=en.Replace);let Oe=O&&"preventScrollReset"in O?O.preventScrollReset===!0:void 0,yt=(O&&O.unstable_flushSync)===!0,mt=Ro({currentLocation:$e,nextLocation:fe,historyAction:Re});if(mt){ms(mt,{state:"blocked",location:fe,proceed(){ms(mt,{state:"proceeding",proceed:void 0,reset:void 0,location:fe}),It(M,O)},reset(){let bt=new Map(C.blockers);bt.set(mt,Ku),me({blockers:bt})}});return}return await Wt(Re,fe,{submission:ye,pendingError:_e,preventScrollReset:Oe,replace:O&&O.replace,enableViewTransition:O&&O.unstable_viewTransition,flushSync:yt})}function Zt(){if(hn(),me({revalidation:"loading"}),C.navigation.state!=="submitting"){if(C.navigation.state==="idle"){Wt(C.historyAction,C.location,{startUninterruptedRevalidation:!0});return}Wt(k||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation})}}async function Wt(M,O,L){P&&P.abort(),P=null,k=M,Z=(L&&L.startUninterruptedRevalidation)===!0,UI(C.location,C.matches),T=(L&&L.preventScrollReset)===!0,N=(L&&L.enableViewTransition)===!0;let H=l||a,ye=L&&L.overrideNavigation,_e=Ua(H,O,c),$e=(L&&L.flushSync)===!0,fe=rm(_e,H,O.pathname);if(fe.active&&fe.matches&&(_e=fe.matches),!_e){let{error:pt,notFoundMatches:bn,route:Yt}=Iu(O.pathname);rt(O,{matches:bn,loaderData:{},errors:{[Yt.id]:pt}},{flushSync:$e});return}if(C.initialized&&!V&&nL(C.location,O)&&!(L&&L.submission&&Jr(L.submission.formMethod))){rt(O,{matches:_e},{flushSync:$e});return}P=new AbortController;let qe=Hi(e.history,O,P.signal,L&&L.submission),Re;if(L&&L.pendingError)Re=[gl(_e).route.id,{type:Ct.error,error:L.pendingError}];else if(L&&L.submission&&Jr(L.submission.formMethod)){let pt=await an(qe,O,L.submission,_e,fe.active,{replace:L.replace,flushSync:$e});if(pt.shortCircuited)return;if(pt.pendingActionResult){let[bn,Yt]=pt.pendingActionResult;if(fr(Yt)&&Zh(Yt.error)&&Yt.error.status===404){P=null,rt(O,{matches:pt.matches,loaderData:{},errors:{[bn]:Yt.error}});return}}_e=pt.matches||_e,Re=pt.pendingActionResult,ye=Im(O,L.submission),$e=!1,fe.active=!1,qe=Hi(e.history,qe.url,qe.signal)}let{shortCircuited:Oe,matches:yt,loaderData:mt,errors:bt}=await j(qe,O,_e,fe.active,ye,L&&L.submission,L&&L.fetcherSubmission,L&&L.replace,L&&L.initialHydration===!0,$e,Re);Oe||(P=null,rt(O,At({matches:yt||_e},T0(Re),{loaderData:mt,errors:bt})))}async function an(M,O,L,H,ye,_e){_e===void 0&&(_e={}),hn();let $e=iL(O,L);if(me({navigation:$e},{flushSync:_e.flushSync===!0}),ye){let Re=await sf(H,O.pathname,M.signal);if(Re.type==="aborted")return{shortCircuited:!0};if(Re.type==="error"){let{boundaryId:Oe,error:yt}=$i(O.pathname,Re);return{matches:Re.partialMatches,pendingActionResult:[Oe,{type:Ct.error,error:yt}]}}else if(Re.matches)H=Re.matches;else{let{notFoundMatches:Oe,error:yt,route:mt}=Iu(O.pathname);return{matches:Oe,pendingActionResult:[mt.id,{type:Ct.error,error:yt}]}}}let fe,qe=cc(H,O);if(!qe.route.action&&!qe.route.lazy)fe={type:Ct.error,error:Bn(405,{method:M.method,pathname:O.pathname,routeId:qe.route.id})};else if(fe=(await et("action",M,[qe],H))[0],M.signal.aborted)return{shortCircuited:!0};if(Wa(fe)){let Re;return _e&&_e.replace!=null?Re=_e.replace:Re=w0(fe.response.headers.get("Location"),new URL(M.url),c)===C.location.pathname+C.location.search,await Ee(M,fe,{submission:L,replace:Re}),{shortCircuited:!0}}if(qa(fe))throw Bn(400,{type:"defer-action"});if(fr(fe)){let Re=gl(H,qe.route.id);return(_e&&_e.replace)!==!0&&(k=en.Push),{matches:H,pendingActionResult:[Re.route.id,fe]}}return{matches:H,pendingActionResult:[qe.route.id,fe]}}async function j(M,O,L,H,ye,_e,$e,fe,qe,Re,Oe){let yt=ye||Im(O,_e),mt=_e||$e||R0(yt),bt=!Z&&(!p.v7_partialHydration||!qe);if(H){if(bt){let Vt=D(Oe);me(At({navigation:yt},Vt!==void 0?{actionData:Vt}:{}),{flushSync:Re})}let Ge=await sf(L,O.pathname,M.signal);if(Ge.type==="aborted")return{shortCircuited:!0};if(Ge.type==="error"){let{boundaryId:Vt,error:ar}=$i(O.pathname,Ge);return{matches:Ge.partialMatches,loaderData:{},errors:{[Vt]:ar}}}else if(Ge.matches)L=Ge.matches;else{let{error:Vt,notFoundMatches:ar,route:Mt}=Iu(O.pathname);return{matches:ar,loaderData:{},errors:{[Mt.id]:Vt}}}}let pt=l||a,[bn,Yt]=y0(e.history,C,L,mt,O,p.v7_partialHydration&&qe===!0,p.v7_skipActionErrorRevalidation,V,Q,ee,ne,z,de,pt,c,Oe);if(vs(Ge=>!(L&&L.some(Vt=>Vt.route.id===Ge))||bn&&bn.some(Vt=>Vt.route.id===Ge)),A=++F,bn.length===0&&Yt.length===0){let Ge=Ue();return rt(O,At({matches:L,loaderData:{},errors:Oe&&fr(Oe[1])?{[Oe[0]]:Oe[1].error}:null},T0(Oe),Ge?{fetchers:new Map(C.fetchers)}:{}),{flushSync:Re}),{shortCircuited:!0}}if(bt){let Ge={};if(!H){Ge.navigation=yt;let Vt=D(Oe);Vt!==void 0&&(Ge.actionData=Vt)}Yt.length>0&&(Ge.fetchers=B(Yt)),me(Ge,{flushSync:Re})}Yt.forEach(Ge=>{W.has(Ge.key)&&Fn(Ge.key),Ge.controller&&W.set(Ge.key,Ge.controller)});let Au=()=>Yt.forEach(Ge=>Fn(Ge.key));P&&P.signal.addEventListener("abort",Au);let{loaderResults:Po,fetcherResults:Bi}=await kt(C.matches,L,bn,Yt,M);if(M.signal.aborted)return{shortCircuited:!0};P&&P.signal.removeEventListener("abort",Au),Yt.forEach(Ge=>W.delete(Ge.key));let zi=_0([...Po,...Bi]);if(zi){if(zi.idx>=bn.length){let Ge=Yt[zi.idx-bn.length].key;de.add(Ge)}return await Ee(M,zi.result,{replace:fe}),{shortCircuited:!0}}let{loaderData:Ui,errors:ys}=C0(C,L,bn,Po,Oe,Yt,Bi,ie);ie.forEach((Ge,Vt)=>{Ge.subscribe(ar=>{(ar||Ge.done)&&ie.delete(Vt)})}),p.v7_partialHydration&&qe&&C.errors&&Object.entries(C.errors).filter(Ge=>{let[Vt]=Ge;return!bn.some(ar=>ar.route.id===Vt)}).forEach(Ge=>{let[Vt,ar]=Ge;ys=Object.assign(ys||{},{[Vt]:ar})});let of=Ue(),af=St(A),lf=of||af||Yt.length>0;return At({matches:L,loaderData:Ui,errors:ys},lf?{fetchers:new Map(C.fetchers)}:{})}function D(M){if(M&&!fr(M[1]))return{[M[0]]:M[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function B(M){return M.forEach(O=>{let L=C.fetchers.get(O.key),H=qu(void 0,L?L.data:void 0);C.fetchers.set(O.key,H)}),new Map(C.fetchers)}function pe(M,O,L,H){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");W.has(M)&&Fn(M);let ye=(H&&H.unstable_flushSync)===!0,_e=l||a,$e=Oy(C.location,C.matches,c,p.v7_prependBasename,L,p.v7_relativeSplatPath,O,H==null?void 0:H.relative),fe=Ua(_e,$e,c),qe=rm(fe,_e,$e);if(qe.active&&qe.matches&&(fe=qe.matches),!fe){gn(M,O,Bn(404,{pathname:$e}),{flushSync:ye});return}let{path:Re,submission:Oe,error:yt}=v0(p.v7_normalizeFormMethod,!0,$e,H);if(yt){gn(M,O,yt,{flushSync:ye});return}let mt=cc(fe,Re);if(T=(H&&H.preventScrollReset)===!0,Oe&&Jr(Oe.formMethod)){le(M,O,Re,mt,fe,qe.active,ye,Oe);return}z.set(M,{routeId:O,path:Re}),ae(M,O,Re,mt,fe,qe.active,ye,Oe)}async function le(M,O,L,H,ye,_e,$e,fe){hn(),z.delete(M);function qe(Mt){if(!Mt.route.action&&!Mt.route.lazy){let Ks=Bn(405,{method:fe.formMethod,pathname:L,routeId:O});return gn(M,O,Ks,{flushSync:$e}),!0}return!1}if(!_e&&qe(H))return;let Re=C.fetchers.get(M);yn(M,lL(fe,Re),{flushSync:$e});let Oe=new AbortController,yt=Hi(e.history,L,Oe.signal,fe);if(_e){let Mt=await sf(ye,L,yt.signal);if(Mt.type==="aborted")return;if(Mt.type==="error"){let{error:Ks}=$i(L,Mt);gn(M,O,Ks,{flushSync:$e});return}else if(Mt.matches){if(ye=Mt.matches,H=cc(ye,L),qe(H))return}else{gn(M,O,Bn(404,{pathname:L}),{flushSync:$e});return}}W.set(M,Oe);let mt=F,pt=(await et("action",yt,[H],ye))[0];if(yt.signal.aborted){W.get(M)===Oe&&W.delete(M);return}if(p.v7_fetcherPersist&&ne.has(M)){if(Wa(pt)||fr(pt)){yn(M,Fo(void 0));return}}else{if(Wa(pt))if(W.delete(M),A>mt){yn(M,Fo(void 0));return}else return de.add(M),yn(M,qu(fe)),Ee(yt,pt,{fetcherSubmission:fe});if(fr(pt)){gn(M,O,pt.error);return}}if(qa(pt))throw Bn(400,{type:"defer-action"});let bn=C.navigation.location||C.location,Yt=Hi(e.history,bn,Oe.signal),Au=l||a,Po=C.navigation.state!=="idle"?Ua(Au,C.navigation.location,c):C.matches;Ze(Po,"Didn't find any matches after fetcher action");let Bi=++F;Y.set(M,Bi);let zi=qu(fe,pt.data);C.fetchers.set(M,zi);let[Ui,ys]=y0(e.history,C,Po,fe,bn,!1,p.v7_skipActionErrorRevalidation,V,Q,ee,ne,z,de,Au,c,[H.route.id,pt]);ys.filter(Mt=>Mt.key!==M).forEach(Mt=>{let Ks=Mt.key,qw=C.fetchers.get(Ks),KI=qu(void 0,qw?qw.data:void 0);C.fetchers.set(Ks,KI),W.has(Ks)&&Fn(Ks),Mt.controller&&W.set(Ks,Mt.controller)}),me({fetchers:new Map(C.fetchers)});let of=()=>ys.forEach(Mt=>Fn(Mt.key));Oe.signal.addEventListener("abort",of);let{loaderResults:af,fetcherResults:lf}=await kt(C.matches,Po,Ui,ys,Yt);if(Oe.signal.aborted)return;Oe.signal.removeEventListener("abort",of),Y.delete(M),W.delete(M),ys.forEach(Mt=>W.delete(Mt.key));let Ge=_0([...af,...lf]);if(Ge){if(Ge.idx>=Ui.length){let Mt=ys[Ge.idx-Ui.length].key;de.add(Mt)}return Ee(Yt,Ge.result)}let{loaderData:Vt,errors:ar}=C0(C,C.matches,Ui,af,void 0,ys,lf,ie);if(C.fetchers.has(M)){let Mt=Fo(pt.data);C.fetchers.set(M,Mt)}St(Bi),C.navigation.state==="loading"&&Bi>A?(Ze(k,"Expected pending action"),P&&P.abort(),rt(C.navigation.location,{matches:Po,loaderData:Vt,errors:ar,fetchers:new Map(C.fetchers)})):(me({errors:ar,loaderData:E0(C.loaderData,Vt,Po,ar),fetchers:new Map(C.fetchers)}),V=!1)}async function ae(M,O,L,H,ye,_e,$e,fe){let qe=C.fetchers.get(M);yn(M,qu(fe,qe?qe.data:void 0),{flushSync:$e});let Re=new AbortController,Oe=Hi(e.history,L,Re.signal);if(_e){let pt=await sf(ye,L,Oe.signal);if(pt.type==="aborted")return;if(pt.type==="error"){let{error:bn}=$i(L,pt);gn(M,O,bn,{flushSync:$e});return}else if(pt.matches)ye=pt.matches,H=cc(ye,L);else{gn(M,O,Bn(404,{pathname:L}),{flushSync:$e});return}}W.set(M,Re);let yt=F,bt=(await et("loader",Oe,[H],ye))[0];if(qa(bt)&&(bt=await g_(bt,Oe.signal,!0)||bt),W.get(M)===Re&&W.delete(M),!Oe.signal.aborted){if(ne.has(M)){yn(M,Fo(void 0));return}if(Wa(bt))if(A>yt){yn(M,Fo(void 0));return}else{de.add(M),await Ee(Oe,bt);return}if(fr(bt)){gn(M,O,bt.error);return}Ze(!qa(bt),"Unhandled fetcher deferred data"),yn(M,Fo(bt.data))}}async function Ee(M,O,L){let{submission:H,fetcherSubmission:ye,replace:_e}=L===void 0?{}:L;O.response.headers.has("X-Remix-Revalidate")&&(V=!0);let $e=O.response.headers.get("Location");Ze($e,"Expected a Location header on the redirect Response"),$e=w0($e,new URL(M.url),c);let fe=Xc(C.location,$e,{_isRedirect:!0});if(n){let bt=!1;if(O.response.headers.has("X-Remix-Reload-Document"))bt=!0;else if(jx.test($e)){const pt=e.history.createURL($e);bt=pt.origin!==t.location.origin||du(pt.pathname,c)==null}if(bt){_e?t.location.replace($e):t.location.assign($e);return}}P=null;let qe=_e===!0?en.Replace:en.Push,{formMethod:Re,formAction:Oe,formEncType:yt}=C.navigation;!H&&!ye&&Re&&Oe&&yt&&(H=R0(C.navigation));let mt=H||ye;if(U2.has(O.response.status)&&mt&&Jr(mt.formMethod))await Wt(qe,fe,{submission:At({},mt,{formAction:$e}),preventScrollReset:T});else{let bt=Im(fe,H);await Wt(qe,fe,{overrideNavigation:bt,fetcherSubmission:ye,preventScrollReset:T})}}async function et(M,O,L,H){try{let ye=await Z2(i,M,O,L,H,o,s);return await Promise.all(ye.map((_e,$e)=>{if(sL(_e)){let fe=_e.result;return{type:Ct.redirect,response:eL(fe,O,L[$e].route.id,H,c,p.v7_relativeSplatPath)}}return X2(_e)}))}catch(ye){return L.map(()=>({type:Ct.error,error:ye}))}}async function kt(M,O,L,H,ye){let[_e,...$e]=await Promise.all([L.length?et("loader",ye,L,O):[],...H.map(fe=>{if(fe.matches&&fe.match&&fe.controller){let qe=Hi(e.history,fe.path,fe.controller.signal);return et("loader",qe,[fe.match],fe.matches).then(Re=>Re[0])}else return Promise.resolve({type:Ct.error,error:Bn(404,{pathname:fe.path})})})]);return await Promise.all([j0(M,L,_e,_e.map(()=>ye.signal),!1,C.loaderData),j0(M,H.map(fe=>fe.match),$e,H.map(fe=>fe.controller?fe.controller.signal:null),!0)]),{loaderResults:_e,fetcherResults:$e}}function hn(){V=!0,Q.push(...vs()),z.forEach((M,O)=>{W.has(O)&&(ee.push(O),Fn(O))})}function yn(M,O,L){L===void 0&&(L={}),C.fetchers.set(M,O),me({fetchers:new Map(C.fetchers)},{flushSync:(L&&L.flushSync)===!0})}function gn(M,O,L,H){H===void 0&&(H={});let ye=gl(C.matches,O);gs(M),me({errors:{[ye.route.id]:L},fetchers:new Map(C.fetchers)},{flushSync:(H&&H.flushSync)===!0})}function jo(M){return p.v7_fetcherPersist&&(se.set(M,(se.get(M)||0)+1),ne.has(M)&&ne.delete(M)),C.fetchers.get(M)||V2}function gs(M){let O=C.fetchers.get(M);W.has(M)&&!(O&&O.state==="loading"&&Y.has(M))&&Fn(M),z.delete(M),Y.delete(M),de.delete(M),ne.delete(M),C.fetchers.delete(M)}function Aa(M){if(p.v7_fetcherPersist){let O=(se.get(M)||0)-1;O<=0?(se.delete(M),ne.add(M)):se.set(M,O)}else gs(M);me({fetchers:new Map(C.fetchers)})}function Fn(M){let O=W.get(M);Ze(O,"Expected fetch controller: "+M),O.abort(),W.delete(M)}function ue(M){for(let O of M){let L=jo(O),H=Fo(L.data);C.fetchers.set(O,H)}}function Ue(){let M=[],O=!1;for(let L of de){let H=C.fetchers.get(L);Ze(H,"Expected fetcher: "+L),H.state==="loading"&&(de.delete(L),M.push(L),O=!0)}return ue(M),O}function St(M){let O=[];for(let[L,H]of Y)if(H0}function dt(M,O){let L=C.blockers.get(M)||Ku;return oe.get(M)!==O&&oe.set(M,O),L}function _n(M){C.blockers.delete(M),oe.delete(M)}function ms(M,O){let L=C.blockers.get(M)||Ku;Ze(L.state==="unblocked"&&O.state==="blocked"||L.state==="blocked"&&O.state==="blocked"||L.state==="blocked"&&O.state==="proceeding"||L.state==="blocked"&&O.state==="unblocked"||L.state==="proceeding"&&O.state==="unblocked","Invalid blocker state transition: "+L.state+" -> "+O.state);let H=new Map(C.blockers);H.set(M,O),me({blockers:H})}function Ro(M){let{currentLocation:O,nextLocation:L,historyAction:H}=M;if(oe.size===0)return;oe.size>1&&Xl(!1,"A router only supports one blocker at a time");let ye=Array.from(oe.entries()),[_e,$e]=ye[ye.length-1],fe=C.blockers.get(_e);if(!(fe&&fe.state==="proceeding")&&$e({currentLocation:O,nextLocation:L,historyAction:H}))return _e}function Iu(M){let O=Bn(404,{pathname:M}),L=l||a,{matches:H,route:ye}=k0(L);return vs(),{notFoundMatches:H,route:ye,error:O}}function $i(M,O){return{boundaryId:gl(O.partialMatches).route.id,error:Bn(400,{type:"route-discovery",pathname:M,message:O.error!=null&&"message"in O.error?O.error:String(O.error)})}}function vs(M){let O=[];return ie.forEach((L,H)=>{(!M||M(H))&&(L.cancel(),O.push(H),ie.delete(H))}),O}function Du(M,O,L){if(g=M,x=O,m=L||null,!b&&C.navigation===Nm){b=!0;let H=Kw(C.location,C.matches);H!=null&&me({restoreScrollPosition:H})}return()=>{g=null,x=null,m=null}}function Hw(M,O){return m&&m(M,O.map(H=>x2(H,C.loaderData)))||M.key}function UI(M,O){if(g&&x){let L=Hw(M,O);g[L]=x()}}function Kw(M,O){if(g){let L=Hw(M,O),H=g[L];if(typeof H=="number")return H}return null}function rm(M,O,L){if(d)if(M){let H=M[M.length-1].route;if(H.path&&(H.path==="*"||H.path.endsWith("/*")))return{active:!0,matches:cp(O,L,c,!0)}}else return{active:!0,matches:cp(O,L,c,!0)||[]};return{active:!1,matches:null}}async function sf(M,O,L){let H=M,ye=H.length>0?H[H.length-1].route:null;for(;;){let _e=l==null,$e=l||a;try{await J2(d,O,H,$e,o,s,J,L)}catch(Oe){return{type:"error",error:Oe,partialMatches:H}}finally{_e&&(a=[...a])}if(L.aborted)return{type:"aborted"};let fe=Ua($e,O,c),qe=!1;if(fe){let Oe=fe[fe.length-1].route;if(Oe.index)return{type:"success",matches:fe};if(Oe.path&&Oe.path.length>0)if(Oe.path==="*")qe=!0;else return{type:"success",matches:fe}}let Re=cp($e,O,c,!0);if(!Re||H.map(Oe=>Oe.route.id).join("-")===Re.map(Oe=>Oe.route.id).join("-"))return{type:"success",matches:qe?fe:null};if(H=Re,ye=H[H.length-1].route,ye.path==="*")return{type:"success",matches:H}}}function VI(M){o={},l=ed(M,s,void 0,o)}function HI(M,O){let L=l==null;f_(M,O,l||a,o,s),L&&(a=[...a],me({}))}return E={get basename(){return c},get future(){return p},get state(){return C},get routes(){return a},get window(){return t},initialize:Pe,subscribe:Me,enableScrollRestoration:Du,navigate:It,fetch:pe,revalidate:Zt,createHref:M=>e.history.createHref(M),encodeLocation:M=>e.history.encodeLocation(M),getFetcher:jo,deleteFetcher:Aa,dispose:Le,getBlocker:dt,deleteBlocker:_n,patchRoutes:HI,_internalFetchControllers:W,_internalActiveDeferreds:ie,_internalSetRoutes:VI},E}function q2(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Oy(e,t,n,r,s,o,a,l){let c,i;if(a){c=[];for(let p of t)if(c.push(p),p.route.id===a){i=p;break}}else c=t,i=t[t.length-1];let d=Qh(s||".",Jh(c,o),du(e.pathname,n)||e.pathname,l==="path");return s==null&&(d.search=e.search,d.hash=e.hash),(s==null||s===""||s===".")&&i&&i.route.index&&!Rx(d.search)&&(d.search=d.search?d.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(d.pathname=d.pathname==="/"?n:uo([n,d.pathname])),wi(d)}function v0(e,t,n,r){if(!r||!q2(r))return{path:n};if(r.formMethod&&!aL(r.formMethod))return{path:n,error:Bn(405,{method:r.formMethod})};let s=()=>({path:n,error:Bn(400,{type:"invalid-body"})}),o=r.formMethod||"get",a=e?o.toUpperCase():o.toLowerCase(),l=p_(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!Jr(a))return s();let f=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((h,g)=>{let[m,x]=g;return""+h+m+"="+x+` -`},""):String(r.body);return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:void 0,text:f}}}else if(r.formEncType==="application/json"){if(!Jr(a))return s();try{let f=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:a,formAction:l,formEncType:r.formEncType,formData:void 0,json:f,text:void 0}}}catch{return s()}}}Ze(typeof FormData=="function","FormData is not available in this environment");let c,i;if(r.formData)c=Ny(r.formData),i=r.formData;else if(r.body instanceof FormData)c=Ny(r.body),i=r.body;else if(r.body instanceof URLSearchParams)c=r.body,i=S0(c);else if(r.body==null)c=new URLSearchParams,i=new FormData;else try{c=new URLSearchParams(r.body),i=S0(c)}catch{return s()}let d={formMethod:a,formAction:l,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(Jr(d.formMethod))return{path:n,submission:d};let p=_a(n);return t&&p.search&&Rx(p.search)&&c.append("index",""),p.search="?"+c,{path:wi(p),submission:d}}function W2(e,t){let n=e;if(t){let r=e.findIndex(s=>s.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function y0(e,t,n,r,s,o,a,l,c,i,d,p,f,h,g,m){let x=m?fr(m[1])?m[1].error:m[1].data:void 0,b=e.createURL(t.location),y=e.createURL(s),w=m&&fr(m[1])?m[0]:void 0,S=w?W2(n,w):n,E=m?m[1].statusCode:void 0,C=a&&E&&E>=400,k=S.filter((P,N)=>{let{route:U}=P;if(U.lazy)return!0;if(U.loader==null)return!1;if(o)return typeof U.loader!="function"||U.loader.hydrate?!0:t.loaderData[U.id]===void 0&&(!t.errors||t.errors[U.id]===void 0);if(G2(t.loaderData,t.matches[N],P)||c.some(V=>V===P.route.id))return!0;let I=t.matches[N],Z=P;return b0(P,At({currentUrl:b,currentParams:I.params,nextUrl:y,nextParams:Z.params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:l||b.pathname+b.search===y.pathname+y.search||b.search!==y.search||d_(I,Z)}))}),T=[];return p.forEach((P,N)=>{if(o||!n.some(Q=>Q.route.id===P.routeId)||d.has(N))return;let U=Ua(h,P.path,g);if(!U){T.push({key:N,routeId:P.routeId,path:P.path,matches:null,match:null,controller:null});return}let I=t.fetchers.get(N),Z=cc(U,P.path),V=!1;f.has(N)?V=!1:i.includes(N)?V=!0:I&&I.state!=="idle"&&I.data===void 0?V=l:V=b0(Z,At({currentUrl:b,currentParams:t.matches[t.matches.length-1].params,nextUrl:y,nextParams:n[n.length-1].params},r,{actionResult:x,actionStatus:E,defaultShouldRevalidate:C?!1:l})),V&&T.push({key:N,routeId:P.routeId,path:P.path,matches:U,match:Z,controller:new AbortController})}),[k,T]}function G2(e,t,n){let r=!t||n.route.id!==t.route.id,s=e[n.route.id]===void 0;return r||s}function d_(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function b0(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function J2(e,t,n,r,s,o,a,l){let c=[t,...n.map(i=>i.route.id)].join("-");try{let i=a.get(c);i||(i=e({path:t,matches:n,patch:(d,p)=>{l.aborted||f_(d,p,r,s,o)}}),a.set(c,i)),i&&rL(i)&&await i}finally{a.delete(c)}}function f_(e,t,n,r,s){if(e){var o;let a=r[e];Ze(a,"No route found to patch children into: routeId = "+e);let l=ed(t,s,[e,"patch",String(((o=a.children)==null?void 0:o.length)||"0")],r);a.children?a.children.push(...l):a.children=l}else{let a=ed(t,s,["patch",String(n.length||"0")],r);n.push(...a)}}async function x0(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let s=n[e.id];Ze(s,"No route found in manifest");let o={};for(let a in r){let c=s[a]!==void 0&&a!=="hasErrorBoundary";Xl(!c,'Route "'+s.id+'" has a static property "'+a+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+a+'" will be ignored.')),!c&&!y2.has(a)&&(o[a]=r[a])}Object.assign(s,o),Object.assign(s,At({},t(s),{lazy:void 0}))}function Q2(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function Z2(e,t,n,r,s,o,a,l){let c=r.reduce((p,f)=>p.add(f.route.id),new Set),i=new Set,d=await e({matches:s.map(p=>{let f=c.has(p.route.id);return At({},p,{shouldLoad:f,resolve:g=>(i.add(p.route.id),f?Y2(t,n,p,o,a,g,l):Promise.resolve({type:Ct.data,result:void 0}))})}),request:n,params:s[0].params,context:l});return s.forEach(p=>Ze(i.has(p.route.id),'`match.resolve()` was not called for route id "'+p.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),d.filter((p,f)=>c.has(s[f].route.id))}async function Y2(e,t,n,r,s,o,a){let l,c,i=d=>{let p,f=new Promise((m,x)=>p=x);c=()=>p(),t.signal.addEventListener("abort",c);let h=m=>typeof d!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):d({request:t,params:n.params,context:a},...m!==void 0?[m]:[]),g;return o?g=o(m=>h(m)):g=(async()=>{try{return{type:"data",result:await h()}}catch(m){return{type:"error",result:m}}})(),Promise.race([g,f])};try{let d=n.route[e];if(n.route.lazy)if(d){let p,[f]=await Promise.all([i(d).catch(h=>{p=h}),x0(n.route,s,r)]);if(p!==void 0)throw p;l=f}else if(await x0(n.route,s,r),d=n.route[e],d)l=await i(d);else if(e==="action"){let p=new URL(t.url),f=p.pathname+p.search;throw Bn(405,{method:t.method,pathname:f,routeId:n.route.id})}else return{type:Ct.data,result:void 0};else if(d)l=await i(d);else{let p=new URL(t.url),f=p.pathname+p.search;throw Bn(404,{pathname:f})}Ze(l.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(d){return{type:Ct.error,result:d}}finally{c&&t.signal.removeEventListener("abort",c)}return l}async function X2(e){let{result:t,type:n,status:r}=e;if(h_(t)){let a;try{let l=t.headers.get("Content-Type");l&&/\bapplication\/json\b/.test(l)?t.body==null?a=null:a=await t.json():a=await t.text()}catch(l){return{type:Ct.error,error:l}}return n===Ct.error?{type:Ct.error,error:new _x(t.status,t.statusText,a),statusCode:t.status,headers:t.headers}:{type:Ct.data,data:a,statusCode:t.status,headers:t.headers}}if(n===Ct.error)return{type:Ct.error,error:t,statusCode:Zh(t)?t.status:r};if(oL(t)){var s,o;return{type:Ct.deferred,deferredData:t,statusCode:(s=t.init)==null?void 0:s.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}return{type:Ct.data,data:t,statusCode:r}}function eL(e,t,n,r,s,o){let a=e.headers.get("Location");if(Ze(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!jx.test(a)){let l=r.slice(0,r.findIndex(c=>c.route.id===n)+1);a=Oy(new URL(t.url),l,s,!0,a,o),e.headers.set("Location",a)}return e}function w0(e,t,n){if(jx.test(e)){let r=e,s=r.startsWith("//")?new URL(t.protocol+r):new URL(r),o=du(s.pathname,n)!=null;if(s.origin===t.origin&&o)return s.pathname+s.search+s.hash}return e}function Hi(e,t,n,r){let s=e.createURL(p_(t)).toString(),o={signal:n};if(r&&Jr(r.formMethod)){let{formMethod:a,formEncType:l}=r;o.method=a.toUpperCase(),l==="application/json"?(o.headers=new Headers({"Content-Type":l}),o.body=JSON.stringify(r.json)):l==="text/plain"?o.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?o.body=Ny(r.formData):o.body=r.formData}return new Request(s,o)}function Ny(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function S0(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function tL(e,t,n,r,s,o){let a={},l=null,c,i=!1,d={},p=r&&fr(r[1])?r[1].error:void 0;return n.forEach((f,h)=>{let g=t[h].route.id;if(Ze(!Wa(f),"Cannot handle redirect results in processLoaderData"),fr(f)){let m=f.error;p!==void 0&&(m=p,p=void 0),l=l||{};{let x=gl(e,g);l[x.route.id]==null&&(l[x.route.id]=m)}a[g]=void 0,i||(i=!0,c=Zh(f.error)?f.error.status:500),f.headers&&(d[g]=f.headers)}else qa(f)?(s.set(g,f.deferredData),a[g]=f.deferredData.data,f.statusCode!=null&&f.statusCode!==200&&!i&&(c=f.statusCode),f.headers&&(d[g]=f.headers)):(a[g]=f.data,f.statusCode&&f.statusCode!==200&&!i&&(c=f.statusCode),f.headers&&(d[g]=f.headers))}),p!==void 0&&r&&(l={[r[0]]:p},a[r[0]]=void 0),{loaderData:a,errors:l,statusCode:c||200,loaderHeaders:d}}function C0(e,t,n,r,s,o,a,l){let{loaderData:c,errors:i}=tL(t,n,r,s,l);for(let d=0;dr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function k0(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Bn(e,t){let{pathname:n,routeId:r,method:s,type:o,message:a}=t===void 0?{}:t,l="Unknown Server Error",c="Unknown @remix-run/router error";return e===400?(l="Bad Request",o==="route-discovery"?c='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: -`+a):s&&n&&r?c="You made a "+s+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":o==="defer-action"?c="defer() is not supported in actions":o==="invalid-body"&&(c="Unable to encode submission body")):e===403?(l="Forbidden",c='Route "'+r+'" does not match URL "'+n+'"'):e===404?(l="Not Found",c='No route matches URL "'+n+'"'):e===405&&(l="Method Not Allowed",s&&n&&r?c="You made a "+s.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":s&&(c='Invalid request method "'+s.toUpperCase()+'"')),new _x(e||500,l,new Error(c),!0)}function _0(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(Wa(n))return{result:n,idx:t}}}function p_(e){let t=typeof e=="string"?_a(e):e;return wi(At({},t,{hash:""}))}function nL(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function rL(e){return typeof e=="object"&&e!=null&&"then"in e}function sL(e){return h_(e.result)&&z2.has(e.result.status)}function qa(e){return e.type===Ct.deferred}function fr(e){return e.type===Ct.error}function Wa(e){return(e&&e.type)===Ct.redirect}function oL(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function h_(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function aL(e){return B2.has(e.toLowerCase())}function Jr(e){return L2.has(e.toLowerCase())}async function j0(e,t,n,r,s,o){for(let a=0;ap.route.id===c.route.id),d=i!=null&&!d_(i,c)&&(o&&o[c.route.id])!==void 0;if(qa(l)&&(s||d)){let p=r[a];Ze(p,"Expected an AbortSignal for revalidating fetcher deferred result"),await g_(l,p,s).then(f=>{f&&(n[a]=f||n[a])})}}}async function g_(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:Ct.data,data:e.deferredData.unwrappedData}}catch(s){return{type:Ct.error,error:s}}return{type:Ct.data,data:e.deferredData.data}}}function Rx(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function cc(e,t){let n=typeof t=="string"?_a(t).search:t.search;if(e[e.length-1].route.index&&Rx(n||""))return e[e.length-1];let r=l_(e);return r[r.length-1]}function R0(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:o,json:a}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(a!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:a,text:void 0}}}function Im(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function iL(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function qu(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function lL(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Fo(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function uL(e,t){try{let n=e.sessionStorage.getItem(c_);if(n){let r=JSON.parse(n);for(let[s,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(s,new Set(o||[]))}}catch{}}function cL(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem(c_,JSON.stringify(n))}catch(r){Xl(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** - * React Router v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Zp(){return Zp=Object.assign?Object.assign.bind():function(e){for(var t=1;t{l.current=!0}),v.useCallback(function(i,d){if(d===void 0&&(d={}),!l.current)return;if(typeof i=="number"){r.go(i);return}let p=Qh(i,JSON.parse(a),o,d.relative==="path");e==null&&t!=="/"&&(p.pathname=p.pathname==="/"?t:uo([t,p.pathname])),(d.replace?r.replace:r.push)(p,d.state,d)},[t,r,a,o,e])}function So(){let{matches:e}=v.useContext(wo),t=e[e.length-1];return t?t.params:{}}function b_(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(ja),{matches:s}=v.useContext(wo),{pathname:o}=pu(),a=JSON.stringify(Jh(s,r.v7_relativeSplatPath));return v.useMemo(()=>Qh(e,JSON.parse(a),o,n==="path"),[e,a,o,n])}function pL(e,t,n,r){fu()||Ze(!1);let{navigator:s}=v.useContext(ja),{matches:o}=v.useContext(wo),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let c=a?a.pathnameBase:"/";a&&a.route;let i=pu(),d;d=i;let p=d.pathname||"/",f=p;if(c!=="/"){let m=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(m.length).join("/")}let h=Ua(e,{pathname:f});return yL(h&&h.map(m=>Object.assign({},m,{params:Object.assign({},l,m.params),pathname:uo([c,s.encodeLocation?s.encodeLocation(m.pathname).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?c:uo([c,s.encodeLocation?s.encodeLocation(m.pathnameBase).pathname:m.pathnameBase])})),o,n,r)}function hL(){let e=SL(),t=Zh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const gL=v.createElement(hL,null);class mL extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(wo.Provider,{value:this.props.routeContext},v.createElement(v_.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function vL(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(Yh);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(wo.Provider,{value:t},r)}function yL(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if((o=n)!=null&&o.errors)e=n.matches;else return null}let a=e,l=(s=n)==null?void 0:s.errors;if(l!=null){let d=a.findIndex(p=>p.route.id&&(l==null?void 0:l[p.route.id])!==void 0);d>=0||Ze(!1),a=a.slice(0,Math.min(a.length,d+1))}let c=!1,i=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?a=a.slice(0,i+1):a=[a[0]];break}}}return a.reduceRight((d,p,f)=>{let h,g=!1,m=null,x=null;n&&(h=l&&p.route.id?l[p.route.id]:void 0,m=p.route.errorElement||gL,c&&(i<0&&f===0?(EL("route-fallback"),g=!0,x=null):i===f&&(g=!0,x=p.route.hydrateFallbackElement||null)));let b=t.concat(a.slice(0,f+1)),y=()=>{let w;return h?w=m:g?w=x:p.route.Component?w=v.createElement(p.route.Component,null):p.route.element?w=p.route.element:w=d,v.createElement(vL,{match:p,routeContext:{outlet:d,matches:b,isDataRoute:n!=null},children:w})};return n&&(p.route.ErrorBoundary||p.route.errorElement||f===0)?v.createElement(mL,{location:n.location,revalidation:n.revalidation,component:m,error:h,children:y(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):y()},null)}var x_=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(x_||{}),Yp=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(Yp||{});function bL(e){let t=v.useContext(Yh);return t||Ze(!1),t}function xL(e){let t=v.useContext(m_);return t||Ze(!1),t}function wL(e){let t=v.useContext(wo);return t||Ze(!1),t}function w_(e){let t=wL(),n=t.matches[t.matches.length-1];return n.route.id||Ze(!1),n.route.id}function SL(){var e;let t=v.useContext(v_),n=xL(Yp.UseRouteError),r=w_(Yp.UseRouteError);return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function CL(){let{router:e}=bL(x_.UseNavigateStable),t=w_(Yp.UseNavigateStable),n=v.useRef(!1);return y_(()=>{n.current=!0}),v.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Zp({fromRouteId:t},o)))},[e,t])}const P0={};function EL(e,t,n){P0[e]||(P0[e]=!0)}function S_(e){let{to:t,replace:n,state:r,relative:s}=e;fu()||Ze(!1);let{future:o,static:a}=v.useContext(ja),{matches:l}=v.useContext(wo),{pathname:c}=pu(),i=An(),d=Qh(t,Jh(l,o.v7_relativeSplatPath),c,s==="path"),p=JSON.stringify(d);return v.useEffect(()=>i(JSON.parse(p),{replace:n,state:r,relative:s}),[i,p,s,n,r]),null}function TL(e){let{basename:t="/",children:n=null,location:r,navigationType:s=en.Pop,navigator:o,static:a=!1,future:l}=e;fu()&&Ze(!1);let c=t.replace(/^\/*/,"/"),i=v.useMemo(()=>({basename:c,navigator:o,static:a,future:Zp({v7_relativeSplatPath:!1},l)}),[c,l,o,a]);typeof r=="string"&&(r=_a(r));let{pathname:d="/",search:p="",hash:f="",state:h=null,key:g="default"}=r,m=v.useMemo(()=>{let x=du(d,c);return x==null?null:{location:{pathname:x,search:p,hash:f,state:h,key:g},navigationType:s}},[c,d,p,f,h,g,s]);return m==null?null:v.createElement(ja.Provider,{value:i},v.createElement(Px.Provider,{children:n,value:m}))}new Promise(()=>{});function kL(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:v.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:v.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:v.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** - * React Router DOM v6.25.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function td(){return td=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function jL(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function RL(e,t){return e.button===0&&(!t||t==="_self")&&!jL(e)}const PL=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],ML="6";try{window.__reactRouterVersion=ML}catch{}function OL(e,t){return K2({basename:void 0,future:td({},void 0,{v7_prependBasename:!0}),history:g2({window:void 0}),hydrationData:NL(),routes:e,mapRouteProperties:kL,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function NL(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=td({},t,{errors:IL(t.errors)})),t}function IL(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new _x(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(s.__subType){let o=window[s.__subType];if(typeof o=="function")try{let a=new o(s.message);a.stack="",n[r]=a}catch{}}if(n[r]==null){let o=new Error(s.message);o.stack="",n[r]=o}}else n[r]=s;return n}const DL=v.createContext({isTransitioning:!1}),AL=v.createContext(new Map),FL="startTransition",M0=Nh[FL],LL="flushSync",O0=YF[LL];function $L(e){M0?M0(e):e()}function Wu(e){O0?O0(e):e()}class BL{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function zL(e){let{fallbackElement:t,router:n,future:r}=e,[s,o]=v.useState(n.state),[a,l]=v.useState(),[c,i]=v.useState({isTransitioning:!1}),[d,p]=v.useState(),[f,h]=v.useState(),[g,m]=v.useState(),x=v.useRef(new Map),{v7_startTransition:b}=r||{},y=v.useCallback(T=>{b?$L(T):T()},[b]),w=v.useCallback((T,P)=>{let{deletedFetchers:N,unstable_flushSync:U,unstable_viewTransitionOpts:I}=P;N.forEach(V=>x.current.delete(V)),T.fetchers.forEach((V,Q)=>{V.data!==void 0&&x.current.set(Q,V.data)});let Z=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!I||Z){U?Wu(()=>o(T)):y(()=>o(T));return}if(U){Wu(()=>{f&&(d&&d.resolve(),f.skipTransition()),i({isTransitioning:!0,flushSync:!0,currentLocation:I.currentLocation,nextLocation:I.nextLocation})});let V=n.window.document.startViewTransition(()=>{Wu(()=>o(T))});V.finished.finally(()=>{Wu(()=>{p(void 0),h(void 0),l(void 0),i({isTransitioning:!1})})}),Wu(()=>h(V));return}f?(d&&d.resolve(),f.skipTransition(),m({state:T,currentLocation:I.currentLocation,nextLocation:I.nextLocation})):(l(T),i({isTransitioning:!0,flushSync:!1,currentLocation:I.currentLocation,nextLocation:I.nextLocation}))},[n.window,f,d,x,y]);v.useLayoutEffect(()=>n.subscribe(w),[n,w]),v.useEffect(()=>{c.isTransitioning&&!c.flushSync&&p(new BL)},[c]),v.useEffect(()=>{if(d&&a&&n.window){let T=a,P=d.promise,N=n.window.document.startViewTransition(async()=>{y(()=>o(T)),await P});N.finished.finally(()=>{p(void 0),h(void 0),l(void 0),i({isTransitioning:!1})}),h(N)}},[y,a,d,n.window]),v.useEffect(()=>{d&&a&&s.location.key===a.location.key&&d.resolve()},[d,f,s.location,a]),v.useEffect(()=>{!c.isTransitioning&&g&&(l(g.state),i({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),m(void 0))},[c.isTransitioning,g]),v.useEffect(()=>{},[]);let S=v.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:T=>n.navigate(T),push:(T,P,N)=>n.navigate(T,{state:P,preventScrollReset:N==null?void 0:N.preventScrollReset}),replace:(T,P,N)=>n.navigate(T,{replace:!0,state:P,preventScrollReset:N==null?void 0:N.preventScrollReset})}),[n]),E=n.basename||"/",C=v.useMemo(()=>({router:n,navigator:S,static:!1,basename:E}),[n,S,E]),k=v.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return v.createElement(v.Fragment,null,v.createElement(Yh.Provider,{value:C},v.createElement(m_.Provider,{value:s},v.createElement(AL.Provider,{value:x.current},v.createElement(DL.Provider,{value:c},v.createElement(TL,{basename:E,location:s.location,navigationType:s.historyAction,navigator:S,future:k},s.initialized||n.future.v7_partialHydration?v.createElement(UL,{routes:n.routes,future:n.future,state:s}):t))))),null)}const UL=v.memo(VL);function VL(e){let{routes:t,future:n,state:r}=e;return pL(t,void 0,r,n)}const HL=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",KL=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nd=v.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:o,replace:a,state:l,target:c,to:i,preventScrollReset:d,unstable_viewTransition:p}=t,f=_L(t,PL),{basename:h}=v.useContext(ja),g,m=!1;if(typeof i=="string"&&KL.test(i)&&(g=i,HL))try{let w=new URL(window.location.href),S=i.startsWith("//")?new URL(w.protocol+i):new URL(i),E=du(S.pathname,h);S.origin===w.origin&&E!=null?i=E+S.search+S.hash:m=!0}catch{}let x=dL(i,{relative:s}),b=qL(i,{replace:a,state:l,target:c,preventScrollReset:d,relative:s,unstable_viewTransition:p});function y(w){r&&r(w),w.defaultPrevented||b(w)}return v.createElement("a",td({},f,{href:g||x,onClick:m||o?r:y,ref:n,target:c}))});var N0;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(N0||(N0={}));var I0;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(I0||(I0={}));function qL(e,t){let{target:n,replace:r,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:l}=t===void 0?{}:t,c=An(),i=pu(),d=b_(e,{relative:a});return v.useCallback(p=>{if(RL(p,n)){p.preventDefault();let f=r!==void 0?r:wi(i)===wi(d);c(e,{replace:f,state:s,preventScrollReset:o,relative:a,unstable_viewTransition:l})}},[i,c,d,r,s,n,e,o,a,l])}function C_(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;ttypeof e=="number"&&!isNaN(e),ci=e=>typeof e=="string",gr=e=>typeof e=="function",dp=e=>ci(e)||gr(e)?e:null,Iy=e=>v.isValidElement(e)||ci(e)||gr(e)||rd(e);function WL(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=r+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function Xh(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:s=!0,collapseDuration:o=300}=e;return function(a){let{children:l,position:c,preventExitTransition:i,done:d,nodeRef:p,isIn:f,playToast:h}=a;const g=r?`${t}--${c}`:t,m=r?`${n}--${c}`:n,x=v.useRef(0);return v.useLayoutEffect(()=>{const b=p.current,y=g.split(" "),w=S=>{S.target===p.current&&(h(),b.removeEventListener("animationend",w),b.removeEventListener("animationcancel",w),x.current===0&&S.type!=="animationcancel"&&b.classList.remove(...y))};b.classList.add(...y),b.addEventListener("animationend",w),b.addEventListener("animationcancel",w)},[]),v.useEffect(()=>{const b=p.current,y=()=>{b.removeEventListener("animationend",y),s?WL(b,d,o):d()};f||(i?y():(x.current=1,b.className+=` ${m}`,b.addEventListener("animationend",y)))},[f]),Te.createElement(Te.Fragment,null,l)}}function D0(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const Vn=new Map;let sd=[];const Dy=new Set,GL=e=>Dy.forEach(t=>t(e)),E_=()=>Vn.size>0;function T_(e,t){var n;if(t)return!((n=Vn.get(t))==null||!n.isToastActive(e));let r=!1;return Vn.forEach(s=>{s.isToastActive(e)&&(r=!0)}),r}function k_(e,t){Iy(e)&&(E_()||sd.push({content:e,options:t}),Vn.forEach(n=>{n.buildToast(e,t)}))}function A0(e,t){Vn.forEach(n=>{t!=null&&t!=null&&t.containerId?(t==null?void 0:t.containerId)===n.id&&n.toggle(e,t==null?void 0:t.id):n.toggle(e,t==null?void 0:t.id)})}function JL(e){const{subscribe:t,getSnapshot:n,setProps:r}=v.useRef(function(o){const a=o.containerId||1;return{subscribe(l){const c=function(d,p,f){let h=1,g=0,m=[],x=[],b=[],y=p;const w=new Map,S=new Set,E=()=>{b=Array.from(w.values()),S.forEach(T=>T())},C=T=>{x=T==null?[]:x.filter(P=>P!==T),E()},k=T=>{const{toastId:P,onOpen:N,updateId:U,children:I}=T.props,Z=U==null;T.staleId&&w.delete(T.staleId),w.set(P,T),x=[...x,T.props.toastId].filter(V=>V!==T.staleId),E(),f(D0(T,Z?"added":"updated")),Z&&gr(N)&&N(v.isValidElement(I)&&I.props)};return{id:d,props:y,observe:T=>(S.add(T),()=>S.delete(T)),toggle:(T,P)=>{w.forEach(N=>{P!=null&&P!==N.props.toastId||gr(N.toggle)&&N.toggle(T)})},removeToast:C,toasts:w,clearQueue:()=>{g-=m.length,m=[]},buildToast:(T,P)=>{if((z=>{let{containerId:se,toastId:ne,updateId:ie}=z;const oe=se?se!==d:d!==1,J=w.has(ne)&&ie==null;return oe||J})(P))return;const{toastId:N,updateId:U,data:I,staleId:Z,delay:V}=P,Q=()=>{C(N)},ee=U==null;ee&&g++;const W={...y,style:y.toastStyle,key:h++,...Object.fromEntries(Object.entries(P).filter(z=>{let[se,ne]=z;return ne!=null})),toastId:N,updateId:U,data:I,closeToast:Q,isIn:!1,className:dp(P.className||y.toastClassName),bodyClassName:dp(P.bodyClassName||y.bodyClassName),progressClassName:dp(P.progressClassName||y.progressClassName),autoClose:!P.isLoading&&(F=P.autoClose,A=y.autoClose,F===!1||rd(F)&&F>0?F:A),deleteToast(){const z=w.get(N),{onClose:se,children:ne}=z.props;gr(se)&&se(v.isValidElement(ne)&&ne.props),f(D0(z,"removed")),w.delete(N),g--,g<0&&(g=0),m.length>0?k(m.shift()):E()}};var F,A;W.closeButton=y.closeButton,P.closeButton===!1||Iy(P.closeButton)?W.closeButton=P.closeButton:P.closeButton===!0&&(W.closeButton=!Iy(y.closeButton)||y.closeButton);let Y=T;v.isValidElement(T)&&!ci(T.type)?Y=v.cloneElement(T,{closeToast:Q,toastProps:W,data:I}):gr(T)&&(Y=T({closeToast:Q,toastProps:W,data:I}));const de={content:Y,props:W,staleId:Z};y.limit&&y.limit>0&&g>y.limit&&ee?m.push(de):rd(V)?setTimeout(()=>{k(de)},V):k(de)},setProps(T){y=T},setToggle:(T,P)=>{w.get(T).toggle=P},isToastActive:T=>x.some(P=>P===T),getSnapshot:()=>y.newestOnTop?b.reverse():b}}(a,o,GL);Vn.set(a,c);const i=c.observe(l);return sd.forEach(d=>k_(d.content,d.options)),sd=[],()=>{i(),Vn.delete(a)}},setProps(l){var c;(c=Vn.get(a))==null||c.setProps(l)},getSnapshot(){var l;return(l=Vn.get(a))==null?void 0:l.getSnapshot()}}}(e)).current;r(e);const s=v.useSyncExternalStore(t,n,n);return{getToastToRender:function(o){if(!s)return[];const a=new Map;return s.forEach(l=>{const{position:c}=l.props;a.has(c)||a.set(c,[]),a.get(c).push(l)}),Array.from(a,l=>o(l[0],l[1]))},isToastActive:T_,count:s==null?void 0:s.length}}function QL(e){const[t,n]=v.useState(!1),[r,s]=v.useState(!1),o=v.useRef(null),a=v.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:l,pauseOnHover:c,closeToast:i,onClick:d,closeOnClick:p}=e;var f,h;function g(){n(!0)}function m(){n(!1)}function x(w){const S=o.current;a.canDrag&&S&&(a.didMove=!0,t&&m(),a.delta=e.draggableDirection==="x"?w.clientX-a.start:w.clientY-a.start,a.start!==w.clientX&&(a.canCloseOnClick=!1),S.style.transform=`translate3d(${e.draggableDirection==="x"?`${a.delta}px, var(--y)`:`0, calc(${a.delta}px + var(--y))`},0)`,S.style.opacity=""+(1-Math.abs(a.delta/a.removalDistance)))}function b(){document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",b);const w=o.current;if(a.canDrag&&a.didMove&&w){if(a.canDrag=!1,Math.abs(a.delta)>a.removalDistance)return s(!0),e.closeToast(),void e.collapseAll();w.style.transition="transform 0.2s, opacity 0.2s",w.style.removeProperty("transform"),w.style.removeProperty("opacity")}}(h=Vn.get((f={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||h.setToggle(f.id,f.fn),v.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||m(),window.addEventListener("focus",g),window.addEventListener("blur",m),()=>{window.removeEventListener("focus",g),window.removeEventListener("blur",m)}},[e.pauseOnFocusLoss]);const y={onPointerDown:function(w){if(e.draggable===!0||e.draggable===w.pointerType){a.didMove=!1,document.addEventListener("pointermove",x),document.addEventListener("pointerup",b);const S=o.current;a.canCloseOnClick=!0,a.canDrag=!0,S.style.transition="none",e.draggableDirection==="x"?(a.start=w.clientX,a.removalDistance=S.offsetWidth*(e.draggablePercent/100)):(a.start=w.clientY,a.removalDistance=S.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(w){const{top:S,bottom:E,left:C,right:k}=o.current.getBoundingClientRect();w.nativeEvent.type!=="touchend"&&e.pauseOnHover&&w.clientX>=C&&w.clientX<=k&&w.clientY>=S&&w.clientY<=E?m():g()}};return l&&c&&(y.onMouseEnter=m,e.stacked||(y.onMouseLeave=g)),p&&(y.onClick=w=>{d&&d(w),a.canCloseOnClick&&i()}),{playToast:g,pauseToast:m,isRunning:t,preventExitTransition:r,toastRef:o,eventHandlers:y}}function ZL(e){let{delay:t,isRunning:n,closeToast:r,type:s="default",hide:o,className:a,style:l,controlledProgress:c,progress:i,rtl:d,isIn:p,theme:f}=e;const h=o||c&&i===0,g={...l,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};c&&(g.transform=`scaleX(${i})`);const m=oo("Toastify__progress-bar",c?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${f}`,`Toastify__progress-bar--${s}`,{"Toastify__progress-bar--rtl":d}),x=gr(a)?a({rtl:d,type:s,defaultClassName:m}):oo(m,a),b={[c&&i>=1?"onTransitionEnd":"onAnimationEnd"]:c&&i<1?null:()=>{p&&r()}};return Te.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":h},Te.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${f} Toastify__progress-bar--${s}`}),Te.createElement("div",{role:"progressbar","aria-hidden":h?"true":"false","aria-label":"notification timer",className:x,style:g,...b}))}let YL=1;const __=()=>""+YL++;function XL(e){return e&&(ci(e.toastId)||rd(e.toastId))?e.toastId:__()}function _c(e,t){return k_(e,t),t.toastId}function Xp(e,t){return{...t,type:t&&t.type||e,toastId:XL(t)}}function jf(e){return(t,n)=>_c(t,Xp(e,n))}function X(e,t){return _c(e,Xp("default",t))}X.loading=(e,t)=>_c(e,Xp("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),X.promise=function(e,t,n){let r,{pending:s,error:o,success:a}=t;s&&(r=ci(s)?X.loading(s,n):X.loading(s.render,{...n,...s}));const l={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},c=(d,p,f)=>{if(p==null)return void X.dismiss(r);const h={type:d,...l,...n,data:f},g=ci(p)?{render:p}:p;return r?X.update(r,{...h,...g}):X(g.render,{...h,...g}),f},i=gr(e)?e():e;return i.then(d=>c("success",a,d)).catch(d=>c("error",o,d)),i},X.success=jf("success"),X.info=jf("info"),X.error=jf("error"),X.warning=jf("warning"),X.warn=X.warning,X.dark=(e,t)=>_c(e,Xp("default",{theme:"dark",...t})),X.dismiss=function(e){(function(t){var n;if(E_()){if(t==null||ci(n=t)||rd(n))Vn.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=Vn.get(t.containerId);r?r.removeToast(t.id):Vn.forEach(s=>{s.removeToast(t.id)})}}else sd=sd.filter(r=>t!=null&&r.options.toastId!==t)})(e)},X.clearWaitingQueue=function(e){e===void 0&&(e={}),Vn.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},X.isActive=T_,X.update=function(e,t){t===void 0&&(t={});const n=((r,s)=>{var o;let{containerId:a}=s;return(o=Vn.get(a||1))==null?void 0:o.toasts.get(r)})(e,t);if(n){const{props:r,content:s}=n,o={delay:100,...r,...t,toastId:t.toastId||e,updateId:__()};o.toastId!==e&&(o.staleId=e);const a=o.render||s;delete o.render,_c(a,o)}},X.done=e=>{X.update(e,{progress:1})},X.onChange=function(e){return Dy.add(e),()=>{Dy.delete(e)}},X.play=e=>A0(!0,e),X.pause=e=>A0(!1,e);const e$=typeof window<"u"?v.useLayoutEffect:v.useEffect,Rf=e=>{let{theme:t,type:n,isLoading:r,...s}=e;return Te.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...s})},Dm={info:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return Te.createElement(Rf,{...e},Te.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return Te.createElement("div",{className:"Toastify__spinner"})}},t$=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:s,playToast:o}=QL(e),{closeButton:a,children:l,autoClose:c,onClick:i,type:d,hideProgressBar:p,closeToast:f,transition:h,position:g,className:m,style:x,bodyClassName:b,bodyStyle:y,progressClassName:w,progressStyle:S,updateId:E,role:C,progress:k,rtl:T,toastId:P,deleteToast:N,isIn:U,isLoading:I,closeOnClick:Z,theme:V}=e,Q=oo("Toastify__toast",`Toastify__toast-theme--${V}`,`Toastify__toast--${d}`,{"Toastify__toast--rtl":T},{"Toastify__toast--close-on-click":Z}),ee=gr(m)?m({rtl:T,position:g,type:d,defaultClassName:Q}):oo(Q,m),W=function(de){let{theme:z,type:se,isLoading:ne,icon:ie}=de,oe=null;const J={theme:z,type:se};return ie===!1||(gr(ie)?oe=ie({...J,isLoading:ne}):v.isValidElement(ie)?oe=v.cloneElement(ie,J):ne?oe=Dm.spinner():(Ce=>Ce in Dm)(se)&&(oe=Dm[se](J))),oe}(e),F=!!k||!c,A={closeToast:f,type:d,theme:V};let Y=null;return a===!1||(Y=gr(a)?a(A):v.isValidElement(a)?v.cloneElement(a,A):function(de){let{closeToast:z,theme:se,ariaLabel:ne="close"}=de;return Te.createElement("button",{className:`Toastify__close-button Toastify__close-button--${se}`,type:"button",onClick:ie=>{ie.stopPropagation(),z(ie)},"aria-label":ne},Te.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},Te.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(A)),Te.createElement(h,{isIn:U,done:N,position:g,preventExitTransition:n,nodeRef:r,playToast:o},Te.createElement("div",{id:P,onClick:i,"data-in":U,className:ee,...s,style:x,ref:r},Te.createElement("div",{...U&&{role:C},className:gr(b)?b({type:d}):oo("Toastify__toast-body",b),style:y},W!=null&&Te.createElement("div",{className:oo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!I})},W),Te.createElement("div",null,l)),Y,Te.createElement(ZL,{...E&&!F?{key:`pb-${E}`}:{},rtl:T,theme:V,delay:c,isRunning:t,isIn:U,closeToast:f,hide:p,type:d,style:S,className:w,controlledProgress:F,progress:k||0})))},eg=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},n$=Xh(eg("bounce",!0));Xh(eg("slide",!0));Xh(eg("zoom"));Xh(eg("flip"));const r$={position:"top-right",transition:n$,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function s$(e){let t={...r$,...e};const n=e.stacked,[r,s]=v.useState(!0),o=v.useRef(null),{getToastToRender:a,isToastActive:l,count:c}=JL(t),{className:i,style:d,rtl:p,containerId:f}=t;function h(m){const x=oo("Toastify__toast-container",`Toastify__toast-container--${m}`,{"Toastify__toast-container--rtl":p});return gr(i)?i({position:m,rtl:p,defaultClassName:x}):oo(x,dp(i))}function g(){n&&(s(!0),X.play())}return e$(()=>{if(n){var m;const x=o.current.querySelectorAll('[data-in="true"]'),b=12,y=(m=t.position)==null?void 0:m.includes("top");let w=0,S=0;Array.from(x).reverse().forEach((E,C)=>{const k=E;k.classList.add("Toastify__toast--stacked"),C>0&&(k.dataset.collapsed=`${r}`),k.dataset.pos||(k.dataset.pos=y?"top":"bot");const T=w*(r?.2:1)+(r?0:b*C);k.style.setProperty("--y",`${y?T:-1*T}px`),k.style.setProperty("--g",`${b}`),k.style.setProperty("--s",""+(1-(r?S:0))),w+=k.offsetHeight,S+=.025})}},[r,c,n]),Te.createElement("div",{ref:o,className:"Toastify",id:f,onMouseEnter:()=>{n&&(s(!1),X.pause())},onMouseLeave:g},a((m,x)=>{const b=x.length?{...d}:{...d,pointerEvents:"none"};return Te.createElement("div",{className:h(m),style:b,key:`container-${m}`},x.map(y=>{let{content:w,props:S}=y;return Te.createElement(t$,{...S,stacked:n,collapseAll:g,isIn:l(S.toastId,S.containerId),style:S.style,key:`toast-${S.key}`},w)}))}))}const o$={theme:"system",setTheme:()=>null},j_=v.createContext(o$);function a$({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[s,o]=v.useState(()=>localStorage.getItem(n)||t);v.useEffect(()=>{const l=window.document.documentElement;if(l.classList.remove("light","dark"),s==="system"){const c=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";l.classList.add(c);return}l.classList.add(s)},[s]);const a={theme:s,setTheme:l=>{localStorage.setItem(n,l),o(l)}};return u.jsx(j_.Provider,{...r,value:a,children:e})}const R_=()=>{const e=v.useContext(j_);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};let Am=!1;const i$=new RD({defaultOptions:{queries:{staleTime:1e3*60*5,retry(e){return e>=3?(Am===!1&&(Am=!0,X.error("The application is taking longer than expected to load, please try again in a few minutes.",{onClose:()=>{Am=!1}})),!1):!0}}}});var rs=(e=>(e.API_URL="apiUrl",e.TOKEN="token",e.VERSION="version",e.FACEBOOK_APP_ID="facebookAppId",e.FACEBOOK_CONFIG_ID="facebookConfigId",e.FACEBOOK_USER_TOKEN="facebookUserToken",e.CLIENT_NAME="clientName",e))(rs||{});const P_=async e=>{if(e.url){const t=e.url.endsWith("/")?e.url.slice(0,-1):e.url;localStorage.setItem("apiUrl",t)}e.token&&localStorage.setItem("token",e.token),e.version&&localStorage.setItem("version",e.version),e.facebookAppId&&localStorage.setItem("facebookAppId",e.facebookAppId),e.facebookConfigId&&localStorage.setItem("facebookConfigId",e.facebookConfigId),e.facebookUserToken&&localStorage.setItem("facebookUserToken",e.facebookUserToken),e.clientName&&localStorage.setItem("clientName",e.clientName)},M_=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version"),localStorage.removeItem("facebookAppId"),localStorage.removeItem("facebookConfigId"),localStorage.removeItem("facebookUserToken"),localStorage.removeItem("clientName")},Fs=e=>localStorage.getItem(e),Gt=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return!t||!n||!r?u.jsx(S_,{to:"/manager/login"}):e},l$=({children:e})=>{const t=Fs(rs.API_URL),n=Fs(rs.TOKEN),r=Fs(rs.VERSION);return t&&n&&r?u.jsx(S_,{to:"/"}):e};function O_(e,t){return function(){return e.apply(t,arguments)}}const{toString:u$}=Object.prototype,{getPrototypeOf:Mx}=Object,tg=(e=>t=>{const n=u$.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),fs=e=>(e=e.toLowerCase(),t=>tg(t)===e),ng=e=>t=>typeof t===e,{isArray:hu}=Array,od=ng("undefined");function c$(e){return e!==null&&!od(e)&&e.constructor!==null&&!od(e.constructor)&&Lr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const N_=fs("ArrayBuffer");function d$(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&N_(e.buffer),t}const f$=ng("string"),Lr=ng("function"),I_=ng("number"),rg=e=>e!==null&&typeof e=="object",p$=e=>e===!0||e===!1,fp=e=>{if(tg(e)!=="object")return!1;const t=Mx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},h$=fs("Date"),g$=fs("File"),m$=fs("Blob"),v$=fs("FileList"),y$=e=>rg(e)&&Lr(e.pipe),b$=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Lr(e.append)&&((t=tg(e))==="formdata"||t==="object"&&Lr(e.toString)&&e.toString()==="[object FormData]"))},x$=fs("URLSearchParams"),[w$,S$,C$,E$]=["ReadableStream","Request","Response","Headers"].map(fs),T$=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Bd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),hu(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const A_=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,F_=e=>!od(e)&&e!==A_;function Ay(){const{caseless:e}=F_(this)&&this||{},t={},n=(r,s)=>{const o=e&&D_(t,s)||s;fp(t[o])&&fp(r)?t[o]=Ay(t[o],r):fp(r)?t[o]=Ay({},r):hu(r)?t[o]=r.slice():t[o]=r};for(let r=0,s=arguments.length;r(Bd(t,(s,o)=>{n&&Lr(s)?e[o]=O_(s,n):e[o]=s},{allOwnKeys:r}),e),_$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),j$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},R$=(e,t,n,r)=>{let s,o,a;const l={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)a=s[o],(!r||r(a,e,t))&&!l[a]&&(t[a]=e[a],l[a]=!0);e=n!==!1&&Mx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},P$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},M$=e=>{if(!e)return null;if(hu(e))return e;let t=e.length;if(!I_(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},O$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Mx(Uint8Array)),N$=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},I$=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},D$=fs("HTMLFormElement"),A$=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),F0=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),F$=fs("RegExp"),L_=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Bd(n,(s,o)=>{let a;(a=t(s,o,e))!==!1&&(r[o]=a||s)}),Object.defineProperties(e,r)},L$=e=>{L_(e,(t,n)=>{if(Lr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Lr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},$$=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return hu(e)?r(e):r(String(e).split(t)),n},B$=()=>{},z$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,Fm="abcdefghijklmnopqrstuvwxyz",L0="0123456789",$_={DIGIT:L0,ALPHA:Fm,ALPHA_DIGIT:Fm+Fm.toUpperCase()+L0},U$=(e=16,t=$_.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function V$(e){return!!(e&&Lr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const H$=e=>{const t=new Array(10),n=(r,s)=>{if(rg(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[s]=r;const o=hu(r)?[]:{};return Bd(r,(a,l)=>{const c=n(a,s+1);!od(c)&&(o[l]=c)}),t[s]=void 0,o}}return r};return n(e,0)},K$=fs("AsyncFunction"),q$=e=>e&&(rg(e)||Lr(e))&&Lr(e.then)&&Lr(e.catch),$={isArray:hu,isArrayBuffer:N_,isBuffer:c$,isFormData:b$,isArrayBufferView:d$,isString:f$,isNumber:I_,isBoolean:p$,isObject:rg,isPlainObject:fp,isReadableStream:w$,isRequest:S$,isResponse:C$,isHeaders:E$,isUndefined:od,isDate:h$,isFile:g$,isBlob:m$,isRegExp:F$,isFunction:Lr,isStream:y$,isURLSearchParams:x$,isTypedArray:O$,isFileList:v$,forEach:Bd,merge:Ay,extend:k$,trim:T$,stripBOM:_$,inherits:j$,toFlatObject:R$,kindOf:tg,kindOfTest:fs,endsWith:P$,toArray:M$,forEachEntry:N$,matchAll:I$,isHTMLForm:D$,hasOwnProperty:F0,hasOwnProp:F0,reduceDescriptors:L_,freezeMethods:L$,toObjectSet:$$,toCamelCase:A$,noop:B$,toFiniteNumber:z$,findKey:D_,global:A_,isContextDefined:F_,ALPHABET:$_,generateString:U$,isSpecCompliantForm:V$,toJSONObject:H$,isAsyncFn:K$,isThenable:q$};function He(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}$.inherits(He,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const B_=He.prototype,z_={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{z_[e]={value:e}});Object.defineProperties(He,z_);Object.defineProperty(B_,"isAxiosError",{value:!0});He.from=(e,t,n,r,s,o)=>{const a=Object.create(B_);return $.toFlatObject(e,a,function(c){return c!==Error.prototype},l=>l!=="isAxiosError"),He.call(a,e.message,t,n,r,s),a.cause=e,a.name=e.name,o&&Object.assign(a,o),a};const W$=null;function Fy(e){return $.isPlainObject(e)||$.isArray(e)}function U_(e){return $.endsWith(e,"[]")?e.slice(0,-2):e}function $0(e,t,n){return e?e.concat(t).map(function(s,o){return s=U_(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function G$(e){return $.isArray(e)&&!e.some(Fy)}const J$=$.toFlatObject($,{},null,function(t){return/^is[A-Z]/.test(t)});function sg(e,t,n){if(!$.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,x){return!$.isUndefined(x[m])});const r=n.metaTokens,s=n.visitor||d,o=n.dots,a=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&$.isSpecCompliantForm(t);if(!$.isFunction(s))throw new TypeError("visitor must be a function");function i(g){if(g===null)return"";if($.isDate(g))return g.toISOString();if(!c&&$.isBlob(g))throw new He("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(g)||$.isTypedArray(g)?c&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function d(g,m,x){let b=g;if(g&&!x&&typeof g=="object"){if($.endsWith(m,"{}"))m=r?m:m.slice(0,-2),g=JSON.stringify(g);else if($.isArray(g)&&G$(g)||($.isFileList(g)||$.endsWith(m,"[]"))&&(b=$.toArray(g)))return m=U_(m),b.forEach(function(w,S){!($.isUndefined(w)||w===null)&&t.append(a===!0?$0([m],S,o):a===null?m:m+"[]",i(w))}),!1}return Fy(g)?!0:(t.append($0(x,m,o),i(g)),!1)}const p=[],f=Object.assign(J$,{defaultVisitor:d,convertValue:i,isVisitable:Fy});function h(g,m){if(!$.isUndefined(g)){if(p.indexOf(g)!==-1)throw Error("Circular reference detected in "+m.join("."));p.push(g),$.forEach(g,function(b,y){(!($.isUndefined(b)||b===null)&&s.call(t,b,$.isString(y)?y.trim():y,m,f))===!0&&h(b,m?m.concat(y):[y])}),p.pop()}}if(!$.isObject(e))throw new TypeError("data must be an object");return h(e),t}function B0(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Ox(e,t){this._pairs=[],e&&sg(e,this,t)}const V_=Ox.prototype;V_.append=function(t,n){this._pairs.push([t,n])};V_.toString=function(t){const n=t?function(r){return t.call(this,r,B0)}:B0;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Q$(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function H_(e,t,n){if(!t)return e;const r=n&&n.encode||Q$,s=n&&n.serialize;let o;if(s?o=s(t,n):o=$.isURLSearchParams(t)?t.toString():new Ox(t,n).toString(r),o){const a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class z0{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){$.forEach(this.handlers,function(r){r!==null&&t(r)})}}const K_={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z$=typeof URLSearchParams<"u"?URLSearchParams:Ox,Y$=typeof FormData<"u"?FormData:null,X$=typeof Blob<"u"?Blob:null,e4={isBrowser:!0,classes:{URLSearchParams:Z$,FormData:Y$,Blob:X$},protocols:["http","https","file","blob","url","data"]},Nx=typeof window<"u"&&typeof document<"u",t4=(e=>Nx&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),n4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",r4=Nx&&window.location.href||"http://localhost",s4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Nx,hasStandardBrowserEnv:t4,hasStandardBrowserWebWorkerEnv:n4,origin:r4},Symbol.toStringTag,{value:"Module"})),ss={...s4,...e4};function o4(e,t){return sg(e,new ss.classes.URLSearchParams,Object.assign({visitor:function(n,r,s,o){return ss.isNode&&$.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function a4(e){return $.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function i4(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r=n.length;return a=!a&&$.isArray(s)?s.length:a,c?($.hasOwnProp(s,a)?s[a]=[s[a],r]:s[a]=r,!l):((!s[a]||!$.isObject(s[a]))&&(s[a]=[]),t(n,r,s[a],o)&&$.isArray(s[a])&&(s[a]=i4(s[a])),!l)}if($.isFormData(e)&&$.isFunction(e.entries)){const n={};return $.forEachEntry(e,(r,s)=>{t(a4(r),s,n,0)}),n}return null}function l4(e,t,n){if($.isString(e))try{return(t||JSON.parse)(e),$.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const zd={transitional:K_,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=$.isObject(t);if(o&&$.isHTMLForm(t)&&(t=new FormData(t)),$.isFormData(t))return s?JSON.stringify(q_(t)):t;if($.isArrayBuffer(t)||$.isBuffer(t)||$.isStream(t)||$.isFile(t)||$.isBlob(t)||$.isReadableStream(t))return t;if($.isArrayBufferView(t))return t.buffer;if($.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return o4(t,this.formSerializer).toString();if((l=$.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return sg(l?{"files[]":t}:t,c&&new c,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),l4(t)):t}],transformResponse:[function(t){const n=this.transitional||zd.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if($.isResponse(t)||$.isReadableStream(t))return t;if(t&&$.isString(t)&&(r&&!this.responseType||s)){const a=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(l){if(a)throw l.name==="SyntaxError"?He.from(l,He.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ss.classes.FormData,Blob:ss.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],e=>{zd.headers[e]={}});const u4=$.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),c4=e=>{const t={};let n,r,s;return e&&e.split(` -`).forEach(function(a){s=a.indexOf(":"),n=a.substring(0,s).trim().toLowerCase(),r=a.substring(s+1).trim(),!(!n||t[n]&&u4[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},U0=Symbol("internals");function Gu(e){return e&&String(e).trim().toLowerCase()}function pp(e){return e===!1||e==null?e:$.isArray(e)?e.map(pp):String(e)}function d4(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const f4=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Lm(e,t,n,r,s){if($.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!$.isString(t)){if($.isString(r))return t.indexOf(r)!==-1;if($.isRegExp(r))return r.test(t)}}function p4(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function h4(e,t){const n=$.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,a){return this[r].call(this,t,s,o,a)},configurable:!0})})}let sr=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(l,c,i){const d=Gu(c);if(!d)throw new Error("header name must be a non-empty string");const p=$.findKey(s,d);(!p||s[p]===void 0||i===!0||i===void 0&&s[p]!==!1)&&(s[p||c]=pp(l))}const a=(l,c)=>$.forEach(l,(i,d)=>o(i,d,c));if($.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if($.isString(t)&&(t=t.trim())&&!f4(t))a(c4(t),n);else if($.isHeaders(t))for(const[l,c]of t.entries())o(c,l,r);else t!=null&&o(n,t,r);return this}get(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return d4(s);if($.isFunction(n))return n.call(this,s,r);if($.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Gu(t),t){const r=$.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Lm(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(a){if(a=Gu(a),a){const l=$.findKey(r,a);l&&(!n||Lm(r,r[l],l,n))&&(delete r[l],s=!0)}}return $.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||Lm(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return $.forEach(this,(s,o)=>{const a=$.findKey(r,o);if(a){n[a]=pp(s),delete n[o];return}const l=t?p4(o):String(o).trim();l!==o&&delete n[o],n[l]=pp(s),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return $.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&$.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` -`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[U0]=this[U0]={accessors:{}}).accessors,s=this.prototype;function o(a){const l=Gu(a);r[l]||(h4(s,a),r[l]=!0)}return $.isArray(t)?t.forEach(o):o(t),this}};sr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);$.reduceDescriptors(sr.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});$.freezeMethods(sr);function $m(e,t){const n=this||zd,r=t||n,s=sr.from(r.headers);let o=r.data;return $.forEach(e,function(l){o=l.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function W_(e){return!!(e&&e.__CANCEL__)}function gu(e,t,n){He.call(this,e??"canceled",He.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(gu,He,{__CANCEL__:!0});function G_(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new He("Request failed with status code "+n.status,[He.ERR_BAD_REQUEST,He.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function g4(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function m4(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,a;return t=t!==void 0?t:1e3,function(c){const i=Date.now(),d=r[o];a||(a=i),n[s]=c,r[s]=i;let p=o,f=0;for(;p!==s;)f+=n[p++],p=p%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),i-ar)return s&&(clearTimeout(s),s=null),n=l,e.apply(null,arguments);s||(s=setTimeout(()=>(s=null,n=Date.now(),e.apply(null,arguments)),r-(l-n)))}}const eh=(e,t,n=3)=>{let r=0;const s=m4(50,250);return v4(o=>{const a=o.loaded,l=o.lengthComputable?o.total:void 0,c=a-r,i=s(c),d=a<=l;r=a;const p={loaded:a,total:l,progress:l?a/l:void 0,bytes:c,rate:i||void 0,estimated:i&&l&&d?(l-a)/i:void 0,event:o,lengthComputable:l!=null};p[t?"download":"upload"]=!0,e(p)},n)},y4=ss.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function s(o){let a=o;return t&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=s(window.location.href),function(a){const l=$.isString(a)?s(a):a;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}(),b4=ss.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const a=[e+"="+encodeURIComponent(t)];$.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),$.isString(r)&&a.push("path="+r),$.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function x4(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function w4(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function J_(e,t){return e&&!x4(t)?w4(e,t):t}const V0=e=>e instanceof sr?{...e}:e;function Si(e,t){t=t||{};const n={};function r(i,d,p){return $.isPlainObject(i)&&$.isPlainObject(d)?$.merge.call({caseless:p},i,d):$.isPlainObject(d)?$.merge({},d):$.isArray(d)?d.slice():d}function s(i,d,p){if($.isUndefined(d)){if(!$.isUndefined(i))return r(void 0,i,p)}else return r(i,d,p)}function o(i,d){if(!$.isUndefined(d))return r(void 0,d)}function a(i,d){if($.isUndefined(d)){if(!$.isUndefined(i))return r(void 0,i)}else return r(void 0,d)}function l(i,d,p){if(p in t)return r(i,d);if(p in e)return r(void 0,i)}const c={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:l,headers:(i,d)=>s(V0(i),V0(d),!0)};return $.forEach(Object.keys(Object.assign({},e,t)),function(d){const p=c[d]||s,f=p(e[d],t[d],d);$.isUndefined(f)&&p!==l||(n[d]=f)}),n}const Q_=e=>{const t=Si({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:l}=t;t.headers=a=sr.from(a),t.url=H_(J_(t.baseURL,t.url),e.params,e.paramsSerializer),l&&a.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):"")));let c;if($.isFormData(n)){if(ss.hasStandardBrowserEnv||ss.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if((c=a.getContentType())!==!1){const[i,...d]=c?c.split(";").map(p=>p.trim()).filter(Boolean):[];a.setContentType([i||"multipart/form-data",...d].join("; "))}}if(ss.hasStandardBrowserEnv&&(r&&$.isFunction(r)&&(r=r(t)),r||r!==!1&&y4(t.url))){const i=s&&o&&b4.read(o);i&&a.set(s,i)}return t},S4=typeof XMLHttpRequest<"u",C4=S4&&function(e){return new Promise(function(n,r){const s=Q_(e);let o=s.data;const a=sr.from(s.headers).normalize();let{responseType:l}=s,c;function i(){s.cancelToken&&s.cancelToken.unsubscribe(c),s.signal&&s.signal.removeEventListener("abort",c)}let d=new XMLHttpRequest;d.open(s.method.toUpperCase(),s.url,!0),d.timeout=s.timeout;function p(){if(!d)return;const h=sr.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),m={data:!l||l==="text"||l==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:h,config:e,request:d};G_(function(b){n(b),i()},function(b){r(b),i()},m),d=null}"onloadend"in d?d.onloadend=p:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(p)},d.onabort=function(){d&&(r(new He("Request aborted",He.ECONNABORTED,s,d)),d=null)},d.onerror=function(){r(new He("Network Error",He.ERR_NETWORK,s,d)),d=null},d.ontimeout=function(){let g=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const m=s.transitional||K_;s.timeoutErrorMessage&&(g=s.timeoutErrorMessage),r(new He(g,m.clarifyTimeoutError?He.ETIMEDOUT:He.ECONNABORTED,s,d)),d=null},o===void 0&&a.setContentType(null),"setRequestHeader"in d&&$.forEach(a.toJSON(),function(g,m){d.setRequestHeader(m,g)}),$.isUndefined(s.withCredentials)||(d.withCredentials=!!s.withCredentials),l&&l!=="json"&&(d.responseType=s.responseType),typeof s.onDownloadProgress=="function"&&d.addEventListener("progress",eh(s.onDownloadProgress,!0)),typeof s.onUploadProgress=="function"&&d.upload&&d.upload.addEventListener("progress",eh(s.onUploadProgress)),(s.cancelToken||s.signal)&&(c=h=>{d&&(r(!h||h.type?new gu(null,e,d):h),d.abort(),d=null)},s.cancelToken&&s.cancelToken.subscribe(c),s.signal&&(s.signal.aborted?c():s.signal.addEventListener("abort",c)));const f=g4(s.url);if(f&&ss.protocols.indexOf(f)===-1){r(new He("Unsupported protocol "+f+":",He.ERR_BAD_REQUEST,e));return}d.send(o||null)})},E4=(e,t)=>{let n=new AbortController,r;const s=function(c){if(!r){r=!0,a();const i=c instanceof Error?c:this.reason;n.abort(i instanceof He?i:new gu(i instanceof Error?i.message:i))}};let o=t&&setTimeout(()=>{s(new He(`timeout ${t} of ms exceeded`,He.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(c=>{c&&(c.removeEventListener?c.removeEventListener("abort",s):c.unsubscribe(s))}),e=null)};e.forEach(c=>c&&c.addEventListener&&c.addEventListener("abort",s));const{signal:l}=n;return l.unsubscribe=a,[l,()=>{o&&clearTimeout(o),o=null}]},T4=function*(e,t){let n=e.byteLength;if(!t||n{const o=k4(e,t,s);let a=0;return new ReadableStream({type:"bytes",async pull(l){const{done:c,value:i}=await o.next();if(c){l.close(),r();return}let d=i.byteLength;n&&n(a+=d),l.enqueue(new Uint8Array(i))},cancel(l){return r(l),o.return()}},{highWaterMark:2})},K0=(e,t)=>{const n=e!=null;return r=>setTimeout(()=>t({lengthComputable:n,total:e,loaded:r}))},og=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Z_=og&&typeof ReadableStream=="function",Ly=og&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),_4=Z_&&(()=>{let e=!1;const t=new Request(ss.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})(),q0=64*1024,$y=Z_&&!!(()=>{try{return $.isReadableStream(new Response("").body)}catch{}})(),th={stream:$y&&(e=>e.body)};og&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!th[t]&&(th[t]=$.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new He(`Response type '${t}' is not supported`,He.ERR_NOT_SUPPORT,r)})})})(new Response);const j4=async e=>{if(e==null)return 0;if($.isBlob(e))return e.size;if($.isSpecCompliantForm(e))return(await new Request(e).arrayBuffer()).byteLength;if($.isArrayBufferView(e))return e.byteLength;if($.isURLSearchParams(e)&&(e=e+""),$.isString(e))return(await Ly(e)).byteLength},R4=async(e,t)=>{const n=$.toFiniteNumber(e.getContentLength());return n??j4(t)},P4=og&&(async e=>{let{url:t,method:n,data:r,signal:s,cancelToken:o,timeout:a,onDownloadProgress:l,onUploadProgress:c,responseType:i,headers:d,withCredentials:p="same-origin",fetchOptions:f}=Q_(e);i=i?(i+"").toLowerCase():"text";let[h,g]=s||o||a?E4([s,o],a):[],m,x;const b=()=>{!m&&setTimeout(()=>{h&&h.unsubscribe()}),m=!0};let y;try{if(c&&_4&&n!=="get"&&n!=="head"&&(y=await R4(d,r))!==0){let C=new Request(t,{method:"POST",body:r,duplex:"half"}),k;$.isFormData(r)&&(k=C.headers.get("content-type"))&&d.setContentType(k),C.body&&(r=H0(C.body,q0,K0(y,eh(c)),null,Ly))}$.isString(p)||(p=p?"cors":"omit"),x=new Request(t,{...f,signal:h,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",withCredentials:p});let w=await fetch(x);const S=$y&&(i==="stream"||i==="response");if($y&&(l||S)){const C={};["status","statusText","headers"].forEach(T=>{C[T]=w[T]});const k=$.toFiniteNumber(w.headers.get("content-length"));w=new Response(H0(w.body,q0,l&&K0(k,eh(l,!0)),S&&b,Ly),C)}i=i||"text";let E=await th[$.findKey(th,i)||"text"](w,e);return!S&&b(),g&&g(),await new Promise((C,k)=>{G_(C,k,{data:E,headers:sr.from(w.headers),status:w.status,statusText:w.statusText,config:e,request:x})})}catch(w){throw b(),w&&w.name==="TypeError"&&/fetch/i.test(w.message)?Object.assign(new He("Network Error",He.ERR_NETWORK,e,x),{cause:w.cause||w}):He.from(w,w&&w.code,e,x)}}),By={http:W$,xhr:C4,fetch:P4};$.forEach(By,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const W0=e=>`- ${e}`,M4=e=>$.isFunction(e)||e===null||e===!1,Y_={getAdapter:e=>{e=$.isArray(e)?e:[e];const{length:t}=e;let n,r;const s={};for(let o=0;o`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since : -`+o.map(W0).join(` -`):" "+W0(o[0]):"as no adapter specified";throw new He("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:By};function Bm(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new gu(null,e)}function G0(e){return Bm(e),e.headers=sr.from(e.headers),e.data=$m.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Y_.getAdapter(e.adapter||zd.adapter)(e).then(function(r){return Bm(e),r.data=$m.call(e,e.transformResponse,r),r.headers=sr.from(r.headers),r},function(r){return W_(r)||(Bm(e),r&&r.response&&(r.response.data=$m.call(e,e.transformResponse,r.response),r.response.headers=sr.from(r.response.headers))),Promise.reject(r)})}const X_="1.7.2",Ix={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ix[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const J0={};Ix.transitional=function(t,n,r){function s(o,a){return"[Axios v"+X_+"] Transitional option '"+o+"'"+a+(r?". "+r:"")}return(o,a,l)=>{if(t===!1)throw new He(s(a," has been removed"+(n?" in "+n:"")),He.ERR_DEPRECATED);return n&&!J0[a]&&(J0[a]=!0,console.warn(s(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,a,l):!0}};function O4(e,t,n){if(typeof e!="object")throw new He("options must be an object",He.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],a=t[o];if(a){const l=e[o],c=l===void 0||a(l,o,e);if(c!==!0)throw new He("option "+o+" must be "+c,He.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new He("Unknown option "+o,He.ERR_BAD_OPTION)}}const zy={assertOptions:O4,validators:Ix},Oo=zy.validators;let di=class{constructor(t){this.defaults=t,this.interceptors={request:new z0,response:new z0}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Si(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&zy.assertOptions(r,{silentJSONParsing:Oo.transitional(Oo.boolean),forcedJSONParsing:Oo.transitional(Oo.boolean),clarifyTimeoutError:Oo.transitional(Oo.boolean)},!1),s!=null&&($.isFunction(s)?n.paramsSerializer={serialize:s}:zy.assertOptions(s,{encode:Oo.function,serialize:Oo.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=o&&$.merge(o.common,o[n.method]);o&&$.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),n.headers=sr.concat(a,o);const l=[];let c=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(c=c&&m.synchronous,l.unshift(m.fulfilled,m.rejected))});const i=[];this.interceptors.response.forEach(function(m){i.push(m.fulfilled,m.rejected)});let d,p=0,f;if(!c){const g=[G0.bind(this),void 0];for(g.unshift.apply(g,l),g.push.apply(g,i),f=g.length,d=Promise.resolve(n);p{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const a=new Promise(l=>{r.subscribe(l),o=l}).then(s);return a.cancel=function(){r.unsubscribe(o)},a},t(function(o,a,l){r.reason||(r.reason=new gu(o,a,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ej(function(s){t=s}),cancel:t}}};function I4(e){return function(n){return e.apply(null,n)}}function D4(e){return $.isObject(e)&&e.isAxiosError===!0}const Uy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Uy).forEach(([e,t])=>{Uy[t]=e});function tj(e){const t=new di(e),n=O_(di.prototype.request,t);return $.extend(n,di.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return tj(Si(e,s))},n}const zt=tj(zd);zt.Axios=di;zt.CanceledError=gu;zt.CancelToken=N4;zt.isCancel=W_;zt.VERSION=X_;zt.toFormData=sg;zt.AxiosError=He;zt.Cancel=zt.CanceledError;zt.all=function(t){return Promise.all(t)};zt.spread=I4;zt.isAxiosError=D4;zt.mergeConfig=Si;zt.AxiosHeaders=sr;zt.formToJSON=e=>q_($.isHTMLForm(e)?new FormData(e):e);zt.getAdapter=Y_.getAdapter;zt.HttpStatusCode=Uy;zt.default=zt;const{Axios:Mse,AxiosError:Ose,CanceledError:Nse,isCancel:Ise,CancelToken:Dse,VERSION:Ase,all:Fse,Cancel:Lse,isAxiosError:A4,spread:$se,toFormData:Bse,AxiosHeaders:zse,HttpStatusCode:Use,formToJSON:Vse,getAdapter:Hse,mergeConfig:Kse}=zt,F4=e=>["auth","verifyServer",JSON.stringify(e)],nj=async({url:e})=>(await zt.get(`${e}/`)).data,L4=e=>{const{url:t,...n}=e;return lt({...n,queryKey:F4({url:t}),queryFn:()=>nj({url:t}),enabled:!!t})};function $4(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function ag(...e){return t=>e.forEach(n=>$4(n,t))}function it(...e){return v.useCallback(ag(...e),e)}var mo=v.forwardRef((e,t)=>{const{children:n,...r}=e,s=v.Children.toArray(n),o=s.find(z4);if(o){const a=o.props.children,l=s.map(c=>c===o?v.Children.count(a)>1?v.Children.only(null):v.isValidElement(a)?a.props.children:null:c);return u.jsx(Vy,{...r,ref:t,children:v.isValidElement(a)?v.cloneElement(a,void 0,l):null})}return u.jsx(Vy,{...r,ref:t,children:n})});mo.displayName="Slot";var Vy=v.forwardRef((e,t)=>{const{children:n,...r}=e;if(v.isValidElement(n)){const s=V4(n);return v.cloneElement(n,{...U4(r,n.props),ref:t?ag(t,s):s})}return v.Children.count(n)>1?v.Children.only(null):null});Vy.displayName="SlotClone";var B4=({children:e})=>u.jsx(u.Fragment,{children:e});function z4(e){return v.isValidElement(e)&&e.type===B4}function U4(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...l)=>{o(...l),s(...l)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function V4(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function rj(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,Z0=H4,ig=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return Z0(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:s,defaultVariants:o}=t,a=Object.keys(s).map(i=>{const d=n==null?void 0:n[i],p=o==null?void 0:o[i];if(d===null)return null;const f=Q0(d)||Q0(p);return s[i][f]}),l=n&&Object.entries(n).reduce((i,d)=>{let[p,f]=d;return f===void 0||(i[p]=f),i},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((i,d)=>{let{class:p,className:f,...h}=d;return Object.entries(h).every(g=>{let[m,x]=g;return Array.isArray(x)?x.includes({...o,...l}[m]):{...o,...l}[m]===x})?[...i,p,f]:i},[]);return Z0(e,a,c,n==null?void 0:n.class,n==null?void 0:n.className)},Dx="-";function K4(e){const t=W4(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;function s(a){const l=a.split(Dx);return l[0]===""&&l.length!==1&&l.shift(),sj(l,t)||q4(a)}function o(a,l){const c=n[a]||[];return l&&r[a]?[...c,...r[a]]:c}return{getClassGroupId:s,getConflictingClassGroupIds:o}}function sj(e,t){var a;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?sj(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Dx);return(a=t.validators.find(({validator:l})=>l(o)))==null?void 0:a.classGroupId}const Y0=/^\[(.+)\]$/;function q4(e){if(Y0.test(e)){const t=Y0.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function W4(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return J4(Object.entries(e.classGroups),n).forEach(([o,a])=>{Hy(a,r,o,t)}),r}function Hy(e,t,n,r){e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:X0(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(G4(s)){Hy(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,a])=>{Hy(a,X0(t,o),n,r)})})}function X0(e,t){let n=e;return t.split(Dx).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function G4(e){return e.isThemeGetter}function J4(e,t){return t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,l])=>[t+a,l])):o);return[n,s]}):e}function Q4(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function s(o,a){n.set(o,a),t++,t>e&&(t=0,r=n,n=new Map)}return{get(o){let a=n.get(o);if(a!==void 0)return a;if((a=r.get(o))!==void 0)return s(o,a),a},set(o,a){n.has(o)?n.set(o,a):s(o,a)}}}const oj="!";function Z4(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length;function a(l){const c=[];let i=0,d=0,p;for(let x=0;xd?p-d:void 0;return{modifiers:c,hasImportantModifier:h,baseClassName:g,maybePostfixModifierPosition:m}}return n?function(c){return n({className:c,parseClassName:a})}:a}function Y4(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function X4(e){return{cache:Q4(e.cacheSize),parseClassName:Z4(e),...K4(e)}}const e3=/\s+/;function t3(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=new Set;return e.trim().split(e3).map(a=>{const{modifiers:l,hasImportantModifier:c,baseClassName:i,maybePostfixModifierPosition:d}=n(a);let p=!!d,f=r(p?i.substring(0,d):i);if(!f){if(!p)return{isTailwindClass:!1,originalClassName:a};if(f=r(i),!f)return{isTailwindClass:!1,originalClassName:a};p=!1}const h=Y4(l).join(":");return{isTailwindClass:!0,modifierId:c?h+oj:h,classGroupId:f,originalClassName:a,hasPostfixModifier:p}}).reverse().filter(a=>{if(!a.isTailwindClass)return!0;const{modifierId:l,classGroupId:c,hasPostfixModifier:i}=a,d=l+c;return o.has(d)?!1:(o.add(d),s(c,i).forEach(p=>o.add(l+p)),!0)}).reverse().map(a=>a.originalClassName).join(" ")}function n3(){let e=0,t,n,r="";for(;ep(d),e());return n=X4(i),r=n.cache.get,s=n.cache.set,o=l,l(c)}function l(c){const i=r(c);if(i)return i;const d=t3(c,n);return s(c,d),d}return function(){return o(n3.apply(null,arguments))}}function _t(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const ij=/^\[(?:([a-z-]+):)?(.+)\]$/i,s3=/^\d+\/\d+$/,o3=new Set(["px","full","screen"]),a3=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,i3=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,l3=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,u3=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,c3=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function qs(e){return Ga(e)||o3.has(e)||s3.test(e)}function No(e){return mu(e,"length",y3)}function Ga(e){return!!e&&!Number.isNaN(Number(e))}function Pf(e){return mu(e,"number",Ga)}function Ju(e){return!!e&&Number.isInteger(Number(e))}function d3(e){return e.endsWith("%")&&Ga(e.slice(0,-1))}function We(e){return ij.test(e)}function Io(e){return a3.test(e)}const f3=new Set(["length","size","percentage"]);function p3(e){return mu(e,f3,lj)}function h3(e){return mu(e,"position",lj)}const g3=new Set(["image","url"]);function m3(e){return mu(e,g3,x3)}function v3(e){return mu(e,"",b3)}function Qu(){return!0}function mu(e,t,n){const r=ij.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function y3(e){return i3.test(e)&&!l3.test(e)}function lj(){return!1}function b3(e){return u3.test(e)}function x3(e){return c3.test(e)}function w3(){const e=_t("colors"),t=_t("spacing"),n=_t("blur"),r=_t("brightness"),s=_t("borderColor"),o=_t("borderRadius"),a=_t("borderSpacing"),l=_t("borderWidth"),c=_t("contrast"),i=_t("grayscale"),d=_t("hueRotate"),p=_t("invert"),f=_t("gap"),h=_t("gradientColorStops"),g=_t("gradientColorStopPositions"),m=_t("inset"),x=_t("margin"),b=_t("opacity"),y=_t("padding"),w=_t("saturate"),S=_t("scale"),E=_t("sepia"),C=_t("skew"),k=_t("space"),T=_t("translate"),P=()=>["auto","contain","none"],N=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto",We,t],I=()=>[We,t],Z=()=>["",qs,No],V=()=>["auto",Ga,We],Q=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ee=()=>["solid","dashed","dotted","double","none"],W=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>["start","end","center","between","around","evenly","stretch"],A=()=>["","0",We],Y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],de=()=>[Ga,Pf],z=()=>[Ga,We];return{cacheSize:500,separator:":",theme:{colors:[Qu],spacing:[qs,No],blur:["none","",Io,We],brightness:de(),borderColor:[e],borderRadius:["none","","full",Io,We],borderSpacing:I(),borderWidth:Z(),contrast:de(),grayscale:A(),hueRotate:z(),invert:A(),gap:I(),gradientColorStops:[e],gradientColorStopPositions:[d3,No],inset:U(),margin:U(),opacity:de(),padding:I(),saturate:de(),scale:de(),sepia:A(),skew:z(),space:I(),translate:I()},classGroups:{aspect:[{aspect:["auto","square","video",We]}],container:["container"],columns:[{columns:[Io]}],"break-after":[{"break-after":Y()}],"break-before":[{"break-before":Y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Q(),We]}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[m]}],"inset-x":[{"inset-x":[m]}],"inset-y":[{"inset-y":[m]}],start:[{start:[m]}],end:[{end:[m]}],top:[{top:[m]}],right:[{right:[m]}],bottom:[{bottom:[m]}],left:[{left:[m]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ju,We]}],basis:[{basis:U()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",We]}],grow:[{grow:A()}],shrink:[{shrink:A()}],order:[{order:["first","last","none",Ju,We]}],"grid-cols":[{"grid-cols":[Qu]}],"col-start-end":[{col:["auto",{span:["full",Ju,We]},We]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[Qu]}],"row-start-end":[{row:["auto",{span:[Ju,We]},We]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",We]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",We]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...F()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...F(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...F(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",We,t]}],"min-w":[{"min-w":[We,t,"min","max","fit"]}],"max-w":[{"max-w":[We,t,"none","full","min","max","fit","prose",{screen:[Io]},Io]}],h:[{h:[We,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[We,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[We,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Io,No]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Pf]}],"font-family":[{font:[Qu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",We]}],"line-clamp":[{"line-clamp":["none",Ga,Pf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",qs,We]}],"list-image":[{"list-image":["none",We]}],"list-style-type":[{list:["none","disc","decimal",We]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ee(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",qs,No]}],"underline-offset":[{"underline-offset":["auto",qs,We]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:I()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",We]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",We]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Q(),h3]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",p3]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},m3]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...ee(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:ee()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...ee()]}],"outline-offset":[{"outline-offset":[qs,We]}],"outline-w":[{outline:[qs,No]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[qs,No]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Io,v3]}],"shadow-color":[{shadow:[Qu]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...W(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":W()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Io,We]}],grayscale:[{grayscale:[i]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[p]}],saturate:[{saturate:[w]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[i]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",We]}],duration:[{duration:z()}],ease:[{ease:["linear","in","out","in-out",We]}],delay:[{delay:z()}],animate:[{animate:["none","spin","ping","pulse","bounce",We]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ju,We]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",We]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",We]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":I()}],"scroll-mx":[{"scroll-mx":I()}],"scroll-my":[{"scroll-my":I()}],"scroll-ms":[{"scroll-ms":I()}],"scroll-me":[{"scroll-me":I()}],"scroll-mt":[{"scroll-mt":I()}],"scroll-mr":[{"scroll-mr":I()}],"scroll-mb":[{"scroll-mb":I()}],"scroll-ml":[{"scroll-ml":I()}],"scroll-p":[{"scroll-p":I()}],"scroll-px":[{"scroll-px":I()}],"scroll-py":[{"scroll-py":I()}],"scroll-ps":[{"scroll-ps":I()}],"scroll-pe":[{"scroll-pe":I()}],"scroll-pt":[{"scroll-pt":I()}],"scroll-pr":[{"scroll-pr":I()}],"scroll-pb":[{"scroll-pb":I()}],"scroll-pl":[{"scroll-pl":I()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",We]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[qs,No,Pf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const S3=r3(w3);function ge(...e){return S3(oo(e))}const C3=ig("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",warning:"bg-amber-600 shadow-sm hover:bg-amber-600/90 data-active:bg-amber-600/90 text-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),q=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...s},o)=>{const a=r?mo:"button";return u.jsx(a,{className:ge(C3({variant:t,size:n,className:e})),ref:o,...s})});q.displayName="Button";function Ax(){const{t:e}=ze(),t=Fs(rs.API_URL),{data:n}=L4({url:t}),r=v.useMemo(()=>n==null?void 0:n.clientName,[n]),s=v.useMemo(()=>n==null?void 0:n.version,[n]),o=[{name:"Discord",url:"https://evolution-api.com/discord"},{name:"Postman",url:"https://evolution-api.com/postman"},{name:"GitHub",url:"https://github.com/EvolutionAPI/evolution-api"},{name:"Docs",url:"https://doc.evolution-api.com"}];return u.jsxs("footer",{className:"flex w-full flex-col items-center justify-between p-6 text-xs text-secondary-foreground sm:flex-row",children:[u.jsxs("div",{className:"flex items-center space-x-3 divide-x",children:[r&&r!==""&&u.jsxs("span",{children:[e("footer.clientName"),": ",u.jsx("strong",{children:r})]}),s&&s!==""&&u.jsxs("span",{className:"pl-3",children:[e("footer.version"),": ",u.jsx("strong",{children:s})]})]}),u.jsx("div",{className:"flex gap-2",children:o.map(a=>u.jsx(q,{variant:"link",asChild:!0,size:"sm",className:"text-xs",children:u.jsx("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",children:a.name})},a.url))})]})}/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const E3=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),uj=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var T3={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const k3=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:o,iconNode:a,...l},c)=>v.createElement("svg",{ref:c,...T3,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:uj("lucide",s),...l},[...a.map(([i,d])=>v.createElement(i,d)),...Array.isArray(o)?o:[o]]));/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Xe=(e,t)=>{const n=v.forwardRef(({className:r,...s},o)=>v.createElement(k3,{ref:o,iconNode:t,className:uj(`lucide-${E3(e)}`,r),...s}));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _3=Xe("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const j3=Xe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const cj=Xe("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const lg=Xe("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const R3=Xe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const P3=Xe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const M3=Xe("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const O3=Xe("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ud=Xe("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dj=Xe("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const N3=Xe("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Oi=Xe("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const I3=Xe("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Vd=Xe("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const D3=Xe("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const vu=Xe("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const A3=Xe("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const F3=Xe("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const L3=Xe("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const $3=Xe("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const B3=Xe("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const z3=Xe("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const U3=Xe("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const V3=Xe("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Hd=Xe("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const H3=Xe("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ug=Xe("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const K3=Xe("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const q3=Xe("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Kd=Xe("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const qd=Xe("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ni=Xe("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fj=Xe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Wd=Xe("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const W3=Xe("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const G3=Xe("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const J3=Xe("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Q3=Xe("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** - * @license lucide-react v0.408.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const pj=Xe("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),he=zt.create({timeout:3e4});he.interceptors.request.use(async e=>{const t=Fs(rs.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=Fs(rs.TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const Z3=e=>["instance","fetchInstance",JSON.stringify(e)],Y3=async({instanceId:e})=>{const t=await he.get("/instance/fetchInstances",{params:{instanceId:e}});return Array.isArray(t.data)?t.data[0]:t.data},hj=e=>{const{instanceId:t,...n}=e;return lt({...n,queryKey:Z3({instanceId:t}),queryFn:()=>Y3({instanceId:t}),enabled:!!t})};function Se(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e==null||e(s),n===!1||!s.defaultPrevented)return t==null?void 0:t(s)}}function X3(e,t){const n=v.createContext(t);function r(o){const{children:a,...l}=o,c=v.useMemo(()=>l,Object.values(l));return u.jsx(n.Provider,{value:c,children:a})}function s(o){const a=v.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function Vr(e,t=[]){let n=[];function r(o,a){const l=v.createContext(a),c=n.length;n=[...n,a];function i(p){const{scope:f,children:h,...g}=p,m=(f==null?void 0:f[e][c])||l,x=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:x,children:h})}function d(p,f){const h=(f==null?void 0:f[e][c])||l,g=v.useContext(h);if(g)return g;if(a!==void 0)return a;throw new Error(`\`${p}\` must be used within \`${o}\``)}return i.displayName=o+"Provider",[i,d]}const s=()=>{const o=n.map(a=>v.createContext(a));return function(l){const c=(l==null?void 0:l[e])||o;return v.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return s.scopeName=e,[r,eB(s,...t)]}function eB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const a=r.reduce((l,{useScope:c,scopeName:i})=>{const p=c(o)[`__scope${i}`];return{...l,...p}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function nn(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function pa({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,s]=tB({defaultProp:t,onChange:n}),o=e!==void 0,a=o?e:r,l=nn(n),c=v.useCallback(i=>{if(o){const p=typeof i=="function"?i(e):i;p!==e&&l(p)}else s(i)},[o,e,s,l]);return[a,c]}function tB({defaultProp:e,onChange:t}){const n=v.useState(e),[r]=n,s=v.useRef(r),o=nn(t);return v.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),n}var nB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ne=nB.reduce((e,t)=>{const n=v.forwardRef((r,s)=>{const{asChild:o,...a}=r,l=o?mo:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function gj(e,t){e&&ka.flushSync(()=>e.dispatchEvent(t))}function Fx(e){const t=e+"CollectionProvider",[n,r]=Vr(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=h=>{const{scope:g,children:m}=h,x=Te.useRef(null),b=Te.useRef(new Map).current;return u.jsx(s,{scope:g,itemMap:b,collectionRef:x,children:m})};a.displayName=t;const l=e+"CollectionSlot",c=Te.forwardRef((h,g)=>{const{scope:m,children:x}=h,b=o(l,m),y=it(g,b.collectionRef);return u.jsx(mo,{ref:y,children:x})});c.displayName=l;const i=e+"CollectionItemSlot",d="data-radix-collection-item",p=Te.forwardRef((h,g)=>{const{scope:m,children:x,...b}=h,y=Te.useRef(null),w=it(g,y),S=o(i,m);return Te.useEffect(()=>(S.itemMap.set(y,{ref:y,...b}),()=>void S.itemMap.delete(y))),u.jsx(mo,{[d]:"",ref:w,children:x})});p.displayName=i;function f(h){const g=o(e+"CollectionConsumer",h);return Te.useCallback(()=>{const x=g.collectionRef.current;if(!x)return[];const b=Array.from(x.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((S,E)=>b.indexOf(S.ref.current)-b.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:a,Slot:c,ItemSlot:p},f,r]}var rB=v.createContext(void 0);function Gd(e){const t=v.useContext(rB);return e||t||"ltr"}function sB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e);v.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var oB="DismissableLayer",Ky="dismissableLayer.update",aB="dismissableLayer.pointerDownOutside",iB="dismissableLayer.focusOutside",eC,mj=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),cg=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:a,onDismiss:l,...c}=e,i=v.useContext(mj),[d,p]=v.useState(null),f=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=it(t,k=>p(k)),m=Array.from(i.layers),[x]=[...i.layersWithOutsidePointerEventsDisabled].slice(-1),b=m.indexOf(x),y=d?m.indexOf(d):-1,w=i.layersWithOutsidePointerEventsDisabled.size>0,S=y>=b,E=cB(k=>{const T=k.target,P=[...i.branches].some(N=>N.contains(T));!S||P||(s==null||s(k),a==null||a(k),k.defaultPrevented||l==null||l())},f),C=dB(k=>{const T=k.target;[...i.branches].some(N=>N.contains(T))||(o==null||o(k),a==null||a(k),k.defaultPrevented||l==null||l())},f);return sB(k=>{y===i.layers.size-1&&(r==null||r(k),!k.defaultPrevented&&l&&(k.preventDefault(),l()))},f),v.useEffect(()=>{if(d)return n&&(i.layersWithOutsidePointerEventsDisabled.size===0&&(eC=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),i.layersWithOutsidePointerEventsDisabled.add(d)),i.layers.add(d),tC(),()=>{n&&i.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=eC)}},[d,f,n,i]),v.useEffect(()=>()=>{d&&(i.layers.delete(d),i.layersWithOutsidePointerEventsDisabled.delete(d),tC())},[d,i]),v.useEffect(()=>{const k=()=>h({});return document.addEventListener(Ky,k),()=>document.removeEventListener(Ky,k)},[]),u.jsx(Ne.div,{...c,ref:g,style:{pointerEvents:w?S?"auto":"none":void 0,...e.style},onFocusCapture:Se(e.onFocusCapture,C.onFocusCapture),onBlurCapture:Se(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Se(e.onPointerDownCapture,E.onPointerDownCapture)})});cg.displayName=oB;var lB="DismissableLayerBranch",uB=v.forwardRef((e,t)=>{const n=v.useContext(mj),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),u.jsx(Ne.div,{...e,ref:s})});uB.displayName=lB;function cB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1),s=v.useRef(()=>{});return v.useEffect(()=>{const o=l=>{if(l.target&&!r.current){let c=function(){vj(aB,n,i,{discrete:!0})};const i={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=c,t.addEventListener("click",s.current,{once:!0})):c()}else t.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function dB(e,t=globalThis==null?void 0:globalThis.document){const n=nn(e),r=v.useRef(!1);return v.useEffect(()=>{const s=o=>{o.target&&!r.current&&vj(iB,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function tC(){const e=new CustomEvent(Ky);document.dispatchEvent(e)}function vj(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?gj(s,o):s.dispatchEvent(o)}var zm=0;function Lx(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??nC()),document.body.insertAdjacentElement("beforeend",e[1]??nC()),zm++,()=>{zm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zm--}},[])}function nC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Um="focusScope.autoFocusOnMount",Vm="focusScope.autoFocusOnUnmount",rC={bubbles:!1,cancelable:!0},fB="FocusScope",dg=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[l,c]=v.useState(null),i=nn(s),d=nn(o),p=v.useRef(null),f=it(t,m=>c(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(w){if(h.paused||!l)return;const S=w.target;l.contains(S)?p.current=S:Lo(p.current,{select:!0})},x=function(w){if(h.paused||!l)return;const S=w.relatedTarget;S!==null&&(l.contains(S)||Lo(p.current,{select:!0}))},b=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Lo(l)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const y=new MutationObserver(b);return l&&y.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),y.disconnect()}}},[r,l,h.paused]),v.useEffect(()=>{if(l){oC.add(h);const m=document.activeElement;if(!l.contains(m)){const b=new CustomEvent(Um,rC);l.addEventListener(Um,i),l.dispatchEvent(b),b.defaultPrevented||(pB(yB(yj(l)),{select:!0}),document.activeElement===m&&Lo(l))}return()=>{l.removeEventListener(Um,i),setTimeout(()=>{const b=new CustomEvent(Vm,rC);l.addEventListener(Vm,d),l.dispatchEvent(b),b.defaultPrevented||Lo(m??document.body,{select:!0}),l.removeEventListener(Vm,d),oC.remove(h)},0)}}},[l,i,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,b=document.activeElement;if(x&&b){const y=m.currentTarget,[w,S]=hB(y);w&&S?!m.shiftKey&&b===S?(m.preventDefault(),n&&Lo(w,{select:!0})):m.shiftKey&&b===w&&(m.preventDefault(),n&&Lo(S,{select:!0})):b===y&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...a,ref:f,onKeyDown:g})});dg.displayName=fB;function pB(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Lo(r,{select:t}),document.activeElement!==n)return}function hB(e){const t=yj(e),n=sC(t,e),r=sC(t.reverse(),e);return[n,r]}function yj(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function sC(e,t){for(const n of e)if(!gB(n,{upTo:t}))return n}function gB(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function mB(e){return e instanceof HTMLInputElement&&"select"in e}function Lo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&mB(e)&&t&&e.select()}}var oC=vB();function vB(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=aC(e,t),e.unshift(t)},remove(t){var n;e=aC(e,t),(n=e[0])==null||n.resume()}}}function aC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function yB(e){return e.filter(t=>t.tagName!=="A")}var fn=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},bB=Nh.useId||(()=>{}),xB=0;function os(e){const[t,n]=v.useState(bB());return fn(()=>{n(r=>r??String(xB++))},[e]),t?`radix-${t}`:""}const wB=["top","right","bottom","left"],Ms=Math.min,pr=Math.max,nh=Math.round,Mf=Math.floor,ha=e=>({x:e,y:e}),SB={left:"right",right:"left",bottom:"top",top:"bottom"},CB={start:"end",end:"start"};function qy(e,t,n){return pr(e,Ms(t,n))}function vo(e,t){return typeof e=="function"?e(t):e}function yo(e){return e.split("-")[0]}function yu(e){return e.split("-")[1]}function $x(e){return e==="x"?"y":"x"}function Bx(e){return e==="y"?"height":"width"}function ga(e){return["top","bottom"].includes(yo(e))?"y":"x"}function zx(e){return $x(ga(e))}function EB(e,t,n){n===void 0&&(n=!1);const r=yu(e),s=zx(e),o=Bx(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(a=rh(a)),[a,rh(a)]}function TB(e){const t=rh(e);return[Wy(e),t,Wy(t)]}function Wy(e){return e.replace(/start|end/g,t=>CB[t])}function kB(e,t,n){const r=["left","right"],s=["right","left"],o=["top","bottom"],a=["bottom","top"];switch(e){case"top":case"bottom":return n?t?s:r:t?r:s;case"left":case"right":return t?o:a;default:return[]}}function _B(e,t,n,r){const s=yu(e);let o=kB(yo(e),n==="start",r);return s&&(o=o.map(a=>a+"-"+s),t&&(o=o.concat(o.map(Wy)))),o}function rh(e){return e.replace(/left|right|bottom|top/g,t=>SB[t])}function jB(e){return{top:0,right:0,bottom:0,left:0,...e}}function bj(e){return typeof e!="number"?jB(e):{top:e,right:e,bottom:e,left:e}}function sh(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function iC(e,t,n){let{reference:r,floating:s}=e;const o=ga(t),a=zx(t),l=Bx(a),c=yo(t),i=o==="y",d=r.x+r.width/2-s.width/2,p=r.y+r.height/2-s.height/2,f=r[l]/2-s[l]/2;let h;switch(c){case"top":h={x:d,y:r.y-s.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:p};break;case"left":h={x:r.x-s.width,y:p};break;default:h={x:r.x,y:r.y}}switch(yu(t)){case"start":h[a]-=f*(n&&i?-1:1);break;case"end":h[a]+=f*(n&&i?-1:1);break}return h}const RB=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:a}=n,l=o.filter(Boolean),c=await(a.isRTL==null?void 0:a.isRTL(t));let i=await a.getElementRects({reference:e,floating:t,strategy:s}),{x:d,y:p}=iC(i,r,c),f=r,h={},g=0;for(let m=0;m({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:o,platform:a,elements:l,middlewareData:c}=t,{element:i,padding:d=0}=vo(e,t)||{};if(i==null)return{};const p=bj(d),f={x:n,y:r},h=zx(s),g=Bx(h),m=await a.getDimensions(i),x=h==="y",b=x?"top":"left",y=x?"bottom":"right",w=x?"clientHeight":"clientWidth",S=o.reference[g]+o.reference[h]-f[h]-o.floating[g],E=f[h]-o.reference[h],C=await(a.getOffsetParent==null?void 0:a.getOffsetParent(i));let k=C?C[w]:0;(!k||!await(a.isElement==null?void 0:a.isElement(C)))&&(k=l.floating[w]||o.floating[g]);const T=S/2-E/2,P=k/2-m[g]/2-1,N=Ms(p[b],P),U=Ms(p[y],P),I=N,Z=k-m[g]-U,V=k/2-m[g]/2+T,Q=qy(I,V,Z),ee=!c.arrow&&yu(s)!=null&&V!==Q&&o.reference[g]/2-(VV<=0)){var U,I;const V=(((U=o.flip)==null?void 0:U.index)||0)+1,Q=k[V];if(Q)return{data:{index:V,overflows:N},reset:{placement:Q}};let ee=(I=N.filter(W=>W.overflows[0]<=0).sort((W,F)=>W.overflows[1]-F.overflows[1])[0])==null?void 0:I.placement;if(!ee)switch(h){case"bestFit":{var Z;const W=(Z=N.filter(F=>{if(C){const A=ga(F.placement);return A===y||A==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(A=>A>0).reduce((A,Y)=>A+Y,0)]).sort((F,A)=>F[1]-A[1])[0])==null?void 0:Z[0];W&&(ee=W);break}case"initialPlacement":ee=l;break}if(s!==ee)return{reset:{placement:ee}}}return{}}}};function lC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function uC(e){return wB.some(t=>e[t]>=0)}const OB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...s}=vo(e,t);switch(r){case"referenceHidden":{const o=await ad(t,{...s,elementContext:"reference"}),a=lC(o,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:uC(a)}}}case"escaped":{const o=await ad(t,{...s,altBoundary:!0}),a=lC(o,n.floating);return{data:{escapedOffsets:a,escaped:uC(a)}}}default:return{}}}}};async function NB(e,t){const{placement:n,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=yo(n),l=yu(n),c=ga(n)==="y",i=["left","top"].includes(a)?-1:1,d=o&&c?-1:1,p=vo(t,e);let{mainAxis:f,crossAxis:h,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof g=="number"&&(h=l==="end"?g*-1:g),c?{x:h*d,y:f*i}:{x:f*i,y:h*d}}const IB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:o,placement:a,middlewareData:l}=t,c=await NB(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:s+c.x,y:o+c.y,data:{...c,placement:a}}}}},DB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s}=t,{mainAxis:o=!0,crossAxis:a=!1,limiter:l={fn:x=>{let{x:b,y}=x;return{x:b,y}}},...c}=vo(e,t),i={x:n,y:r},d=await ad(t,c),p=ga(yo(s)),f=$x(p);let h=i[f],g=i[p];if(o){const x=f==="y"?"top":"left",b=f==="y"?"bottom":"right",y=h+d[x],w=h-d[b];h=qy(y,h,w)}if(a){const x=p==="y"?"top":"left",b=p==="y"?"bottom":"right",y=g+d[x],w=g-d[b];g=qy(y,g,w)}const m=l.fn({...t,[f]:h,[p]:g});return{...m,data:{x:m.x-n,y:m.y-r}}}}},AB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:o,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:i=!0}=vo(e,t),d={x:n,y:r},p=ga(s),f=$x(p);let h=d[f],g=d[p];const m=vo(l,t),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const w=f==="y"?"height":"width",S=o.reference[f]-o.floating[w]+x.mainAxis,E=o.reference[f]+o.reference[w]-x.mainAxis;hE&&(h=E)}if(i){var b,y;const w=f==="y"?"width":"height",S=["top","left"].includes(yo(s)),E=o.reference[p]-o.floating[w]+(S&&((b=a.offset)==null?void 0:b[p])||0)+(S?0:x.crossAxis),C=o.reference[p]+o.reference[w]+(S?0:((y=a.offset)==null?void 0:y[p])||0)-(S?x.crossAxis:0);gC&&(g=C)}return{[f]:h,[p]:g}}}},FB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:s,elements:o}=t,{apply:a=()=>{},...l}=vo(e,t),c=await ad(t,l),i=yo(n),d=yu(n),p=ga(n)==="y",{width:f,height:h}=r.floating;let g,m;i==="top"||i==="bottom"?(g=i,m=d===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(m=i,g=d==="end"?"top":"bottom");const x=h-c.top-c.bottom,b=f-c.left-c.right,y=Ms(h-c[g],x),w=Ms(f-c[m],b),S=!t.middlewareData.shift;let E=y,C=w;if(p?C=d||S?Ms(w,b):b:E=d||S?Ms(y,x):x,S&&!d){const T=pr(c.left,0),P=pr(c.right,0),N=pr(c.top,0),U=pr(c.bottom,0);p?C=f-2*(T!==0||P!==0?T+P:pr(c.left,c.right)):E=h-2*(N!==0||U!==0?N+U:pr(c.top,c.bottom))}await a({...t,availableWidth:C,availableHeight:E});const k=await s.getDimensions(o.floating);return f!==k.width||h!==k.height?{reset:{rects:!0}}:{}}}};function bu(e){return xj(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Co(e){var t;return(t=(xj(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function xj(e){return e instanceof Node||e instanceof vr(e).Node}function $s(e){return e instanceof Element||e instanceof vr(e).Element}function Bs(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function cC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Jd(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=cs(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(s)}function LB(e){return["table","td","th"].includes(bu(e))}function fg(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Ux(e){const t=Vx(),n=cs(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function $B(e){let t=ma(e);for(;Bs(t)&&!eu(t);){if(fg(t))return null;if(Ux(t))return t;t=ma(t)}return null}function Vx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eu(e){return["html","body","#document"].includes(bu(e))}function cs(e){return vr(e).getComputedStyle(e)}function pg(e){return $s(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ma(e){if(bu(e)==="html")return e;const t=e.assignedSlot||e.parentNode||cC(e)&&e.host||Co(e);return cC(t)?t.host:t}function wj(e){const t=ma(e);return eu(t)?e.ownerDocument?e.ownerDocument.body:e.body:Bs(t)&&Jd(t)?t:wj(t)}function id(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=wj(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),a=vr(s);return o?t.concat(a,a.visualViewport||[],Jd(s)?s:[],a.frameElement&&n?id(a.frameElement):[]):t.concat(s,id(s,[],n))}function Sj(e){const t=cs(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Bs(e),o=s?e.offsetWidth:n,a=s?e.offsetHeight:r,l=nh(n)!==o||nh(r)!==a;return l&&(n=o,r=a),{width:n,height:r,$:l}}function Hx(e){return $s(e)?e:e.contextElement}function kl(e){const t=Hx(e);if(!Bs(t))return ha(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:o}=Sj(t);let a=(o?nh(n.width):n.width)/r,l=(o?nh(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const BB=ha(0);function Cj(e){const t=vr(e);return!Vx()||!t.visualViewport?BB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function zB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ci(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),o=Hx(e);let a=ha(1);t&&(r?$s(r)&&(a=kl(r)):a=kl(e));const l=zB(o,n,r)?Cj(o):ha(0);let c=(s.left+l.x)/a.x,i=(s.top+l.y)/a.y,d=s.width/a.x,p=s.height/a.y;if(o){const f=vr(o),h=r&&$s(r)?vr(r):r;let g=f,m=g.frameElement;for(;m&&r&&h!==g;){const x=kl(m),b=m.getBoundingClientRect(),y=cs(m),w=b.left+(m.clientLeft+parseFloat(y.paddingLeft))*x.x,S=b.top+(m.clientTop+parseFloat(y.paddingTop))*x.y;c*=x.x,i*=x.y,d*=x.x,p*=x.y,c+=w,i+=S,g=vr(m),m=g.frameElement}}return sh({width:d,height:p,x:c,y:i})}function UB(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const o=s==="fixed",a=Co(r),l=t?fg(t.floating):!1;if(r===a||l&&o)return n;let c={scrollLeft:0,scrollTop:0},i=ha(1);const d=ha(0),p=Bs(r);if((p||!p&&!o)&&((bu(r)!=="body"||Jd(a))&&(c=pg(r)),Bs(r))){const f=Ci(r);i=kl(r),d.x=f.x+r.clientLeft,d.y=f.y+r.clientTop}return{width:n.width*i.x,height:n.height*i.y,x:n.x*i.x-c.scrollLeft*i.x+d.x,y:n.y*i.y-c.scrollTop*i.y+d.y}}function VB(e){return Array.from(e.getClientRects())}function Ej(e){return Ci(Co(e)).left+pg(e).scrollLeft}function HB(e){const t=Co(e),n=pg(e),r=e.ownerDocument.body,s=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Ej(e);const l=-n.scrollTop;return cs(r).direction==="rtl"&&(a+=pr(t.clientWidth,r.clientWidth)-s),{width:s,height:o,x:a,y:l}}function KB(e,t){const n=vr(e),r=Co(e),s=n.visualViewport;let o=r.clientWidth,a=r.clientHeight,l=0,c=0;if(s){o=s.width,a=s.height;const i=Vx();(!i||i&&t==="fixed")&&(l=s.offsetLeft,c=s.offsetTop)}return{width:o,height:a,x:l,y:c}}function qB(e,t){const n=Ci(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,o=Bs(e)?kl(e):ha(1),a=e.clientWidth*o.x,l=e.clientHeight*o.y,c=s*o.x,i=r*o.y;return{width:a,height:l,x:c,y:i}}function dC(e,t,n){let r;if(t==="viewport")r=KB(e,n);else if(t==="document")r=HB(Co(e));else if($s(t))r=qB(t,n);else{const s=Cj(e);r={...t,x:t.x-s.x,y:t.y-s.y}}return sh(r)}function Tj(e,t){const n=ma(e);return n===t||!$s(n)||eu(n)?!1:cs(n).position==="fixed"||Tj(n,t)}function WB(e,t){const n=t.get(e);if(n)return n;let r=id(e,[],!1).filter(l=>$s(l)&&bu(l)!=="body"),s=null;const o=cs(e).position==="fixed";let a=o?ma(e):e;for(;$s(a)&&!eu(a);){const l=cs(a),c=Ux(a);!c&&l.position==="fixed"&&(s=null),(o?!c&&!s:!c&&l.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||Jd(a)&&!c&&Tj(e,a))?r=r.filter(d=>d!==a):s=l,a=ma(a)}return t.set(e,r),r}function GB(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const a=[...n==="clippingAncestors"?fg(t)?[]:WB(t,this._c):[].concat(n),r],l=a[0],c=a.reduce((i,d)=>{const p=dC(t,d,s);return i.top=pr(p.top,i.top),i.right=Ms(p.right,i.right),i.bottom=Ms(p.bottom,i.bottom),i.left=pr(p.left,i.left),i},dC(t,l,s));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function JB(e){const{width:t,height:n}=Sj(e);return{width:t,height:n}}function QB(e,t,n){const r=Bs(t),s=Co(t),o=n==="fixed",a=Ci(e,!0,o,t);let l={scrollLeft:0,scrollTop:0};const c=ha(0);if(r||!r&&!o)if((bu(t)!=="body"||Jd(s))&&(l=pg(t)),r){const p=Ci(t,!0,o,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else s&&(c.x=Ej(s));const i=a.left+l.scrollLeft-c.x,d=a.top+l.scrollTop-c.y;return{x:i,y:d,width:a.width,height:a.height}}function Hm(e){return cs(e).position==="static"}function fC(e,t){return!Bs(e)||cs(e).position==="fixed"?null:t?t(e):e.offsetParent}function kj(e,t){const n=vr(e);if(fg(e))return n;if(!Bs(e)){let s=ma(e);for(;s&&!eu(s);){if($s(s)&&!Hm(s))return s;s=ma(s)}return n}let r=fC(e,t);for(;r&&LB(r)&&Hm(r);)r=fC(r,t);return r&&eu(r)&&Hm(r)&&!Ux(r)?n:r||$B(e)||n}const ZB=async function(e){const t=this.getOffsetParent||kj,n=this.getDimensions,r=await n(e.floating);return{reference:QB(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function YB(e){return cs(e).direction==="rtl"}const XB={convertOffsetParentRelativeRectToViewportRelativeRect:UB,getDocumentElement:Co,getClippingRect:GB,getOffsetParent:kj,getElementRects:ZB,getClientRects:VB,getDimensions:JB,getScale:kl,isElement:$s,isRTL:YB};function ez(e,t){let n=null,r;const s=Co(e);function o(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),o();const{left:i,top:d,width:p,height:f}=e.getBoundingClientRect();if(l||t(),!p||!f)return;const h=Mf(d),g=Mf(s.clientWidth-(i+p)),m=Mf(s.clientHeight-(d+f)),x=Mf(i),y={rootMargin:-h+"px "+-g+"px "+-m+"px "+-x+"px",threshold:pr(0,Ms(1,c))||1};let w=!0;function S(E){const C=E[0].intersectionRatio;if(C!==c){if(!w)return a();C?a(!1,C):r=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(S,{...y,root:s.ownerDocument})}catch{n=new IntersectionObserver(S,y)}n.observe(e)}return a(!0),o}function tz(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,i=Hx(e),d=s||o?[...i?id(i):[],...id(t)]:[];d.forEach(b=>{s&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=i&&l?ez(i,n):null;let f=-1,h=null;a&&(h=new ResizeObserver(b=>{let[y]=b;y&&y.target===i&&h&&(h.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var w;(w=h)==null||w.observe(t)})),n()}),i&&!c&&h.observe(i),h.observe(t));let g,m=c?Ci(e):null;c&&x();function x(){const b=Ci(e);m&&(b.x!==m.x||b.y!==m.y||b.width!==m.width||b.height!==m.height)&&n(),m=b,g=requestAnimationFrame(x)}return n(),()=>{var b;d.forEach(y=>{s&&y.removeEventListener("scroll",n),o&&y.removeEventListener("resize",n)}),p==null||p(),(b=h)==null||b.disconnect(),h=null,c&&cancelAnimationFrame(g)}}const nz=IB,rz=DB,sz=MB,oz=FB,az=OB,pC=PB,iz=AB,lz=(e,t,n)=>{const r=new Map,s={platform:XB,...n},o={...s.platform,_c:r};return RB(e,t,{...s,platform:o})};var hp=typeof document<"u"?v.useLayoutEffect:v.useEffect;function oh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!oh(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!oh(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function _j(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function hC(e,t){const n=_j(e);return Math.round(t*n)/n}function gC(e){const t=v.useRef(e);return hp(()=>{t.current=e}),t}function uz(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:a}={},transform:l=!0,whileElementsMounted:c,open:i}=e,[d,p]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,h]=v.useState(r);oh(f,r)||h(r);const[g,m]=v.useState(null),[x,b]=v.useState(null),y=v.useCallback(W=>{W!==C.current&&(C.current=W,m(W))},[]),w=v.useCallback(W=>{W!==k.current&&(k.current=W,b(W))},[]),S=o||g,E=a||x,C=v.useRef(null),k=v.useRef(null),T=v.useRef(d),P=c!=null,N=gC(c),U=gC(s),I=v.useCallback(()=>{if(!C.current||!k.current)return;const W={placement:t,strategy:n,middleware:f};U.current&&(W.platform=U.current),lz(C.current,k.current,W).then(F=>{const A={...F,isPositioned:!0};Z.current&&!oh(T.current,A)&&(T.current=A,ka.flushSync(()=>{p(A)}))})},[f,t,n,U]);hp(()=>{i===!1&&T.current.isPositioned&&(T.current.isPositioned=!1,p(W=>({...W,isPositioned:!1})))},[i]);const Z=v.useRef(!1);hp(()=>(Z.current=!0,()=>{Z.current=!1}),[]),hp(()=>{if(S&&(C.current=S),E&&(k.current=E),S&&E){if(N.current)return N.current(S,E,I);I()}},[S,E,I,N,P]);const V=v.useMemo(()=>({reference:C,floating:k,setReference:y,setFloating:w}),[y,w]),Q=v.useMemo(()=>({reference:S,floating:E}),[S,E]),ee=v.useMemo(()=>{const W={position:n,left:0,top:0};if(!Q.floating)return W;const F=hC(Q.floating,d.x),A=hC(Q.floating,d.y);return l?{...W,transform:"translate("+F+"px, "+A+"px)",..._j(Q.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:A}},[n,l,Q.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:I,refs:V,elements:Q,floatingStyles:ee}),[d,I,V,Q,ee])}const cz=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?pC({element:r.current,padding:s}).fn(n):{}:r?pC({element:r,padding:s}).fn(n):{}}}},dz=(e,t)=>({...nz(e),options:[e,t]}),fz=(e,t)=>({...rz(e),options:[e,t]}),pz=(e,t)=>({...iz(e),options:[e,t]}),hz=(e,t)=>({...sz(e),options:[e,t]}),gz=(e,t)=>({...oz(e),options:[e,t]}),mz=(e,t)=>({...az(e),options:[e,t]}),vz=(e,t)=>({...cz(e),options:[e,t]});var yz="Arrow",jj=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return u.jsx(Ne.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});jj.displayName=yz;var bz=jj;function Rj(e){const[t,n]=v.useState(void 0);return fn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let a,l;if("borderBoxSize"in o){const c=o.borderBoxSize,i=Array.isArray(c)?c[0]:c;a=i.inlineSize,l=i.blockSize}else a=e.offsetWidth,l=e.offsetHeight;n({width:a,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Kx="Popper",[Pj,hg]=Vr(Kx),[xz,Mj]=Pj(Kx),Oj=e=>{const{__scopePopper:t,children:n}=e,[r,s]=v.useState(null);return u.jsx(xz,{scope:t,anchor:r,onAnchorChange:s,children:n})};Oj.displayName=Kx;var Nj="PopperAnchor",Ij=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=Mj(Nj,n),a=v.useRef(null),l=it(t,a);return v.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||a.current)}),r?null:u.jsx(Ne.div,{...s,ref:l})});Ij.displayName=Nj;var qx="PopperContent",[wz,Sz]=Pj(qx),Dj=v.forwardRef((e,t)=>{var J,Ce,Pe,Le,Me,me;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:i=[],collisionPadding:d=0,sticky:p="partial",hideWhenDetached:f=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,x=Mj(qx,n),[b,y]=v.useState(null),w=it(t,rt=>y(rt)),[S,E]=v.useState(null),C=Rj(S),k=(C==null?void 0:C.width)??0,T=(C==null?void 0:C.height)??0,P=r+(o!=="center"?"-"+o:""),N=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},U=Array.isArray(i)?i:[i],I=U.length>0,Z={padding:N,boundary:U.filter(Ez),altBoundary:I},{refs:V,floatingStyles:Q,placement:ee,isPositioned:W,middlewareData:F}=uz({strategy:"fixed",placement:P,whileElementsMounted:(...rt)=>tz(...rt,{animationFrame:h==="always"}),elements:{reference:x.anchor},middleware:[dz({mainAxis:s+T,alignmentAxis:a}),c&&fz({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?pz():void 0,...Z}),c&&hz({...Z}),gz({...Z,apply:({elements:rt,rects:It,availableWidth:Zt,availableHeight:Wt})=>{const{width:an,height:j}=It.reference,D=rt.floating.style;D.setProperty("--radix-popper-available-width",`${Zt}px`),D.setProperty("--radix-popper-available-height",`${Wt}px`),D.setProperty("--radix-popper-anchor-width",`${an}px`),D.setProperty("--radix-popper-anchor-height",`${j}px`)}}),S&&vz({element:S,padding:l}),Tz({arrowWidth:k,arrowHeight:T}),f&&mz({strategy:"referenceHidden",...Z})]}),[A,Y]=Lj(ee),de=nn(g);fn(()=>{W&&(de==null||de())},[W,de]);const z=(J=F.arrow)==null?void 0:J.x,se=(Ce=F.arrow)==null?void 0:Ce.y,ne=((Pe=F.arrow)==null?void 0:Pe.centerOffset)!==0,[ie,oe]=v.useState();return fn(()=>{b&&oe(window.getComputedStyle(b).zIndex)},[b]),u.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...Q,transform:W?Q.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(Le=F.transformOrigin)==null?void 0:Le.x,(Me=F.transformOrigin)==null?void 0:Me.y].join(" "),...((me=F.hide)==null?void 0:me.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(wz,{scope:n,placedSide:A,onArrowChange:E,arrowX:z,arrowY:se,shouldHideArrow:ne,children:u.jsx(Ne.div,{"data-side":A,"data-align":Y,...m,ref:w,style:{...m.style,animation:W?void 0:"none"}})})})});Dj.displayName=qx;var Aj="PopperArrow",Cz={top:"bottom",right:"left",bottom:"top",left:"right"},Fj=v.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=Sz(Aj,r),a=Cz[o.placedSide];return u.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:u.jsx(bz,{...s,ref:n,style:{...s.style,display:"block"}})})});Fj.displayName=Aj;function Ez(e){return e!==null}var Tz=e=>({name:"transformOrigin",options:e,fn(t){var x,b,y;const{placement:n,rects:r,middlewareData:s}=t,a=((x=s.arrow)==null?void 0:x.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[i,d]=Lj(n),p={start:"0%",center:"50%",end:"100%"}[d],f=(((b=s.arrow)==null?void 0:b.x)??0)+l/2,h=(((y=s.arrow)==null?void 0:y.y)??0)+c/2;let g="",m="";return i==="bottom"?(g=a?p:`${f}px`,m=`${-c}px`):i==="top"?(g=a?p:`${f}px`,m=`${r.floating.height+c}px`):i==="right"?(g=`${-c}px`,m=a?p:`${h}px`):i==="left"&&(g=`${r.floating.width+c}px`,m=a?p:`${h}px`),{data:{x:g,y:m}}}});function Lj(e){const[t,n="center"]=e.split("-");return[t,n]}var $j=Oj,Bj=Ij,zj=Dj,Uj=Fj,kz="Portal",gg=v.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[s,o]=v.useState(!1);fn(()=>o(!0),[]);const a=n||s&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?t_.createPortal(u.jsx(Ne.div,{...r,ref:t}),a):null});gg.displayName=kz;function _z(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var or=e=>{const{present:t,children:n}=e,r=jz(t),s=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),o=it(r.ref,Rz(s));return typeof n=="function"||r.isPresent?v.cloneElement(s,{ref:o}):null};or.displayName="Presence";function jz(e){const[t,n]=v.useState(),r=v.useRef({}),s=v.useRef(e),o=v.useRef("none"),a=e?"mounted":"unmounted",[l,c]=_z(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const i=Of(r.current);o.current=l==="mounted"?i:"none"},[l]),fn(()=>{const i=r.current,d=s.current;if(d!==e){const f=o.current,h=Of(i);e?c("MOUNT"):h==="none"||(i==null?void 0:i.display)==="none"?c("UNMOUNT"):c(d&&f!==h?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,c]),fn(()=>{if(t){const i=p=>{const h=Of(r.current).includes(p.animationName);p.target===t&&h&&ka.flushSync(()=>c("ANIMATION_END"))},d=p=>{p.target===t&&(o.current=Of(r.current))};return t.addEventListener("animationstart",d),t.addEventListener("animationcancel",i),t.addEventListener("animationend",i),()=>{t.removeEventListener("animationstart",d),t.removeEventListener("animationcancel",i),t.removeEventListener("animationend",i)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:v.useCallback(i=>{i&&(r.current=getComputedStyle(i)),n(i)},[])}}function Of(e){return(e==null?void 0:e.animationName)||"none"}function Rz(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Km="rovingFocusGroup.onEntryFocus",Pz={bubbles:!1,cancelable:!0},mg="RovingFocusGroup",[Gy,Vj,Mz]=Fx(mg),[Oz,vg]=Vr(mg,[Mz]),[Nz,Iz]=Oz(mg),Hj=v.forwardRef((e,t)=>u.jsx(Gy.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Gy.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Dz,{...e,ref:t})})}));Hj.displayName=mg;var Dz=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:o,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:i,preventScrollOnEntryFocus:d=!1,...p}=e,f=v.useRef(null),h=it(t,f),g=Gd(o),[m=null,x]=pa({prop:a,defaultProp:l,onChange:c}),[b,y]=v.useState(!1),w=nn(i),S=Vj(n),E=v.useRef(!1),[C,k]=v.useState(0);return v.useEffect(()=>{const T=f.current;if(T)return T.addEventListener(Km,w),()=>T.removeEventListener(Km,w)},[w]),u.jsx(Nz,{scope:n,orientation:r,dir:g,loop:s,currentTabStopId:m,onItemFocus:v.useCallback(T=>x(T),[x]),onItemShiftTab:v.useCallback(()=>y(!0),[]),onFocusableItemAdd:v.useCallback(()=>k(T=>T+1),[]),onFocusableItemRemove:v.useCallback(()=>k(T=>T-1),[]),children:u.jsx(Ne.div,{tabIndex:b||C===0?-1:0,"data-orientation":r,...p,ref:h,style:{outline:"none",...e.style},onMouseDown:Se(e.onMouseDown,()=>{E.current=!0}),onFocus:Se(e.onFocus,T=>{const P=!E.current;if(T.target===T.currentTarget&&P&&!b){const N=new CustomEvent(Km,Pz);if(T.currentTarget.dispatchEvent(N),!N.defaultPrevented){const U=S().filter(ee=>ee.focusable),I=U.find(ee=>ee.active),Z=U.find(ee=>ee.id===m),Q=[I,Z,...U].filter(Boolean).map(ee=>ee.ref.current);Wj(Q,d)}}E.current=!1}),onBlur:Se(e.onBlur,()=>y(!1))})})}),Kj="RovingFocusGroupItem",qj=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:o,...a}=e,l=os(),c=o||l,i=Iz(Kj,n),d=i.currentTabStopId===c,p=Vj(n),{onFocusableItemAdd:f,onFocusableItemRemove:h}=i;return v.useEffect(()=>{if(r)return f(),()=>h()},[r,f,h]),u.jsx(Gy.ItemSlot,{scope:n,id:c,focusable:r,active:s,children:u.jsx(Ne.span,{tabIndex:d?0:-1,"data-orientation":i.orientation,...a,ref:t,onMouseDown:Se(e.onMouseDown,g=>{r?i.onItemFocus(c):g.preventDefault()}),onFocus:Se(e.onFocus,()=>i.onItemFocus(c)),onKeyDown:Se(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){i.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const m=Lz(g,i.orientation,i.dir);if(m!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let b=p().filter(y=>y.focusable).map(y=>y.ref.current);if(m==="last")b.reverse();else if(m==="prev"||m==="next"){m==="prev"&&b.reverse();const y=b.indexOf(g.currentTarget);b=i.loop?$z(b,y+1):b.slice(y+1)}setTimeout(()=>Wj(b))}})})})});qj.displayName=Kj;var Az={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Fz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Lz(e,t,n){const r=Fz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Az[r]}function Wj(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function $z(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Gj=Hj,Jj=qj,Bz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ki=new WeakMap,Nf=new WeakMap,If={},qm=0,Qj=function(e){return e&&(e.host||Qj(e.parentNode))},zz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Qj(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Uz=function(e,t,n,r){var s=zz(t,Array.isArray(e)?e:[e]);If[n]||(If[n]=new WeakMap);var o=If[n],a=[],l=new Set,c=new Set(s),i=function(p){!p||l.has(p)||(l.add(p),i(p.parentNode))};s.forEach(i);var d=function(p){!p||c.has(p)||Array.prototype.forEach.call(p.children,function(f){if(l.has(f))d(f);else try{var h=f.getAttribute(r),g=h!==null&&h!=="false",m=(Ki.get(f)||0)+1,x=(o.get(f)||0)+1;Ki.set(f,m),o.set(f,x),a.push(f),m===1&&g&&Nf.set(f,!0),x===1&&f.setAttribute(n,"true"),g||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return d(t),l.clear(),qm++,function(){a.forEach(function(p){var f=Ki.get(p)-1,h=o.get(p)-1;Ki.set(p,f),o.set(p,h),f||(Nf.has(p)||p.removeAttribute(r),Nf.delete(p)),h||p.removeAttribute(n)}),qm--,qm||(Ki=new WeakMap,Ki=new WeakMap,Nf=new WeakMap,If={})}},Wx=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=Bz(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),Uz(r,s,n,"aria-hidden")):function(){return null}},_s=function(){return _s=Object.assign||function(t){for(var n,r=1,s=arguments.length;r"u")return oU;var t=aU(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},lU=eR(),_l="data-scroll-locked",uU=function(e,t,n,r){var s=e.left,o=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),` - .`.concat(Hz,` { - overflow: hidden `).concat(r,`; - padding-right: `).concat(l,"px ").concat(r,`; - } - body[`).concat(_l,`] { - overflow: hidden `).concat(r,`; - overscroll-behavior: contain; - `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` - padding-left: `.concat(s,`px; - padding-top: `).concat(o,`px; - padding-right: `).concat(a,`px; - margin-left:0; - margin-top:0; - margin-right: `).concat(l,"px ").concat(r,`; - `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` - } - - .`).concat(gp,` { - right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(mp,` { - margin-right: `).concat(l,"px ").concat(r,`; - } - - .`).concat(gp," .").concat(gp,` { - right: 0 `).concat(r,`; - } - - .`).concat(mp," .").concat(mp,` { - margin-right: 0 `).concat(r,`; - } - - body[`).concat(_l,`] { - `).concat(Kz,": ").concat(l,`px; - } -`)},vC=function(){var e=parseInt(document.body.getAttribute(_l)||"0",10);return isFinite(e)?e:0},cU=function(){v.useEffect(function(){return document.body.setAttribute(_l,(vC()+1).toString()),function(){var e=vC()-1;e<=0?document.body.removeAttribute(_l):document.body.setAttribute(_l,e.toString())}},[])},dU=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;cU();var o=v.useMemo(function(){return iU(s)},[s]);return v.createElement(lU,{styles:uU(o,!t,s,n?"":"!important")})},Jy=!1;if(typeof window<"u")try{var Df=Object.defineProperty({},"passive",{get:function(){return Jy=!0,!0}});window.addEventListener("test",Df,Df),window.removeEventListener("test",Df,Df)}catch{Jy=!1}var qi=Jy?{passive:!1}:!1,fU=function(e){return e.tagName==="TEXTAREA"},tR=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!fU(e)&&n[t]==="visible")},pU=function(e){return tR(e,"overflowY")},hU=function(e){return tR(e,"overflowX")},yC=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=nR(e,r);if(s){var o=rR(e,r),a=o[1],l=o[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gU=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},mU=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},nR=function(e,t){return e==="v"?pU(t):hU(t)},rR=function(e,t){return e==="v"?gU(t):mU(t)},vU=function(e,t){return e==="h"&&t==="rtl"?-1:1},yU=function(e,t,n,r,s){var o=vU(e,window.getComputedStyle(t).direction),a=o*r,l=n.target,c=t.contains(l),i=!1,d=a>0,p=0,f=0;do{var h=rR(e,l),g=h[0],m=h[1],x=h[2],b=m-x-o*g;(g||b)&&nR(e,l)&&(p+=b,f+=g),l instanceof ShadowRoot?l=l.host:l=l.parentNode}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(d&&(Math.abs(p)<1||!s)||!d&&(Math.abs(f)<1||!s))&&(i=!0),i},Af=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},bC=function(e){return[e.deltaX,e.deltaY]},xC=function(e){return e&&"current"in e?e.current:e},bU=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xU=function(e){return` - .block-interactivity-`.concat(e,` {pointer-events: none;} - .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},wU=0,Wi=[];function SU(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),s=v.useState(wU++)[0],o=v.useState(eR)[0],a=v.useRef(e);v.useEffect(function(){a.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var m=Vz([e.lockRef.current],(e.shards||[]).map(xC),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var l=v.useCallback(function(m,x){if("touches"in m&&m.touches.length===2)return!a.current.allowPinchZoom;var b=Af(m),y=n.current,w="deltaX"in m?m.deltaX:y[0]-b[0],S="deltaY"in m?m.deltaY:y[1]-b[1],E,C=m.target,k=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in m&&k==="h"&&C.type==="range")return!1;var T=yC(k,C);if(!T)return!0;if(T?E=k:(E=k==="v"?"h":"v",T=yC(k,C)),!T)return!1;if(!r.current&&"changedTouches"in m&&(w||S)&&(r.current=E),!E)return!0;var P=r.current||E;return yU(P,x,m,P==="h"?w:S,!0)},[]),c=v.useCallback(function(m){var x=m;if(!(!Wi.length||Wi[Wi.length-1]!==o)){var b="deltaY"in x?bC(x):Af(x),y=t.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&bU(E.delta,b)})[0];if(y&&y.should){x.cancelable&&x.preventDefault();return}if(!y){var w=(a.current.shards||[]).map(xC).filter(Boolean).filter(function(E){return E.contains(x.target)}),S=w.length>0?l(x,w[0]):!a.current.noIsolation;S&&x.cancelable&&x.preventDefault()}}},[]),i=v.useCallback(function(m,x,b,y){var w={name:m,delta:x,target:b,should:y,shadowParent:CU(b)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),d=v.useCallback(function(m){n.current=Af(m),r.current=void 0},[]),p=v.useCallback(function(m){i(m.type,bC(m),m.target,l(m,e.lockRef.current))},[]),f=v.useCallback(function(m){i(m.type,Af(m),m.target,l(m,e.lockRef.current))},[]);v.useEffect(function(){return Wi.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",c,qi),document.addEventListener("touchmove",c,qi),document.addEventListener("touchstart",d,qi),function(){Wi=Wi.filter(function(m){return m!==o}),document.removeEventListener("wheel",c,qi),document.removeEventListener("touchmove",c,qi),document.removeEventListener("touchstart",d,qi)}},[]);var h=e.removeScrollBar,g=e.inert;return v.createElement(v.Fragment,null,g?v.createElement(o,{styles:xU(s)}):null,h?v.createElement(dU,{gapMode:e.gapMode}):null)}function CU(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const EU=Yz(Xj,SU);var bg=v.forwardRef(function(e,t){return v.createElement(yg,_s({},e,{ref:t,sideCar:EU}))});bg.classNames=yg.classNames;var Qy=["Enter"," "],TU=["ArrowDown","PageUp","Home"],sR=["ArrowUp","PageDown","End"],kU=[...TU,...sR],_U={ltr:[...Qy,"ArrowRight"],rtl:[...Qy,"ArrowLeft"]},jU={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Qd="Menu",[ld,RU,PU]=Fx(Qd),[Ii,oR]=Vr(Qd,[PU,hg,vg]),xg=hg(),aR=vg(),[MU,Di]=Ii(Qd),[OU,Zd]=Ii(Qd),iR=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:s,onOpenChange:o,modal:a=!0}=e,l=xg(t),[c,i]=v.useState(null),d=v.useRef(!1),p=nn(o),f=Gd(s);return v.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),u.jsx($j,{...l,children:u.jsx(MU,{scope:t,open:n,onOpenChange:p,content:c,onContentChange:i,children:u.jsx(OU,{scope:t,onClose:v.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:d,dir:f,modal:a,children:r})})})};iR.displayName=Qd;var NU="MenuAnchor",Gx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Bj,{...s,...r,ref:t})});Gx.displayName=NU;var Jx="MenuPortal",[IU,lR]=Ii(Jx,{forceMount:void 0}),uR=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,o=Di(Jx,t);return u.jsx(IU,{scope:t,forceMount:n,children:u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:r})})})};uR.displayName=Jx;var $r="MenuContent",[DU,Qx]=Ii($r),cR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:a.modal?u.jsx(AU,{...s,ref:t}):u.jsx(FU,{...s,ref:t})})})})}),AU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu),r=v.useRef(null),s=it(t,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(Zx,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),FU=v.forwardRef((e,t)=>{const n=Di($r,e.__scopeMenu);return u.jsx(Zx,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Zx=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,disableOutsideScroll:g,...m}=e,x=Di($r,n),b=Zd($r,n),y=xg(n),w=aR(n),S=RU(n),[E,C]=v.useState(null),k=v.useRef(null),T=it(t,k,x.onContentChange),P=v.useRef(0),N=v.useRef(""),U=v.useRef(0),I=v.useRef(null),Z=v.useRef("right"),V=v.useRef(0),Q=g?bg:v.Fragment,ee=g?{as:mo,allowPinchZoom:!0}:void 0,W=A=>{var J,Ce;const Y=N.current+A,de=S().filter(Pe=>!Pe.disabled),z=document.activeElement,se=(J=de.find(Pe=>Pe.ref.current===z))==null?void 0:J.textValue,ne=de.map(Pe=>Pe.textValue),ie=JU(ne,Y,se),oe=(Ce=de.find(Pe=>Pe.textValue===ie))==null?void 0:Ce.ref.current;(function Pe(Le){N.current=Le,window.clearTimeout(P.current),Le!==""&&(P.current=window.setTimeout(()=>Pe(""),1e3))})(Y),oe&&setTimeout(()=>oe.focus())};v.useEffect(()=>()=>window.clearTimeout(P.current),[]),Lx();const F=v.useCallback(A=>{var de,z;return Z.current===((de=I.current)==null?void 0:de.side)&&ZU(A,(z=I.current)==null?void 0:z.area)},[]);return u.jsx(DU,{scope:n,searchRef:N,onItemEnter:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),onItemLeave:v.useCallback(A=>{var Y;F(A)||((Y=k.current)==null||Y.focus(),C(null))},[F]),onTriggerLeave:v.useCallback(A=>{F(A)&&A.preventDefault()},[F]),pointerGraceTimerRef:U,onPointerGraceIntentChange:v.useCallback(A=>{I.current=A},[]),children:u.jsx(Q,{...ee,children:u.jsx(dg,{asChild:!0,trapped:s,onMountAutoFocus:Se(o,A=>{var Y;A.preventDefault(),(Y=k.current)==null||Y.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:i,onPointerDownOutside:d,onFocusOutside:p,onInteractOutside:f,onDismiss:h,children:u.jsx(Gj,{asChild:!0,...w,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:C,onEntryFocus:Se(c,A=>{b.isUsingKeyboardRef.current||A.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(zj,{role:"menu","aria-orientation":"vertical","data-state":kR(x.open),"data-radix-menu-content":"",dir:b.dir,...y,...m,ref:T,style:{outline:"none",...m.style},onKeyDown:Se(m.onKeyDown,A=>{const de=A.target.closest("[data-radix-menu-content]")===A.currentTarget,z=A.ctrlKey||A.altKey||A.metaKey,se=A.key.length===1;de&&(A.key==="Tab"&&A.preventDefault(),!z&&se&&W(A.key));const ne=k.current;if(A.target!==ne||!kU.includes(A.key))return;A.preventDefault();const oe=S().filter(J=>!J.disabled).map(J=>J.ref.current);sR.includes(A.key)&&oe.reverse(),WU(oe)}),onBlur:Se(e.onBlur,A=>{A.currentTarget.contains(A.target)||(window.clearTimeout(P.current),N.current="")}),onPointerMove:Se(e.onPointerMove,ud(A=>{const Y=A.target,de=V.current!==A.clientX;if(A.currentTarget.contains(Y)&&de){const z=A.clientX>V.current?"right":"left";Z.current=z,V.current=A.clientX}}))})})})})})})});cR.displayName=$r;var LU="MenuGroup",Yx=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{role:"group",...r,ref:t})});Yx.displayName=LU;var $U="MenuLabel",dR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{...r,ref:t})});dR.displayName=$U;var ah="MenuItem",wC="menu.itemSelect",wg=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,o=v.useRef(null),a=Zd(ah,e.__scopeMenu),l=Qx(ah,e.__scopeMenu),c=it(t,o),i=v.useRef(!1),d=()=>{const p=o.current;if(!n&&p){const f=new CustomEvent(wC,{bubbles:!0,cancelable:!0});p.addEventListener(wC,h=>r==null?void 0:r(h),{once:!0}),gj(p,f),f.defaultPrevented?i.current=!1:a.onClose()}};return u.jsx(fR,{...s,ref:c,disabled:n,onClick:Se(e.onClick,d),onPointerDown:p=>{var f;(f=e.onPointerDown)==null||f.call(e,p),i.current=!0},onPointerUp:Se(e.onPointerUp,p=>{var f;i.current||(f=p.currentTarget)==null||f.click()}),onKeyDown:Se(e.onKeyDown,p=>{const f=l.searchRef.current!=="";n||f&&p.key===" "||Qy.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});wg.displayName=ah;var fR=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...o}=e,a=Qx(ah,n),l=aR(n),c=v.useRef(null),i=it(t,c),[d,p]=v.useState(!1),[f,h]=v.useState("");return v.useEffect(()=>{const g=c.current;g&&h((g.textContent??"").trim())},[o.children]),u.jsx(ld.ItemSlot,{scope:n,disabled:r,textValue:s??f,children:u.jsx(Jj,{asChild:!0,...l,focusable:!r,children:u.jsx(Ne.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:i,onPointerMove:Se(e.onPointerMove,ud(g=>{r?a.onItemLeave(g):(a.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Se(e.onPointerLeave,ud(g=>a.onItemLeave(g))),onFocus:Se(e.onFocus,()=>p(!0)),onBlur:Se(e.onBlur,()=>p(!1))})})})}),BU="MenuCheckboxItem",pR=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return u.jsx(yR,{scope:e.__scopeMenu,checked:n,children:u.jsx(wg,{role:"menuitemcheckbox","aria-checked":ih(n)?"mixed":n,...s,ref:t,"data-state":ew(n),onSelect:Se(s.onSelect,()=>r==null?void 0:r(ih(n)?!0:!n),{checkForDefaultPrevented:!1})})})});pR.displayName=BU;var hR="MenuRadioGroup",[zU,UU]=Ii(hR,{value:void 0,onValueChange:()=>{}}),gR=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,o=nn(r);return u.jsx(zU,{scope:e.__scopeMenu,value:n,onValueChange:o,children:u.jsx(Yx,{...s,ref:t})})});gR.displayName=hR;var mR="MenuRadioItem",vR=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=UU(mR,e.__scopeMenu),o=n===s.value;return u.jsx(yR,{scope:e.__scopeMenu,checked:o,children:u.jsx(wg,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":ew(o),onSelect:Se(r.onSelect,()=>{var a;return(a=s.onValueChange)==null?void 0:a.call(s,n)},{checkForDefaultPrevented:!1})})})});vR.displayName=mR;var Xx="MenuItemIndicator",[yR,VU]=Ii(Xx,{checked:!1}),bR=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,o=VU(Xx,n);return u.jsx(or,{present:r||ih(o.checked)||o.checked===!0,children:u.jsx(Ne.span,{...s,ref:t,"data-state":ew(o.checked)})})});bR.displayName=Xx;var HU="MenuSeparator",xR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ne.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});xR.displayName=HU;var KU="MenuArrow",wR=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=xg(n);return u.jsx(Uj,{...s,...r,ref:t})});wR.displayName=KU;var qU="MenuSub",[qse,SR]=Ii(qU),dc="MenuSubTrigger",CR=v.forwardRef((e,t)=>{const n=Di(dc,e.__scopeMenu),r=Zd(dc,e.__scopeMenu),s=SR(dc,e.__scopeMenu),o=Qx(dc,e.__scopeMenu),a=v.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=o,i={__scopeMenu:e.__scopeMenu},d=v.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return v.useEffect(()=>d,[d]),v.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),c(null)}},[l,c]),u.jsx(Gx,{asChild:!0,...i,children:u.jsx(fR,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":kR(n.open),...e,ref:ag(t,s.onTriggerChange),onClick:p=>{var f;(f=e.onClick)==null||f.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Se(e.onPointerMove,ud(p=>{o.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(o.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:Se(e.onPointerLeave,ud(p=>{var h,g;d();const f=(h=n.content)==null?void 0:h.getBoundingClientRect();if(f){const m=(g=n.content)==null?void 0:g.dataset.side,x=m==="right",b=x?-5:5,y=f[x?"left":"right"],w=f[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:p.clientX+b,y:p.clientY},{x:y,y:f.top},{x:w,y:f.top},{x:w,y:f.bottom},{x:y,y:f.bottom}],side:m}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(p),p.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Se(e.onKeyDown,p=>{var h;const f=o.searchRef.current!=="";e.disabled||f&&p.key===" "||_U[r.dir].includes(p.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),p.preventDefault())})})})});CR.displayName=dc;var ER="MenuSubContent",TR=v.forwardRef((e,t)=>{const n=lR($r,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Di($r,e.__scopeMenu),a=Zd($r,e.__scopeMenu),l=SR(ER,e.__scopeMenu),c=v.useRef(null),i=it(t,c);return u.jsx(ld.Provider,{scope:e.__scopeMenu,children:u.jsx(or,{present:r||o.open,children:u.jsx(ld.Slot,{scope:e.__scopeMenu,children:u.jsx(Zx,{id:l.contentId,"aria-labelledby":l.triggerId,...s,ref:i,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var p;a.isUsingKeyboardRef.current&&((p=c.current)==null||p.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:Se(e.onFocusOutside,d=>{d.target!==l.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Se(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:Se(e.onKeyDown,d=>{var h;const p=d.currentTarget.contains(d.target),f=jU[a.dir].includes(d.key);p&&f&&(o.onOpenChange(!1),(h=l.trigger)==null||h.focus(),d.preventDefault())})})})})})});TR.displayName=ER;function kR(e){return e?"open":"closed"}function ih(e){return e==="indeterminate"}function ew(e){return ih(e)?"indeterminate":e?"checked":"unchecked"}function WU(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function GU(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function JU(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=GU(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const c=a.find(i=>i.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function QU(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,a=t.length-1;or!=d>r&&n<(i-l)*(r-c)/(d-c)+l&&(s=!s)}return s}function ZU(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return QU(n,t)}function ud(e){return t=>t.pointerType==="mouse"?e(t):void 0}var YU=iR,XU=Gx,e5=uR,t5=cR,n5=Yx,r5=dR,s5=wg,o5=pR,a5=gR,i5=vR,l5=bR,u5=xR,c5=wR,d5=CR,f5=TR,tw="DropdownMenu",[p5,Wse]=Vr(tw,[oR]),Gn=oR(),[h5,_R]=p5(tw),nw=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:s,defaultOpen:o,onOpenChange:a,modal:l=!0}=e,c=Gn(t),i=v.useRef(null),[d=!1,p]=pa({prop:s,defaultProp:o,onChange:a});return u.jsx(h5,{scope:t,triggerId:os(),triggerRef:i,contentId:os(),open:d,onOpenChange:p,onOpenToggle:v.useCallback(()=>p(f=>!f),[p]),modal:l,children:u.jsx(YU,{...c,open:d,onOpenChange:p,dir:r,modal:l,children:n})})};nw.displayName=tw;var jR="DropdownMenuTrigger",rw=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,o=_R(jR,n),a=Gn(n);return u.jsx(XU,{asChild:!0,...a,children:u.jsx(Ne.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:ag(t,o.triggerRef),onPointerDown:Se(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(o.onOpenToggle(),o.open||l.preventDefault())}),onKeyDown:Se(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&o.onOpenToggle(),l.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});rw.displayName=jR;var g5="DropdownMenuPortal",RR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Gn(t);return u.jsx(e5,{...r,...n})};RR.displayName=g5;var PR="DropdownMenuContent",MR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=_R(PR,n),o=Gn(n),a=v.useRef(!1);return u.jsx(t5,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:t,onCloseAutoFocus:Se(e.onCloseAutoFocus,l=>{var c;a.current||(c=s.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:Se(e.onInteractOutside,l=>{const c=l.detail.originalEvent,i=c.button===0&&c.ctrlKey===!0,d=c.button===2||i;(!s.modal||d)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});MR.displayName=PR;var m5="DropdownMenuGroup",v5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(n5,{...s,...r,ref:t})});v5.displayName=m5;var y5="DropdownMenuLabel",OR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(r5,{...s,...r,ref:t})});OR.displayName=y5;var b5="DropdownMenuItem",NR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(s5,{...s,...r,ref:t})});NR.displayName=b5;var x5="DropdownMenuCheckboxItem",IR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(o5,{...s,...r,ref:t})});IR.displayName=x5;var w5="DropdownMenuRadioGroup",S5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(a5,{...s,...r,ref:t})});S5.displayName=w5;var C5="DropdownMenuRadioItem",DR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(i5,{...s,...r,ref:t})});DR.displayName=C5;var E5="DropdownMenuItemIndicator",AR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(l5,{...s,...r,ref:t})});AR.displayName=E5;var T5="DropdownMenuSeparator",FR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(u5,{...s,...r,ref:t})});FR.displayName=T5;var k5="DropdownMenuArrow",_5=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(c5,{...s,...r,ref:t})});_5.displayName=k5;var j5="DropdownMenuSubTrigger",LR=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(d5,{...s,...r,ref:t})});LR.displayName=j5;var R5="DropdownMenuSubContent",$R=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=Gn(n);return u.jsx(f5,{...s,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});$R.displayName=R5;var P5=nw,M5=rw,O5=RR,BR=MR,zR=OR,UR=NR,VR=IR,HR=DR,KR=AR,Ra=FR,qR=LR,WR=$R;const Eo=P5,To=M5,N5=v.forwardRef(({className:e,inset:t,children:n,...r},s)=>u.jsxs(qR,{ref:s,className:ge("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,u.jsx(R3,{className:"ml-auto h-4 w-4"})]}));N5.displayName=qR.displayName;const I5=v.forwardRef(({className:e,...t},n)=>u.jsx(WR,{ref:n,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));I5.displayName=WR.displayName;const ps=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(O5,{children:u.jsx(BR,{ref:r,sideOffset:t,className:ge("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));ps.displayName=BR.displayName;const ft=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(UR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));ft.displayName=UR.displayName;const GR=v.forwardRef(({className:e,children:t,checked:n,...r},s)=>u.jsxs(VR,{ref:s,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(cj,{className:"h-4 w-4"})})}),t]}));GR.displayName=VR.displayName;const D5=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HR,{ref:r,className:ge("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(KR,{children:u.jsx(N3,{className:"h-2 w-2 fill-current"})})}),t]}));D5.displayName=HR.displayName;const Ai=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(zR,{ref:r,className:ge("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Ai.displayName=zR.displayName;const Pa=v.forwardRef(({className:e,...t},n)=>u.jsx(Ra,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));Pa.displayName=Ra.displayName;function A5(){const{t:e,i18n:t}=ze(),n=r=>{t.changeLanguage(r),localStorage.setItem("i18nextLng",r),window.location.reload()};return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"outline",size:"icon",children:[u.jsx(z3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{className:t.language==="pt-BR"?"font-bold":"",onClick:()=>n("pt-BR"),children:e("header.language.portuguese")}),u.jsx(ft,{className:t.language==="en-US"?"font-bold":"",onClick:()=>n("en-US"),children:e("header.language.english")}),u.jsx(ft,{className:t.language==="es-ES"?"font-bold":"",onClick:()=>n("es-ES"),children:e("header.language.spanish")}),u.jsx(ft,{className:t.language==="fr-FR"?"font-bold":"",onClick:()=>n("fr-FR"),children:e("header.language.french")})]})]})}function F5(){const{t:e}=ze(),{setTheme:t}=R_();return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"outline",size:"icon",children:[u.jsx(G3,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),u.jsx(K3,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),u.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(ft,{onClick:()=>t("light"),children:e("header.theme.light")}),u.jsx(ft,{onClick:()=>t("dark"),children:e("header.theme.dark")}),u.jsx(ft,{onClick:()=>t("system"),children:e("header.theme.system")})]})]})}var sw="Avatar",[L5,Gse]=Vr(sw),[$5,JR]=L5(sw),QR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[s,o]=v.useState("idle");return u.jsx($5,{scope:n,imageLoadingStatus:s,onImageLoadingStatusChange:o,children:u.jsx(Ne.span,{...r,ref:t})})});QR.displayName=sw;var ZR="AvatarImage",YR=v.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:s=()=>{},...o}=e,a=JR(ZR,n),l=B5(r),c=nn(i=>{s(i),a.onImageLoadingStatusChange(i)});return fn(()=>{l!=="idle"&&c(l)},[l,c]),l==="loaded"?u.jsx(Ne.img,{...o,ref:t,src:r}):null});YR.displayName=ZR;var XR="AvatarFallback",eP=v.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...s}=e,o=JR(XR,n),[a,l]=v.useState(r===void 0);return v.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>l(!0),r);return()=>window.clearTimeout(c)}},[r]),a&&o.imageLoadingStatus!=="loaded"?u.jsx(Ne.span,{...s,ref:t}):null});eP.displayName=XR;function B5(e){const[t,n]=v.useState("idle");return fn(()=>{if(!e){n("error");return}let r=!0;const s=new window.Image,o=a=>()=>{r&&n(a)};return n("loading"),s.onload=o("loaded"),s.onerror=o("error"),s.src=e,()=>{r=!1}},[e]),t}var tP=QR,nP=YR,rP=eP;const Sg=v.forwardRef(({className:e,...t},n)=>u.jsx(tP,{ref:n,className:ge("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Sg.displayName=tP.displayName;const Cg=v.forwardRef(({className:e,...t},n)=>u.jsx(nP,{ref:n,className:ge("aspect-square h-full w-full",e),...t}));Cg.displayName=nP.displayName;const z5=v.forwardRef(({className:e,...t},n)=>u.jsx(rP,{ref:n,className:ge("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));z5.displayName=rP.displayName;var ow="Dialog",[sP,Jse]=Vr(ow),[U5,hs]=sP(ow),oP=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:a=!0}=e,l=v.useRef(null),c=v.useRef(null),[i=!1,d]=pa({prop:r,defaultProp:s,onChange:o});return u.jsx(U5,{scope:t,triggerRef:l,contentRef:c,contentId:os(),titleId:os(),descriptionId:os(),open:i,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(p=>!p),[d]),modal:a,children:n})};oP.displayName=ow;var aP="DialogTrigger",iP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(aP,n),o=it(t,s.triggerRef);return u.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":lw(s.open),...r,ref:o,onClick:Se(e.onClick,s.onOpenToggle)})});iP.displayName=aP;var aw="DialogPortal",[V5,lP]=sP(aw,{forceMount:void 0}),uP=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,o=hs(aw,t);return u.jsx(V5,{scope:t,forceMount:n,children:v.Children.map(r,a=>u.jsx(or,{present:n||o.open,children:u.jsx(gg,{asChild:!0,container:s,children:a})}))})};uP.displayName=aw;var lh="DialogOverlay",cP=v.forwardRef((e,t)=>{const n=lP(lh,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(lh,e.__scopeDialog);return o.modal?u.jsx(or,{present:r||o.open,children:u.jsx(H5,{...s,ref:t})}):null});cP.displayName=lh;var H5=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(lh,n);return u.jsx(bg,{as:mo,allowPinchZoom:!0,shards:[s.contentRef],children:u.jsx(Ne.div,{"data-state":lw(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Ei="DialogContent",dP=v.forwardRef((e,t)=>{const n=lP(Ei,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=hs(Ei,e.__scopeDialog);return u.jsx(or,{present:r||o.open,children:o.modal?u.jsx(K5,{...s,ref:t}):u.jsx(q5,{...s,ref:t})})});dP.displayName=Ei;var K5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(null),s=it(t,n.contentRef,r);return v.useEffect(()=>{const o=r.current;if(o)return Wx(o)},[]),u.jsx(fP,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Se(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Se(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&o.preventDefault()}),onFocusOutside:Se(e.onFocusOutside,o=>o.preventDefault())})}),q5=v.forwardRef((e,t)=>{const n=hs(Ei,e.__scopeDialog),r=v.useRef(!1),s=v.useRef(!1);return u.jsx(fP,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,o),o.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var c,i;(c=e.onInteractOutside)==null||c.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=o.target;((i=n.triggerRef.current)==null?void 0:i.contains(a))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),fP=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...a}=e,l=hs(Ei,n),c=v.useRef(null),i=it(t,c);return Lx(),u.jsxs(u.Fragment,{children:[u.jsx(dg,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:u.jsx(cg,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":lw(l.open),...a,ref:i,onDismiss:()=>l.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(W5,{titleId:l.titleId}),u.jsx(J5,{contentRef:c,descriptionId:l.descriptionId})]})]})}),iw="DialogTitle",pP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(iw,n);return u.jsx(Ne.h2,{id:s.titleId,...r,ref:t})});pP.displayName=iw;var hP="DialogDescription",gP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(hP,n);return u.jsx(Ne.p,{id:s.descriptionId,...r,ref:t})});gP.displayName=hP;var mP="DialogClose",vP=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=hs(mP,n);return u.jsx(Ne.button,{type:"button",...r,ref:t,onClick:Se(e.onClick,()=>s.onOpenChange(!1))})});vP.displayName=mP;function lw(e){return e?"open":"closed"}var yP="DialogTitleWarning",[Qse,bP]=X3(yP,{contentName:Ei,titleName:iw,docsSlug:"dialog"}),W5=({titleId:e})=>{const t=bP(yP),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return v.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},G5="DialogDescriptionWarning",J5=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${bP(G5).contentName}}.`;return v.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Q5=oP,Z5=iP,Y5=uP,xP=cP,wP=dP,SP=pP,CP=gP,EP=vP;const Tt=Q5,Nt=Z5,X5=Y5,TP=EP,kP=v.forwardRef(({className:e,...t},n)=>u.jsx(xP,{ref:n,className:ge("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));kP.displayName=xP.displayName;const xt=v.forwardRef(({className:e,children:t,closeBtn:n=!0,...r},s)=>u.jsx(X5,{children:u.jsx(kP,{className:"fixed inset-0 grid place-items-center overflow-y-auto",children:u.jsxs(wP,{ref:s,className:ge("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:m-4 sm:rounded-lg md:w-full",e),...r,children:[t,n&&u.jsxs(EP,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(Q3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})})}));xt.displayName=wP.displayName;const wt=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});wt.displayName="DialogHeader";const rn=({className:e,...t})=>u.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});rn.displayName="DialogFooter";const Ut=v.forwardRef(({className:e,...t},n)=>u.jsx(SP,{ref:n,className:ge("text-lg font-semibold leading-none tracking-tight",e),...t}));Ut.displayName=SP.displayName;const Fi=v.forwardRef(({className:e,...t},n)=>u.jsx(CP,{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));Fi.displayName=CP.displayName;function _P({instanceId:e}){const[t,n]=v.useState(!1),r=An(),s=()=>{M_(),r("/manager/login")},o=()=>{r("/manager/")},{data:a}=hj({instanceId:e});return u.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[u.jsxs(nd,{to:"/manager",onClick:o,className:"flex h-8 items-center gap-4",children:[u.jsx("img",{src:"/assets/images/evolution-logo.png",alt:"Logo",className:"h-full"}),u.jsx("span",{children:"Evolution Manager"})]}),u.jsxs("div",{className:"flex items-center gap-4",children:[e&&u.jsx(Sg,{className:"h-8 w-8",children:u.jsx(Cg,{src:(a==null?void 0:a.profilePicUrl)||"/assets/images/evolution-logo.png",alt:a==null?void 0:a.name})}),u.jsx(A5,{}),u.jsx(F5,{}),u.jsx(q,{onClick:()=>n(!0),variant:"destructive",size:"icon",children:u.jsx(D3,{size:"18"})})]}),t&&u.jsx(Tt,{onOpenChange:n,open:t,children:u.jsxs(xt,{children:[u.jsx(TP,{}),u.jsx(wt,{children:"Deseja realmente sair?"}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(q,{onClick:()=>n(!1),size:"sm",variant:"outline",children:"Cancelar"}),u.jsx(q,{onClick:s,variant:"destructive",children:"Sair"})]})})]})})]})}const jP=v.createContext(null),nt=()=>{const e=v.useContext(jP);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},eV=({children:e})=>{const t=So(),[n,r]=v.useState(null),{data:s,refetch:o}=hj({instanceId:n});return v.useEffect(()=>{t.instanceId?r(t.instanceId):r(null)},[t]),u.jsx(jP.Provider,{value:{instance:s??null,reloadInstance:async()=>{await o()}},children:e})};var uw="Collapsible",[tV,Zse]=Vr(uw),[nV,cw]=tV(uw),RP=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:a,...l}=e,[c=!1,i]=pa({prop:r,defaultProp:s,onChange:a});return u.jsx(nV,{scope:n,disabled:o,contentId:os(),open:c,onOpenToggle:v.useCallback(()=>i(d=>!d),[i]),children:u.jsx(Ne.div,{"data-state":fw(c),"data-disabled":o?"":void 0,...l,ref:t})})});RP.displayName=uw;var PP="CollapsibleTrigger",MP=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=cw(PP,n);return u.jsx(Ne.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":fw(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Se(e.onClick,s.onOpenToggle)})});MP.displayName=PP;var dw="CollapsibleContent",OP=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=cw(dw,e.__scopeCollapsible);return u.jsx(or,{present:n||s.open,children:({present:o})=>u.jsx(rV,{...r,ref:t,present:o})})});OP.displayName=dw;var rV=v.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,a=cw(dw,n),[l,c]=v.useState(r),i=v.useRef(null),d=it(t,i),p=v.useRef(0),f=p.current,h=v.useRef(0),g=h.current,m=a.open||l,x=v.useRef(m),b=v.useRef();return v.useEffect(()=>{const y=requestAnimationFrame(()=>x.current=!1);return()=>cancelAnimationFrame(y)},[]),fn(()=>{const y=i.current;if(y){b.current=b.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const w=y.getBoundingClientRect();p.current=w.height,h.current=w.width,x.current||(y.style.transitionDuration=b.current.transitionDuration,y.style.animationName=b.current.animationName),c(r)}},[a.open,r]),u.jsx(Ne.div,{"data-state":fw(a.open),"data-disabled":a.disabled?"":void 0,id:a.contentId,hidden:!m,...o,ref:d,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:m&&s})});function fw(e){return e?"open":"closed"}var sV=RP;const oV=sV,aV=MP,iV=OP;function lV(){const{t:e}=ze(),t=v.useMemo(()=>[{id:"dashboard",title:e("sidebar.dashboard"),icon:U3,path:"dashboard"},{navLabel:!0,title:e("sidebar.configurations"),icon:Oi,children:[{id:"settings",title:e("sidebar.settings"),path:"settings"},{id:"proxy",title:e("sidebar.proxy"),path:"proxy"}]},{title:e("sidebar.events"),icon:B3,children:[{id:"webhook",title:e("sidebar.webhook"),path:"webhook"},{id:"websocket",title:e("sidebar.websocket"),path:"websocket"},{id:"rabbitmq",title:e("sidebar.rabbitmq"),path:"rabbitmq"},{id:"sqs",title:e("sidebar.sqs"),path:"sqs"}]},{title:e("sidebar.integrations"),icon:pj,children:[{id:"evolutionBot",title:e("sidebar.evolutionBot"),path:"evolutionBot"},{id:"chatwoot",title:e("sidebar.chatwoot"),path:"chatwoot"},{id:"typebot",title:e("sidebar.typebot"),path:"typebot"},{id:"openai",title:e("sidebar.openai"),path:"openai"},{id:"dify",title:e("sidebar.dify"),path:"dify"},{id:"flowise",title:e("sidebar.flowise"),path:"flowise"}]},{id:"documentation",title:e("sidebar.documentation"),icon:L3,link:"https://doc.evolution-api.com",divider:!0},{id:"postman",title:e("sidebar.postman"),icon:O3,link:"https://evolution-api.com/postman"},{id:"discord",title:e("sidebar.discord"),icon:ug,link:"https://evolution-api.com/discord"},{id:"support-premium",title:e("sidebar.supportPremium"),icon:V3,link:"https://evolution-api.com/suporte-pro"}],[e]),n=An(),{pathname:r}=pu(),{instance:s}=nt(),o=l=>{!l||!s||(l.path&&n(`/manager/instance/${s.id}/${l.path}`),l.link&&window.open(l.link,"_blank"))},a=v.useMemo(()=>t.map(l=>{var c;return{...l,children:"children"in l?(c=l.children)==null?void 0:c.map(i=>({...i,isActive:"path"in i?r.includes(i.path):!1})):void 0,isActive:"path"in l&&l.path?r.includes(l.path):!1}}).map(l=>{var c;return{...l,isActive:l.isActive||"children"in l&&((c=l.children)==null?void 0:c.some(i=>i.isActive))}}),[t,r]);return u.jsx("ul",{className:"flex h-full w-full flex-col gap-2 border-r border-border px-2",children:a.map(l=>u.jsx("li",{className:"divider"in l?"mt-auto":void 0,children:l.children?u.jsxs(oV,{defaultOpen:l.isActive,children:[u.jsx(aV,{asChild:!0,children:u.jsxs(q,{className:ge("flex w-full items-center justify-start gap-2"),variant:l.isActive?"secondary":"link",children:[l.icon&&u.jsx(l.icon,{size:"15"}),u.jsx("span",{children:l.title}),u.jsx(lg,{size:"15",className:"ml-auto"})]})}),u.jsx(iV,{children:u.jsx("ul",{className:"my-4 ml-6 flex flex-col gap-2 text-sm",children:l.children.map(c=>u.jsx("li",{children:u.jsx("button",{onClick:()=>o(c),className:ge(c.isActive?"text-foreground":"text-muted-foreground"),children:u.jsx("span",{className:"nav-label",children:c.title})})},c.id))})})]}):u.jsxs(q,{className:ge("relative flex w-full items-center justify-start gap-2",l.isActive&&"pointer-events-none"),variant:l.isActive?"secondary":"link",children:["link"in l&&u.jsx("a",{href:l.link,target:"_blank",rel:"noreferrer",className:"absolute inset-0 h-full w-full"}),"path"in l&&u.jsx(nd,{to:`/manager/instance/${s==null?void 0:s.id}/${l.path}`,className:"absolute inset-0 h-full w-full"}),l.icon&&u.jsx(l.icon,{size:"15"}),u.jsx("span",{children:l.title})]})},l.title))})}function Zy(e,[t,n]){return Math.min(n,Math.max(t,e))}function uV(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var pw="ScrollArea",[NP,Yse]=Vr(pw),[cV,Hr]=NP(pw),IP=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...a}=e,[l,c]=v.useState(null),[i,d]=v.useState(null),[p,f]=v.useState(null),[h,g]=v.useState(null),[m,x]=v.useState(null),[b,y]=v.useState(0),[w,S]=v.useState(0),[E,C]=v.useState(!1),[k,T]=v.useState(!1),P=it(t,U=>c(U)),N=Gd(s);return u.jsx(cV,{scope:n,type:r,dir:N,scrollHideDelay:o,scrollArea:l,viewport:i,onViewportChange:d,content:p,onContentChange:f,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:E,onScrollbarXEnabledChange:C,scrollbarY:m,onScrollbarYChange:x,scrollbarYEnabled:k,onScrollbarYEnabledChange:T,onCornerWidthChange:y,onCornerHeightChange:S,children:u.jsx(Ne.div,{dir:N,...a,ref:P,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":w+"px",...e.style}})})});IP.displayName=pw;var DP="ScrollAreaViewport",AP=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,a=Hr(DP,n),l=v.useRef(null),c=it(t,l,a.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),u.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...o,ref:c,style:{overflowX:a.scrollbarXEnabled?"scroll":"hidden",overflowY:a.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:a.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});AP.displayName=DP;var Hs="ScrollAreaScrollbar",hw=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:a}=s,l=e.orientation==="horizontal";return v.useEffect(()=>(l?o(!0):a(!0),()=>{l?o(!1):a(!1)}),[l,o,a]),s.type==="hover"?u.jsx(dV,{...r,ref:t,forceMount:n}):s.type==="scroll"?u.jsx(fV,{...r,ref:t,forceMount:n}):s.type==="auto"?u.jsx(FP,{...r,ref:t,forceMount:n}):s.type==="always"?u.jsx(gw,{...r,ref:t}):null});hw.displayName=Hs;var dV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),[o,a]=v.useState(!1);return v.useEffect(()=>{const l=s.scrollArea;let c=0;if(l){const i=()=>{window.clearTimeout(c),a(!0)},d=()=>{c=window.setTimeout(()=>a(!1),s.scrollHideDelay)};return l.addEventListener("pointerenter",i),l.addEventListener("pointerleave",d),()=>{window.clearTimeout(c),l.removeEventListener("pointerenter",i),l.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),u.jsx(or,{present:n||o,children:u.jsx(FP,{"data-state":o?"visible":"hidden",...r,ref:t})})}),fV=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=e.orientation==="horizontal",a=Tg(()=>c("SCROLL_END"),100),[l,c]=uV("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(l==="idle"){const i=window.setTimeout(()=>c("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(i)}},[l,s.scrollHideDelay,c]),v.useEffect(()=>{const i=s.viewport,d=o?"scrollLeft":"scrollTop";if(i){let p=i[d];const f=()=>{const h=i[d];p!==h&&(c("SCROLL"),a()),p=h};return i.addEventListener("scroll",f),()=>i.removeEventListener("scroll",f)}},[s.viewport,o,c,a]),u.jsx(or,{present:n||l!=="hidden",children:u.jsx(gw,{"data-state":l==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Se(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Se(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),FP=v.forwardRef((e,t)=>{const n=Hr(Hs,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,a]=v.useState(!1),l=e.orientation==="horizontal",c=Tg(()=>{if(n.viewport){const i=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,s=Hr(Hs,e.__scopeScrollArea),o=v.useRef(null),a=v.useRef(0),[l,c]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),i=UP(l.viewport,l.content),d={...r,sizes:l,onSizesChange:c,hasThumb:i>0&&i<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>a.current=0,onThumbPointerDown:f=>a.current=f};function p(f,h){return yV(f,a.current,l,h)}return n==="horizontal"?u.jsx(pV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollLeft,h=SC(f,l,s.dir);o.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollLeft=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollLeft=p(f,s.dir))}}):n==="vertical"?u.jsx(hV,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const f=s.viewport.scrollTop,h=SC(f,l);o.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:f=>{s.viewport&&(s.viewport.scrollTop=f)},onDragScroll:f=>{s.viewport&&(s.viewport.scrollTop=p(f))}}):null}),pV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,l]=v.useState(),c=v.useRef(null),i=it(t,c,o.onScrollbarXChange);return v.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),u.jsx($P,{"data-orientation":"horizontal",...s,ref:i,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(f),HP(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:ch(a.paddingLeft),paddingEnd:ch(a.paddingRight)}})}})}),hV=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Hr(Hs,e.__scopeScrollArea),[a,l]=v.useState(),c=v.useRef(null),i=it(t,c,o.onScrollbarYChange);return v.useEffect(()=>{c.current&&l(getComputedStyle(c.current))},[c]),u.jsx($P,{"data-orientation":"vertical",...s,ref:i,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Eg(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,p)=>{if(o.viewport){const f=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(f),HP(f,p)&&d.preventDefault()}},onResize:()=>{c.current&&o.viewport&&a&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:ch(a.paddingTop),paddingEnd:ch(a.paddingBottom)}})}})}),[gV,LP]=NP(Hs),$P=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:a,onThumbPointerDown:l,onThumbPositionChange:c,onDragScroll:i,onWheelScroll:d,onResize:p,...f}=e,h=Hr(Hs,n),[g,m]=v.useState(null),x=it(t,P=>m(P)),b=v.useRef(null),y=v.useRef(""),w=h.viewport,S=r.content-r.viewport,E=nn(d),C=nn(c),k=Tg(p,10);function T(P){if(b.current){const N=P.clientX-b.current.left,U=P.clientY-b.current.top;i({x:N,y:U})}}return v.useEffect(()=>{const P=N=>{const U=N.target;(g==null?void 0:g.contains(U))&&E(N,S)};return document.addEventListener("wheel",P,{passive:!1}),()=>document.removeEventListener("wheel",P,{passive:!1})},[w,g,S,E]),v.useEffect(C,[r,C]),tu(g,k),tu(h.content,k),u.jsx(gV,{scope:n,scrollbar:g,hasThumb:s,onThumbChange:nn(o),onThumbPointerUp:nn(a),onThumbPositionChange:C,onThumbPointerDown:nn(l),children:u.jsx(Ne.div,{...f,ref:x,style:{position:"absolute",...f.style},onPointerDown:Se(e.onPointerDown,P=>{P.button===0&&(P.target.setPointerCapture(P.pointerId),b.current=g.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),T(P))}),onPointerMove:Se(e.onPointerMove,T),onPointerUp:Se(e.onPointerUp,P=>{const N=P.target;N.hasPointerCapture(P.pointerId)&&N.releasePointerCapture(P.pointerId),document.body.style.webkitUserSelect=y.current,h.viewport&&(h.viewport.style.scrollBehavior=""),b.current=null})})})}),uh="ScrollAreaThumb",BP=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=LP(uh,e.__scopeScrollArea);return u.jsx(or,{present:n||s.hasThumb,children:u.jsx(mV,{ref:t,...r})})}),mV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Hr(uh,n),a=LP(uh,n),{onThumbPositionChange:l}=a,c=it(t,p=>a.onThumbChange(p)),i=v.useRef(),d=Tg(()=>{i.current&&(i.current(),i.current=void 0)},100);return v.useEffect(()=>{const p=o.viewport;if(p){const f=()=>{if(d(),!i.current){const h=bV(p,l);i.current=h,l()}};return l(),p.addEventListener("scroll",f),()=>p.removeEventListener("scroll",f)}},[o.viewport,d,l]),u.jsx(Ne.div,{"data-state":a.hasThumb?"visible":"hidden",...s,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Se(e.onPointerDownCapture,p=>{const h=p.target.getBoundingClientRect(),g=p.clientX-h.left,m=p.clientY-h.top;a.onThumbPointerDown({x:g,y:m})}),onPointerUp:Se(e.onPointerUp,a.onThumbPointerUp)})});BP.displayName=uh;var mw="ScrollAreaCorner",zP=v.forwardRef((e,t)=>{const n=Hr(mw,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(vV,{...e,ref:t}):null});zP.displayName=mw;var vV=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Hr(mw,n),[o,a]=v.useState(0),[l,c]=v.useState(0),i=!!(o&&l);return tu(s.scrollbarX,()=>{var p;const d=((p=s.scrollbarX)==null?void 0:p.offsetHeight)||0;s.onCornerHeightChange(d),c(d)}),tu(s.scrollbarY,()=>{var p;const d=((p=s.scrollbarY)==null?void 0:p.offsetWidth)||0;s.onCornerWidthChange(d),a(d)}),i?u.jsx(Ne.div,{...r,ref:t,style:{width:o,height:l,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function ch(e){return e?parseInt(e,10):0}function UP(e,t){const n=e/t;return isNaN(n)?0:n}function Eg(e){const t=UP(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function yV(e,t,n,r="ltr"){const s=Eg(n),o=s/2,a=t||o,l=s-a,c=n.scrollbar.paddingStart+a,i=n.scrollbar.size-n.scrollbar.paddingEnd-l,d=n.content-n.viewport,p=r==="ltr"?[0,d]:[d*-1,0];return VP([c,i],p)(e)}function SC(e,t,n="ltr"){const r=Eg(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,a=t.content-t.viewport,l=o-r,c=n==="ltr"?[0,a]:[a*-1,0],i=Zy(e,c);return VP([0,a],[0,l])(i)}function VP(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function HP(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},a=n.left!==o.left,l=n.top!==o.top;(a||l)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function Tg(e,t){const n=nn(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function tu(e,t){const n=nn(t);fn(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var KP=IP,xV=AP,wV=zP;const Yy=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(KP,{ref:r,className:ge("relative overflow-hidden",e),...n,children:[u.jsx(xV,{className:"h-full w-full rounded-[inherit] [&>div[style]]:!block [&>div[style]]:h-full",children:t}),u.jsx(qP,{}),u.jsx(wV,{})]}));Yy.displayName=KP.displayName;const qP=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(hw,{ref:r,orientation:t,className:ge("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(BP,{className:ge("relative rounded-full bg-border",t==="vertical"&&"flex-1")})}));qP.displayName=hw.displayName;function Xt({children:e}){const{instanceId:t}=So();return u.jsx(eV,{children:u.jsxs("div",{className:"flex h-screen flex-col",children:[u.jsx(_P,{instanceId:t}),u.jsxs("div",{className:"flex min-h-[calc(100vh_-_56px)] flex-1 flex-col md:flex-row",children:[u.jsx(Yy,{className:"mr-2 py-6 md:w-64",children:u.jsx("div",{className:"flex h-full",children:u.jsx(lV,{})})}),u.jsx(Yy,{className:"w-full",children:u.jsxs("div",{className:"flex h-full flex-col",children:[u.jsx("div",{className:"my-6 flex flex-1 flex-col gap-2 pl-2 pr-4",children:e}),u.jsx(Ax,{})]})})]})]})})}function SV({children:e}){return u.jsxs("div",{className:"flex h-full min-h-screen flex-col",children:[u.jsx(_P,{}),u.jsx("main",{className:"flex-1",children:e}),u.jsx(Ax,{})]})}const CV=ig("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",warning:"border-transparent bg-amber-600 text-amber-100 hover:bg-amber-600/80"}},defaultVariants:{variant:"default"}});function Ff({className:e,variant:t,...n}){return u.jsx("div",{className:ge(CV({variant:t}),e),...n})}function WP({status:e}){const{t}=ze();return e?e==="open"?u.jsx(Ff,{children:t("status.open")}):e==="connecting"?u.jsx(Ff,{variant:"warning",children:t("status.connecting")}):e==="close"||e==="closed"?u.jsx(Ff,{variant:"destructive",children:t("status.closed")}):u.jsx(Ff,{variant:"secondary",children:e}):null}const EV=e=>{navigator.clipboard.writeText(e),X.success("Copiado para a área de transferência")};function GP({token:e,className:t}){const[n,r]=v.useState(!1);return u.jsxs("div",{className:ge("flex items-center gap-3 truncate rounded-sm bg-primary/20 px-2 py-1",t),children:[u.jsx("pre",{className:"block truncate text-xs",children:n?e:e==null?void 0:e.replace(/\w/g,"*")}),u.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{EV(e)},children:u.jsx(I3,{size:"15"})}),u.jsx(q,{variant:"ghost",size:"icon",onClick:()=>{r(s=>!s)},children:n?u.jsx(A3,{size:"15"}):u.jsx(F3,{size:"15"})})]})}const Ja=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Ja.displayName="Card";const Qa=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex flex-col space-y-1.5 p-6",e),...t}));Qa.displayName="CardHeader";const jc=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ge("text-2xl font-semibold leading-none tracking-tight",e),...t}));jc.displayName="CardTitle";const JP=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));JP.displayName="CardDescription";const Za=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("p-6 pt-0",e),...t}));Za.displayName="CardContent";const kg=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("flex items-center p-6 pt-0",e),...t}));kg.displayName="CardFooter";const QP="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",K=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:ge(QP,e),ref:r,...n}));K.displayName="Input";const TV=["instance","fetchInstances"],kV=async()=>(await he.get("/instance/fetchInstances")).data,_V=e=>lt({...e,queryKey:TV,queryFn:()=>kV()});function Ye(e,t){const n=Ab(),r=WD({mutationFn:e});return(s,o)=>r.mutateAsync(s,{onSuccess:async(a,l,c)=>{var i;t!=null&&t.invalidateKeys&&await Promise.all(t.invalidateKeys.map(d=>n.invalidateQueries({queryKey:d}))),(i=o==null?void 0:o.onSuccess)==null||i.call(o,a,l,c)},onError(a,l,c){var i;(i=o==null?void 0:o.onError)==null||i.call(o,a,l,c)},onSettled(a,l,c,i){var d;(d=o==null?void 0:o.onSettled)==null||d.call(o,a,l,c,i)}})}const jV=async e=>(await he.post("/instance/create",e)).data,RV=async e=>(await he.post(`/instance/restart/${e}`)).data,PV=async e=>(await he.delete(`/instance/logout/${e}`)).data,MV=async e=>(await he.delete(`/instance/delete/${e}`)).data,OV=async({instanceName:e,token:t,number:n})=>(await he.get(`/instance/connect/${e}`,{headers:{apikey:t},params:{number:n}})).data,NV=async({instanceName:e,token:t,data:n})=>(await he.post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;function _g(){const e=Ye(OV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),t=Ye(NV,{invalidateKeys:[["instance","fetchSettings"]]}),n=Ye(MV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),r=Ye(PV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),s=Ye(RV,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),o=Ye(jV,{invalidateKeys:[["instance","fetchInstances"]]});return{connect:e,updateSettings:t,deleteInstance:n,logout:r,restart:s,createInstance:o}}var Yd=e=>e.type==="checkbox",ml=e=>e instanceof Date,Un=e=>e==null;const ZP=e=>typeof e=="object";var pn=e=>!Un(e)&&!Array.isArray(e)&&ZP(e)&&!ml(e),YP=e=>pn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,IV=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,XP=(e,t)=>e.has(IV(t)),DV=e=>{const t=e.constructor&&e.constructor.prototype;return pn(t)&&t.hasOwnProperty("isPrototypeOf")},vw=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Jn(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(vw&&(e instanceof Blob||e instanceof FileList))&&(n||pn(e)))if(t=n?[]:{},!n&&!DV(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Jn(e[r]));else return e;return t}var jg=e=>Array.isArray(e)?e.filter(Boolean):[],qt=e=>e===void 0,ce=(e,t,n)=>{if(!t||!pn(e))return n;const r=jg(t.split(/[,[\].]+?/)).reduce((s,o)=>Un(s)?s:s[o],e);return qt(r)||r===e?qt(e[t])?n:e[t]:r},js=e=>typeof e=="boolean",yw=e=>/^\w*$/.test(e),eM=e=>jg(e.replace(/["|']|\]/g,"").split(/\.|\[/)),ht=(e,t,n)=>{let r=-1;const s=yw(t)?[t]:eM(t),o=s.length,a=o-1;for(;++rTe.useContext(tM),Tr=e=>{const{children:t,...n}=e;return Te.createElement(tM.Provider,{value:n},t)};var nM=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(s,o,{get:()=>{const a=o;return t._proxyFormState[a]!==Yr.all&&(t._proxyFormState[a]=!r||Yr.all),n&&(n[a]=!0),e[a]}});return s},ur=e=>pn(e)&&!Object.keys(e).length,rM=(e,t,n,r)=>{n(e);const{name:s,...o}=e;return ur(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(a=>t[a]===(!r||Yr.all))},Rc=e=>Array.isArray(e)?e:[e],sM=(e,t,n)=>!e||!t||e===t||Rc(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function bw(e){const t=Te.useRef(e);t.current=e,Te.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function AV(e){const t=Rg(),{control:n=t.control,disabled:r,name:s,exact:o}=e||{},[a,l]=Te.useState(n._formState),c=Te.useRef(!0),i=Te.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),d=Te.useRef(s);return d.current=s,bw({disabled:r,next:p=>c.current&&sM(d.current,p.name,o)&&rM(p,i.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Te.useEffect(()=>(c.current=!0,i.current.isValid&&n._updateValid(!0),()=>{c.current=!1}),[n]),nM(a,n,i.current,!1)}var Os=e=>typeof e=="string",oM=(e,t,n,r,s)=>Os(e)?(r&&t.watch.add(e),ce(n,e,s)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),ce(n,o))):(r&&(t.watchAll=!0),n);function FV(e){const t=Rg(),{control:n=t.control,name:r,defaultValue:s,disabled:o,exact:a}=e||{},l=Te.useRef(r);l.current=r,bw({disabled:o,subject:n._subjects.values,next:d=>{sM(l.current,d.name,a)&&i(Jn(oM(l.current,n._names,d.values||n._formValues,!1,s)))}});const[c,i]=Te.useState(n._getWatch(r,s));return Te.useEffect(()=>n._removeUnmounted()),c}function LV(e){const t=Rg(),{name:n,disabled:r,control:s=t.control,shouldUnregister:o}=e,a=XP(s._names.array,n),l=FV({control:s,name:n,defaultValue:ce(s._formValues,n,ce(s._defaultValues,n,e.defaultValue)),exact:!0}),c=AV({control:s,name:n}),i=Te.useRef(s.register(n,{...e.rules,value:l,...js(e.disabled)?{disabled:e.disabled}:{}}));return Te.useEffect(()=>{const d=s._options.shouldUnregister||o,p=(f,h)=>{const g=ce(s._fields,f);g&&g._f&&(g._f.mount=h)};if(p(n,!0),d){const f=Jn(ce(s._options.defaultValues,n));ht(s._defaultValues,n,f),qt(ce(s._formValues,n))&&ht(s._formValues,n,f)}return()=>{(a?d&&!s._state.action:d)?s.unregister(n):p(n,!1)}},[n,s,a,o]),Te.useEffect(()=>{ce(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:ce(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:l,...js(r)||c.disabled?{disabled:c.disabled||r}:{},onChange:Te.useCallback(d=>i.current.onChange({target:{value:YP(d),name:n},type:dh.CHANGE}),[n]),onBlur:Te.useCallback(()=>i.current.onBlur({target:{value:ce(s._formValues,n),name:n},type:dh.BLUR}),[n,s]),ref:d=>{const p=ce(s._fields,n);p&&d&&(p._f.ref={focus:()=>d.focus(),select:()=>d.select(),setCustomValidity:f=>d.setCustomValidity(f),reportValidity:()=>d.reportValidity()})}},formState:c,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ce(c.errors,n)},isDirty:{enumerable:!0,get:()=>!!ce(c.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ce(c.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!ce(c.validatingFields,n)},error:{enumerable:!0,get:()=>ce(c.errors,n)}})}}const $V=e=>e.render(LV(e));var aM=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},CC=e=>({isOnSubmit:!e||e===Yr.onSubmit,isOnBlur:e===Yr.onBlur,isOnChange:e===Yr.onChange,isOnAll:e===Yr.all,isOnTouch:e===Yr.onTouched}),EC=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Pc=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const o=ce(e,s);if(o){const{_f:a,...l}=o;if(a){if(a.refs&&a.refs[0]&&t(a.refs[0],s)&&!r)break;if(a.ref&&t(a.ref,a.name)&&!r)break;Pc(l,t)}else pn(l)&&Pc(l,t)}}};var BV=(e,t,n)=>{const r=Rc(ce(e,n));return ht(r,"root",t[n]),ht(e,n,r),e},xw=e=>e.type==="file",ta=e=>typeof e=="function",fh=e=>{if(!vw)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},vp=e=>Os(e),ww=e=>e.type==="radio",ph=e=>e instanceof RegExp;const TC={value:!1,isValid:!1},kC={value:!0,isValid:!0};var iM=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!qt(e[0].attributes.value)?qt(e[0].value)||e[0].value===""?kC:{value:e[0].value,isValid:!0}:kC:TC}return TC};const _C={isValid:!1,value:null};var lM=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,_C):_C;function jC(e,t,n="validate"){if(vp(e)||Array.isArray(e)&&e.every(vp)||js(e)&&!e)return{type:n,message:vp(e)?e:"",ref:t}}var Gi=e=>pn(e)&&!ph(e)?e:{value:e,message:""},RC=async(e,t,n,r,s)=>{const{ref:o,refs:a,required:l,maxLength:c,minLength:i,min:d,max:p,pattern:f,validate:h,name:g,valueAsNumber:m,mount:x,disabled:b}=e._f,y=ce(t,g);if(!x||b)return{};const w=a?a[0]:o,S=I=>{r&&w.reportValidity&&(w.setCustomValidity(js(I)?"":I||""),w.reportValidity())},E={},C=ww(o),k=Yd(o),T=C||k,P=(m||xw(o))&&qt(o.value)&&qt(y)||fh(o)&&o.value===""||y===""||Array.isArray(y)&&!y.length,N=aM.bind(null,g,n,E),U=(I,Z,V,Q=Ws.maxLength,ee=Ws.minLength)=>{const W=I?Z:V;E[g]={type:I?Q:ee,message:W,ref:o,...N(I?Q:ee,W)}};if(s?!Array.isArray(y)||!y.length:l&&(!T&&(P||Un(y))||js(y)&&!y||k&&!iM(a).isValid||C&&!lM(a).isValid)){const{value:I,message:Z}=vp(l)?{value:!!l,message:l}:Gi(l);if(I&&(E[g]={type:Ws.required,message:Z,ref:w,...N(Ws.required,Z)},!n))return S(Z),E}if(!P&&(!Un(d)||!Un(p))){let I,Z;const V=Gi(p),Q=Gi(d);if(!Un(y)&&!isNaN(y)){const ee=o.valueAsNumber||y&&+y;Un(V.value)||(I=ee>V.value),Un(Q.value)||(Z=eenew Date(new Date().toDateString()+" "+Y),F=o.type=="time",A=o.type=="week";Os(V.value)&&y&&(I=F?W(y)>W(V.value):A?y>V.value:ee>new Date(V.value)),Os(Q.value)&&y&&(Z=F?W(y)+I.value,Q=!Un(Z.value)&&y.length<+Z.value;if((V||Q)&&(U(V,I.message,Z.message),!n))return S(E[g].message),E}if(f&&!P&&Os(y)){const{value:I,message:Z}=Gi(f);if(ph(I)&&!y.match(I)&&(E[g]={type:Ws.pattern,message:Z,ref:o,...N(Ws.pattern,Z)},!n))return S(Z),E}if(h){if(ta(h)){const I=await h(y,t),Z=jC(I,w);if(Z&&(E[g]={...Z,...N(Ws.validate,Z.message)},!n))return S(Z.message),E}else if(pn(h)){let I={};for(const Z in h){if(!ur(I)&&!n)break;const V=jC(await h[Z](y,t),w,Z);V&&(I={...V,...N(Z,V.message)},S(V.message),n&&(E[g]=I))}if(!ur(I)&&(E[g]={ref:w,...I},!n))return E}}return S(!0),E};function zV(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:s=>{for(const o of e)o.next&&o.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(o=>o!==s)}}),unsubscribe:()=>{e=[]}}},hh=e=>Un(e)||!ZP(e);function Ya(e,t){if(hh(e)||hh(t))return e===t;if(ml(e)&&ml(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const o=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const a=t[s];if(ml(o)&&ml(a)||pn(o)&&pn(a)||Array.isArray(o)&&Array.isArray(a)?!Ya(o,a):o!==a)return!1}}return!0}var uM=e=>e.type==="select-multiple",VV=e=>ww(e)||Yd(e),Zm=e=>fh(e)&&e.isConnected,cM=e=>{for(const t in e)if(ta(e[t]))return!0;return!1};function gh(e,t={}){const n=Array.isArray(e);if(pn(e)||n)for(const r in e)Array.isArray(e[r])||pn(e[r])&&!cM(e[r])?(t[r]=Array.isArray(e[r])?[]:{},gh(e[r],t[r])):Un(e[r])||(t[r]=!0);return t}function dM(e,t,n){const r=Array.isArray(e);if(pn(e)||r)for(const s in e)Array.isArray(e[s])||pn(e[s])&&!cM(e[s])?qt(t)||hh(n[s])?n[s]=Array.isArray(e[s])?gh(e[s],[]):{...gh(e[s])}:dM(e[s],Un(t)?{}:t[s],n[s]):n[s]=!Ya(e[s],t[s]);return n}var Lf=(e,t)=>dM(e,t,gh(t)),fM=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>qt(e)?e:t?e===""?NaN:e&&+e:n&&Os(e)?new Date(e):r?r(e):e;function Ym(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return xw(t)?t.files:ww(t)?lM(e.refs).value:uM(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?iM(e.refs).value:fM(qt(t.value)?e.ref.value:t.value,e)}var HV=(e,t,n,r)=>{const s={};for(const o of e){const a=ce(t,o);a&&ht(s,o,a._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},Zu=e=>qt(e)?e:ph(e)?e.source:pn(e)?ph(e.value)?e.value.source:e.value:e,KV=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function PC(e,t,n){const r=ce(e,n);if(r||yw(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const o=s.join("."),a=ce(t,o),l=ce(e,o);if(a&&!Array.isArray(a)&&n!==o)return{name:n};if(l&&l.type)return{name:o,error:l};s.pop()}return{name:n}}var qV=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,WV=(e,t)=>!jg(ce(e,t)).length&&ln(e,t);const GV={mode:Yr.onSubmit,reValidateMode:Yr.onChange,shouldFocusError:!0};function JV(e={}){let t={...GV,...e},n={submitCount:0,isDirty:!1,isLoading:ta(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=pn(t.defaultValues)||pn(t.values)?Jn(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Jn(s),a={action:!1,mount:!1,watch:!1},l={mount:new Set,unMount:new Set,array:new Set,watch:new Set},c,i=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},p={values:Qm(),array:Qm(),state:Qm()},f=CC(t.mode),h=CC(t.reValidateMode),g=t.criteriaMode===Yr.all,m=j=>D=>{clearTimeout(i),i=setTimeout(j,D)},x=async j=>{if(d.isValid||j){const D=t.resolver?ur((await T()).errors):await N(r,!0);D!==n.isValid&&p.state.next({isValid:D})}},b=(j,D)=>{(d.isValidating||d.validatingFields)&&((j||Array.from(l.mount)).forEach(B=>{B&&(D?ht(n.validatingFields,B,D):ln(n.validatingFields,B))}),p.state.next({validatingFields:n.validatingFields,isValidating:!ur(n.validatingFields)}))},y=(j,D=[],B,pe,le=!0,ae=!0)=>{if(pe&&B){if(a.action=!0,ae&&Array.isArray(ce(r,j))){const Ee=B(ce(r,j),pe.argA,pe.argB);le&&ht(r,j,Ee)}if(ae&&Array.isArray(ce(n.errors,j))){const Ee=B(ce(n.errors,j),pe.argA,pe.argB);le&&ht(n.errors,j,Ee),WV(n.errors,j)}if(d.touchedFields&&ae&&Array.isArray(ce(n.touchedFields,j))){const Ee=B(ce(n.touchedFields,j),pe.argA,pe.argB);le&&ht(n.touchedFields,j,Ee)}d.dirtyFields&&(n.dirtyFields=Lf(s,o)),p.state.next({name:j,isDirty:I(j,D),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else ht(o,j,D)},w=(j,D)=>{ht(n.errors,j,D),p.state.next({errors:n.errors})},S=j=>{n.errors=j,p.state.next({errors:n.errors,isValid:!1})},E=(j,D,B,pe)=>{const le=ce(r,j);if(le){const ae=ce(o,j,qt(B)?ce(s,j):B);qt(ae)||pe&&pe.defaultChecked||D?ht(o,j,D?ae:Ym(le._f)):Q(j,ae),a.mount&&x()}},C=(j,D,B,pe,le)=>{let ae=!1,Ee=!1;const et={name:j},kt=!!(ce(r,j)&&ce(r,j)._f&&ce(r,j)._f.disabled);if(!B||pe){d.isDirty&&(Ee=n.isDirty,n.isDirty=et.isDirty=I(),ae=Ee!==et.isDirty);const hn=kt||Ya(ce(s,j),D);Ee=!!(!kt&&ce(n.dirtyFields,j)),hn||kt?ln(n.dirtyFields,j):ht(n.dirtyFields,j,!0),et.dirtyFields=n.dirtyFields,ae=ae||d.dirtyFields&&Ee!==!hn}if(B){const hn=ce(n.touchedFields,j);hn||(ht(n.touchedFields,j,B),et.touchedFields=n.touchedFields,ae=ae||d.touchedFields&&hn!==B)}return ae&&le&&p.state.next(et),ae?et:{}},k=(j,D,B,pe)=>{const le=ce(n.errors,j),ae=d.isValid&&js(D)&&n.isValid!==D;if(e.delayError&&B?(c=m(()=>w(j,B)),c(e.delayError)):(clearTimeout(i),c=null,B?ht(n.errors,j,B):ln(n.errors,j)),(B?!Ya(le,B):le)||!ur(pe)||ae){const Ee={...pe,...ae&&js(D)?{isValid:D}:{},errors:n.errors,name:j};n={...n,...Ee},p.state.next(Ee)}},T=async j=>{b(j,!0);const D=await t.resolver(o,t.context,HV(j||l.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return b(j),D},P=async j=>{const{errors:D}=await T(j);if(j)for(const B of j){const pe=ce(D,B);pe?ht(n.errors,B,pe):ln(n.errors,B)}else n.errors=D;return D},N=async(j,D,B={valid:!0})=>{for(const pe in j){const le=j[pe];if(le){const{_f:ae,...Ee}=le;if(ae){const et=l.array.has(ae.name);b([pe],!0);const kt=await RC(le,o,g,t.shouldUseNativeValidation&&!D,et);if(b([pe]),kt[ae.name]&&(B.valid=!1,D))break;!D&&(ce(kt,ae.name)?et?BV(n.errors,kt,ae.name):ht(n.errors,ae.name,kt[ae.name]):ln(n.errors,ae.name))}Ee&&await N(Ee,D,B)}}return B.valid},U=()=>{for(const j of l.unMount){const D=ce(r,j);D&&(D._f.refs?D._f.refs.every(B=>!Zm(B)):!Zm(D._f.ref))&&oe(j)}l.unMount=new Set},I=(j,D)=>(j&&D&&ht(o,j,D),!Ya(de(),s)),Z=(j,D,B)=>oM(j,l,{...a.mount?o:qt(D)?s:Os(j)?{[j]:D}:D},B,D),V=j=>jg(ce(a.mount?o:s,j,e.shouldUnregister?ce(s,j,[]):[])),Q=(j,D,B={})=>{const pe=ce(r,j);let le=D;if(pe){const ae=pe._f;ae&&(!ae.disabled&&ht(o,j,fM(D,ae)),le=fh(ae.ref)&&Un(D)?"":D,uM(ae.ref)?[...ae.ref.options].forEach(Ee=>Ee.selected=le.includes(Ee.value)):ae.refs?Yd(ae.ref)?ae.refs.length>1?ae.refs.forEach(Ee=>(!Ee.defaultChecked||!Ee.disabled)&&(Ee.checked=Array.isArray(le)?!!le.find(et=>et===Ee.value):le===Ee.value)):ae.refs[0]&&(ae.refs[0].checked=!!le):ae.refs.forEach(Ee=>Ee.checked=Ee.value===le):xw(ae.ref)?ae.ref.value="":(ae.ref.value=le,ae.ref.type||p.values.next({name:j,values:{...o}})))}(B.shouldDirty||B.shouldTouch)&&C(j,le,B.shouldTouch,B.shouldDirty,!0),B.shouldValidate&&Y(j)},ee=(j,D,B)=>{for(const pe in D){const le=D[pe],ae=`${j}.${pe}`,Ee=ce(r,ae);(l.array.has(j)||!hh(le)||Ee&&!Ee._f)&&!ml(le)?ee(ae,le,B):Q(ae,le,B)}},W=(j,D,B={})=>{const pe=ce(r,j),le=l.array.has(j),ae=Jn(D);ht(o,j,ae),le?(p.array.next({name:j,values:{...o}}),(d.isDirty||d.dirtyFields)&&B.shouldDirty&&p.state.next({name:j,dirtyFields:Lf(s,o),isDirty:I(j,ae)})):pe&&!pe._f&&!Un(ae)?ee(j,ae,B):Q(j,ae,B),EC(j,l)&&p.state.next({...n}),p.values.next({name:a.mount?j:void 0,values:{...o}})},F=async j=>{a.mount=!0;const D=j.target;let B=D.name,pe=!0;const le=ce(r,B),ae=()=>D.type?Ym(le._f):YP(j),Ee=et=>{pe=Number.isNaN(et)||et===ce(o,B,et)};if(le){let et,kt;const hn=ae(),yn=j.type===dh.BLUR||j.type===dh.FOCUS_OUT,gn=!KV(le._f)&&!t.resolver&&!ce(n.errors,B)&&!le._f.deps||qV(yn,ce(n.touchedFields,B),n.isSubmitted,h,f),jo=EC(B,l,yn);ht(o,B,hn),yn?(le._f.onBlur&&le._f.onBlur(j),c&&c(0)):le._f.onChange&&le._f.onChange(j);const gs=C(B,hn,yn,!1),Aa=!ur(gs)||jo;if(!yn&&p.values.next({name:B,type:j.type,values:{...o}}),gn)return d.isValid&&x(),Aa&&p.state.next({name:B,...jo?{}:gs});if(!yn&&jo&&p.state.next({...n}),t.resolver){const{errors:Fn}=await T([B]);if(Ee(hn),pe){const ue=PC(n.errors,r,B),Ue=PC(Fn,r,ue.name||B);et=Ue.error,B=Ue.name,kt=ur(Fn)}}else b([B],!0),et=(await RC(le,o,g,t.shouldUseNativeValidation))[B],b([B]),Ee(hn),pe&&(et?kt=!1:d.isValid&&(kt=await N(r,!0)));pe&&(le._f.deps&&Y(le._f.deps),k(B,kt,et,gs))}},A=(j,D)=>{if(ce(n.errors,D)&&j.focus)return j.focus(),1},Y=async(j,D={})=>{let B,pe;const le=Rc(j);if(t.resolver){const ae=await P(qt(j)?j:le);B=ur(ae),pe=j?!le.some(Ee=>ce(ae,Ee)):B}else j?(pe=(await Promise.all(le.map(async ae=>{const Ee=ce(r,ae);return await N(Ee&&Ee._f?{[ae]:Ee}:Ee)}))).every(Boolean),!(!pe&&!n.isValid)&&x()):pe=B=await N(r);return p.state.next({...!Os(j)||d.isValid&&B!==n.isValid?{}:{name:j},...t.resolver||!j?{isValid:B}:{},errors:n.errors}),D.shouldFocus&&!pe&&Pc(r,A,j?le:l.mount),pe},de=j=>{const D={...a.mount?o:s};return qt(j)?D:Os(j)?ce(D,j):j.map(B=>ce(D,B))},z=(j,D)=>({invalid:!!ce((D||n).errors,j),isDirty:!!ce((D||n).dirtyFields,j),error:ce((D||n).errors,j),isValidating:!!ce(n.validatingFields,j),isTouched:!!ce((D||n).touchedFields,j)}),se=j=>{j&&Rc(j).forEach(D=>ln(n.errors,D)),p.state.next({errors:j?n.errors:{}})},ne=(j,D,B)=>{const pe=(ce(r,j,{_f:{}})._f||{}).ref,le=ce(n.errors,j)||{},{ref:ae,message:Ee,type:et,...kt}=le;ht(n.errors,j,{...kt,...D,ref:pe}),p.state.next({name:j,errors:n.errors,isValid:!1}),B&&B.shouldFocus&&pe&&pe.focus&&pe.focus()},ie=(j,D)=>ta(j)?p.values.subscribe({next:B=>j(Z(void 0,D),B)}):Z(j,D,!0),oe=(j,D={})=>{for(const B of j?Rc(j):l.mount)l.mount.delete(B),l.array.delete(B),D.keepValue||(ln(r,B),ln(o,B)),!D.keepError&&ln(n.errors,B),!D.keepDirty&&ln(n.dirtyFields,B),!D.keepTouched&&ln(n.touchedFields,B),!D.keepIsValidating&&ln(n.validatingFields,B),!t.shouldUnregister&&!D.keepDefaultValue&&ln(s,B);p.values.next({values:{...o}}),p.state.next({...n,...D.keepDirty?{isDirty:I()}:{}}),!D.keepIsValid&&x()},J=({disabled:j,name:D,field:B,fields:pe,value:le})=>{if(js(j)&&a.mount||j){const ae=j?void 0:qt(le)?Ym(B?B._f:ce(pe,D)._f):le;ht(o,D,ae),C(D,ae,!1,!1,!0)}},Ce=(j,D={})=>{let B=ce(r,j);const pe=js(D.disabled);return ht(r,j,{...B||{},_f:{...B&&B._f?B._f:{ref:{name:j}},name:j,mount:!0,...D}}),l.mount.add(j),B?J({field:B,disabled:D.disabled,name:j,value:D.value}):E(j,!0,D.value),{...pe?{disabled:D.disabled}:{},...t.progressive?{required:!!D.required,min:Zu(D.min),max:Zu(D.max),minLength:Zu(D.minLength),maxLength:Zu(D.maxLength),pattern:Zu(D.pattern)}:{},name:j,onChange:F,onBlur:F,ref:le=>{if(le){Ce(j,D),B=ce(r,j);const ae=qt(le.value)&&le.querySelectorAll&&le.querySelectorAll("input,select,textarea")[0]||le,Ee=VV(ae),et=B._f.refs||[];if(Ee?et.find(kt=>kt===ae):ae===B._f.ref)return;ht(r,j,{_f:{...B._f,...Ee?{refs:[...et.filter(Zm),ae,...Array.isArray(ce(s,j))?[{}]:[]],ref:{type:ae.type,name:j}}:{ref:ae}}}),E(j,!1,void 0,ae)}else B=ce(r,j,{}),B._f&&(B._f.mount=!1),(t.shouldUnregister||D.shouldUnregister)&&!(XP(l.array,j)&&a.action)&&l.unMount.add(j)}}},Pe=()=>t.shouldFocusError&&Pc(r,A,l.mount),Le=j=>{js(j)&&(p.state.next({disabled:j}),Pc(r,(D,B)=>{const pe=ce(r,B);pe&&(D.disabled=pe._f.disabled||j,Array.isArray(pe._f.refs)&&pe._f.refs.forEach(le=>{le.disabled=pe._f.disabled||j}))},0,!1))},Me=(j,D)=>async B=>{let pe;B&&(B.preventDefault&&B.preventDefault(),B.persist&&B.persist());let le=Jn(o);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:ae,values:Ee}=await T();n.errors=ae,le=Ee}else await N(r);if(ln(n.errors,"root"),ur(n.errors)){p.state.next({errors:{}});try{await j(le,B)}catch(ae){pe=ae}}else D&&await D({...n.errors},B),Pe(),setTimeout(Pe);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ur(n.errors)&&!pe,submitCount:n.submitCount+1,errors:n.errors}),pe)throw pe},me=(j,D={})=>{ce(r,j)&&(qt(D.defaultValue)?W(j,Jn(ce(s,j))):(W(j,D.defaultValue),ht(s,j,Jn(D.defaultValue))),D.keepTouched||ln(n.touchedFields,j),D.keepDirty||(ln(n.dirtyFields,j),n.isDirty=D.defaultValue?I(j,Jn(ce(s,j))):I()),D.keepError||(ln(n.errors,j),d.isValid&&x()),p.state.next({...n}))},rt=(j,D={})=>{const B=j?Jn(j):s,pe=Jn(B),le=ur(j),ae=le?s:pe;if(D.keepDefaultValues||(s=B),!D.keepValues){if(D.keepDirtyValues)for(const Ee of l.mount)ce(n.dirtyFields,Ee)?ht(ae,Ee,ce(o,Ee)):W(Ee,ce(ae,Ee));else{if(vw&&qt(j))for(const Ee of l.mount){const et=ce(r,Ee);if(et&&et._f){const kt=Array.isArray(et._f.refs)?et._f.refs[0]:et._f.ref;if(fh(kt)){const hn=kt.closest("form");if(hn){hn.reset();break}}}}r={}}o=e.shouldUnregister?D.keepDefaultValues?Jn(s):{}:Jn(ae),p.array.next({values:{...ae}}),p.values.next({values:{...ae}})}l={mount:D.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!d.isValid||!!D.keepIsValid||!!D.keepDirtyValues,a.watch=!!e.shouldUnregister,p.state.next({submitCount:D.keepSubmitCount?n.submitCount:0,isDirty:le?!1:D.keepDirty?n.isDirty:!!(D.keepDefaultValues&&!Ya(j,s)),isSubmitted:D.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:le?{}:D.keepDirtyValues?D.keepDefaultValues&&o?Lf(s,o):n.dirtyFields:D.keepDefaultValues&&j?Lf(s,j):D.keepDirty?n.dirtyFields:{},touchedFields:D.keepTouched?n.touchedFields:{},errors:D.keepErrors?n.errors:{},isSubmitSuccessful:D.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},It=(j,D)=>rt(ta(j)?j(o):j,D);return{control:{register:Ce,unregister:oe,getFieldState:z,handleSubmit:Me,setError:ne,_executeSchema:T,_getWatch:Z,_getDirty:I,_updateValid:x,_removeUnmounted:U,_updateFieldArray:y,_updateDisabledField:J,_getFieldArray:V,_reset:rt,_resetDefaultValues:()=>ta(t.defaultValues)&&t.defaultValues().then(j=>{It(j,t.resetOptions),p.state.next({isLoading:!1})}),_updateFormState:j=>{n={...n,...j}},_disableForm:Le,_subjects:p,_proxyFormState:d,_setErrors:S,get _fields(){return r},get _formValues(){return o},get _state(){return a},set _state(j){a=j},get _defaultValues(){return s},get _names(){return l},set _names(j){l=j},get _formState(){return n},set _formState(j){n=j},get _options(){return t},set _options(j){t={...t,...j}}},trigger:Y,register:Ce,handleSubmit:Me,watch:ie,setValue:W,getValues:de,reset:It,resetField:me,clearErrors:se,unregister:oe,setError:ne,setFocus:(j,D={})=>{const B=ce(r,j),pe=B&&B._f;if(pe){const le=pe.refs?pe.refs[0]:pe.ref;le.focus&&(le.focus(),D.shouldSelect&&le.select())}},getFieldState:z}}function sn(e={}){const t=Te.useRef(),n=Te.useRef(),[r,s]=Te.useState({isDirty:!1,isValidating:!1,isLoading:ta(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ta(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...JV(e),formState:r});const o=t.current.control;return o._options=e,bw({subject:o._subjects.state,next:a=>{rM(a,o._proxyFormState,o._updateFormState,!0)&&s({...o._formState})}}),Te.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),Te.useEffect(()=>{if(o._proxyFormState.isDirty){const a=o._getDirty();a!==r.isDirty&&o._subjects.state.next({isDirty:a})}},[o,r.isDirty]),Te.useEffect(()=>{e.values&&!Ya(e.values,n.current)?(o._reset(e.values,o._options.resetOptions),n.current=e.values,s(a=>({...a}))):o._resetDefaultValues()},[e.values,o]),Te.useEffect(()=>{e.errors&&o._setErrors(e.errors)},[e.errors,o]),Te.useEffect(()=>{o._state.mount||(o._updateValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),Te.useEffect(()=>{e.shouldUnregister&&o._subjects.values.next({values:o._getWatch()})},[e.shouldUnregister,o]),t.current.formState=nM(r,o),t.current}const MC=(e,t,n)=>{if(e&&"reportValidity"in e){const r=ce(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},pM=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?MC(r.ref,n,e):r.refs&&r.refs.forEach(s=>MC(s,n,e))}},QV=(e,t)=>{t.shouldUseNativeValidation&&pM(e,t);const n={};for(const r in e){const s=ce(t.fields,r),o=Object.assign(e[r]||{},{ref:s&&s.ref});if(ZV(t.names||Object.keys(e),r)){const a=Object.assign({},ce(n,r));ht(a,"root",o),ht(n,r,a)}else ht(n,r,o)}return n},ZV=(e,t)=>e.some(n=>n.startsWith(t+"."));var YV=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,o=r.message,a=r.path.join(".");if(!n[a])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[a]={message:l.message,type:l.code}}else n[a]={message:o,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(d){return d.errors.forEach(function(p){return e.push(p)})}),t){var c=n[a].types,i=c&&c[r.code];n[a]=aM(a,t,n,s,i?[].concat(i,r.message):r.message)}e.shift()}return n},on=function(e,t,n){return n===void 0&&(n={}),function(r,s,o){try{return Promise.resolve(function(a,l){try{var c=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(i){return o.shouldUseNativeValidation&&pM({},o),{errors:{},values:n.raw?r:i}})}catch(i){return l(i)}return c&&c.then?c.then(void 0,l):c}(0,function(a){if(function(l){return Array.isArray(l==null?void 0:l.errors)}(a))return{values:{},errors:QV(YV(a.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw a}))}catch(a){return Promise.reject(a)}}},xn=[];for(var Xm=0;Xm<256;++Xm)xn.push((Xm+256).toString(16).slice(1));function XV(e,t=0){return(xn[e[t+0]]+xn[e[t+1]]+xn[e[t+2]]+xn[e[t+3]]+"-"+xn[e[t+4]]+xn[e[t+5]]+"-"+xn[e[t+6]]+xn[e[t+7]]+"-"+xn[e[t+8]]+xn[e[t+9]]+"-"+xn[e[t+10]]+xn[e[t+11]]+xn[e[t+12]]+xn[e[t+13]]+xn[e[t+14]]+xn[e[t+15]]).toLowerCase()}var $f,e6=new Uint8Array(16);function t6(){if(!$f&&($f=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!$f))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $f(e6)}var n6=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const OC={randomUUID:n6};function NC(e,t,n){if(OC.randomUUID&&!t&&!e)return OC.randomUUID();e=e||{};var r=e.random||(e.rng||t6)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,XV(r)}var ut;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),a={};for(const l of o)a[l]=s[l];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},e.find=(s,o)=>{for(const a of s)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ut||(ut={}));var Xy;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Xy||(Xy={}));const be=ut.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Vo=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},re=ut.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),r6=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class yr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let l=r,c=0;for(;cn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}yr.create=e=>new yr(e);const nu=(e,t)=>{let n;switch(e.code){case re.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case re.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ut.jsonStringifyReplacer)}`;break;case re.unrecognized_keys:n=`Unrecognized key(s) in object: ${ut.joinValues(e.keys,", ")}`;break;case re.invalid_union:n="Invalid input";break;case re.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ut.joinValues(e.options)}`;break;case re.invalid_enum_value:n=`Invalid enum value. Expected ${ut.joinValues(e.options)}, received '${e.received}'`;break;case re.invalid_arguments:n="Invalid function arguments";break;case re.invalid_return_type:n="Invalid function return type";break;case re.invalid_date:n="Invalid date";break;case re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:ut.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case re.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case re.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case re.custom:n="Invalid input";break;case re.invalid_intersection_types:n="Intersection results could not be merged";break;case re.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case re.not_finite:n="Number must be finite";break;default:n=t.defaultError,ut.assertNever(e)}return{message:n}};let hM=nu;function s6(e){hM=e}function mh(){return hM}const vh=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let l="";const c=r.filter(i=>!!i).slice().reverse();for(const i of c)l=i(a,{data:t,defaultError:l}).message;return{...s,path:o,message:l}},o6=[];function ve(e,t){const n=mh(),r=vh({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===nu?void 0:nu].filter(s=>!!s)});e.common.issues.push(r)}class Dn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return Be;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,a=await s.value;r.push({key:o,value:a})}return Dn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return Be;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}}const Be=Object.freeze({status:"aborted"}),vl=e=>({status:"dirty",value:e}),Kn=e=>({status:"valid",value:e}),eb=e=>e.status==="aborted",tb=e=>e.status==="dirty",cd=e=>e.status==="valid",dd=e=>typeof Promise<"u"&&e instanceof Promise;function yh(e,t,n,r){if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function gM(e,t,n,r,s){if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var je;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(je||(je={}));var fc,pc;class zs{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const IC=(e,t)=>{if(cd(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new yr(e.common.issues);return this._error=n,this._error}}};function Ke(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,l)=>{var c,i;const{message:d}=e;return a.code==="invalid_enum_value"?{message:d??l.defaultError}:typeof l.data>"u"?{message:(c=d??r)!==null&&c!==void 0?c:l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:(i=d??n)!==null&&i!==void 0?i:l.defaultError}},description:s}}class Qe{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return Vo(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Dn,ctx:{common:t.parent.common,data:t.data,parsedType:Vo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(dd(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},o=this._parseSync({data:t,path:s.path,parent:s});return IC(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vo(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(dd(s)?s:Promise.resolve(s));return IC(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const a=t(s),l=()=>o.addIssue({code:re.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ds({schema:this,typeName:Fe.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Ls.create(this,this._def)}nullable(){return xa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return as.create(this,this._def)}promise(){return su.create(this,this._def)}or(t){return gd.create([this,t],this._def)}and(t){return md.create(this,t,this._def)}transform(t){return new ds({...Ke(this._def),schema:this,typeName:Fe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new wd({...Ke(this._def),innerType:this,defaultValue:n,typeName:Fe.ZodDefault})}brand(){return new Sw({typeName:Fe.ZodBranded,type:this,...Ke(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Sd({...Ke(this._def),innerType:this,catchValue:n,typeName:Fe.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Xd.create(this,t)}readonly(){return Cd.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const a6=/^c[^\s-]{8,}$/i,i6=/^[0-9a-z]+$/,l6=/^[0-9A-HJKMNP-TV-Z]{26}$/,u6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,c6=/^[a-z0-9_-]{21}$/i,d6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,f6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,p6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ev;const h6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,g6=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,m6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mM="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",v6=new RegExp(`^${mM}$`);function vM(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function y6(e){return new RegExp(`^${vM(e)}$`)}function yM(e){let t=`${mM}T${vM(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function b6(e,t){return!!((t==="v4"||!t)&&h6.test(e)||(t==="v6"||!t)&&g6.test(e))}class es extends Qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.string,received:o.parsedType}),Be}const r=new Dn;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const a=t.data.length>o.value,l=t.data.lengtht.test(s),{validation:n,code:re.invalid_string,...je.errToObj(r)})}_addCheck(t){return new es({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...je.errToObj(t)})}url(t){return this._addCheck({kind:"url",...je.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...je.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...je.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...je.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...je.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...je.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...je.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...je.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...je.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,local:(r=t==null?void 0:t.local)!==null&&r!==void 0?r:!1,...je.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...je.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...je.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...je.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...je.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...je.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...je.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...je.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...je.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...je.errToObj(n)})}nonempty(t){return this.min(1,je.errToObj(t))}trim(){return new es({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new es({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new es({checks:[],typeName:Fe.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};function x6(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return o%a/Math.pow(10,s)}class va extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.number,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="int"?ut.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?x6(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_finite,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,je.toString(n))}gt(t,n){return this.setLimit("min",t,!1,je.toString(n))}lte(t,n){return this.setLimit("max",t,!0,je.toString(n))}lt(t,n){return this.setLimit("max",t,!1,je.toString(n))}setLimit(t,n,r,s){return new va({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:je.toString(s)}]})}_addCheck(t){return new va({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:je.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:je.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:je.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:je.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:je.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:je.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:je.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:je.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:je.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&ut.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew va({checks:[],typeName:Fe.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class ya extends Qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.bigint,received:o.parsedType}),Be}let r;const s=new Dn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),ve(r,{code:re.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ut.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,je.toString(n))}gt(t,n){return this.setLimit("min",t,!1,je.toString(n))}lte(t,n){return this.setLimit("max",t,!0,je.toString(n))}lt(t,n){return this.setLimit("max",t,!1,je.toString(n))}setLimit(t,n,r,s){return new ya({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:je.toString(s)}]})}_addCheck(t){return new ya({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:je.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:je.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:je.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:je.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:je.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new ya({checks:[],typeName:Fe.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Ke(e)})};class fd extends Qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.boolean,received:r.parsedType}),Be}return Kn(t.data)}}fd.create=e=>new fd({typeName:Fe.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ke(e)});class Ti extends Qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_type,expected:be.date,received:o.parsedType}),Be}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return ve(o,{code:re.invalid_date}),Be}const r=new Dn;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),ve(s,{code:re.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):ut.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ti({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:je.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:je.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Ti({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Fe.ZodDate,...Ke(e)});class bh extends Qe{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.symbol,received:r.parsedType}),Be}return Kn(t.data)}}bh.create=e=>new bh({typeName:Fe.ZodSymbol,...Ke(e)});class pd extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.undefined,received:r.parsedType}),Be}return Kn(t.data)}}pd.create=e=>new pd({typeName:Fe.ZodUndefined,...Ke(e)});class hd extends Qe{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.null,received:r.parsedType}),Be}return Kn(t.data)}}hd.create=e=>new hd({typeName:Fe.ZodNull,...Ke(e)});class ru extends Qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Kn(t.data)}}ru.create=e=>new ru({typeName:Fe.ZodAny,...Ke(e)});class fi extends Qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Kn(t.data)}}fi.create=e=>new fi({typeName:Fe.ZodUnknown,...Ke(e)});class bo extends Qe{_parse(t){const n=this._getOrReturnCtx(t);return ve(n,{code:re.invalid_type,expected:be.never,received:n.parsedType}),Be}}bo.create=e=>new bo({typeName:Fe.ZodNever,...Ke(e)});class xh extends Qe{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.void,received:r.parsedType}),Be}return Kn(t.data)}}xh.create=e=>new xh({typeName:Fe.ZodVoid,...Ke(e)});class as extends Qe{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==be.array)return ve(n,{code:re.invalid_type,expected:be.array,received:n.parsedType}),Be;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,l=n.data.lengths.maxLength.value&&(ve(n,{code:re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,l)=>s.type._parseAsync(new zs(n,a,n.path,l)))).then(a=>Dn.mergeArray(r,a));const o=[...n.data].map((a,l)=>s.type._parseSync(new zs(n,a,n.path,l)));return Dn.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new as({...this._def,minLength:{value:t,message:je.toString(n)}})}max(t,n){return new as({...this._def,maxLength:{value:t,message:je.toString(n)}})}length(t,n){return new as({...this._def,exactLength:{value:t,message:je.toString(n)}})}nonempty(t){return this.min(1,t)}}as.create=(e,t)=>new as({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Fe.ZodArray,...Ke(t)});function tl(e){if(e instanceof Dt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ls.create(tl(r))}return new Dt({...e._def,shape:()=>t})}else return e instanceof as?new as({...e._def,type:tl(e.element)}):e instanceof Ls?Ls.create(tl(e.unwrap())):e instanceof xa?xa.create(tl(e.unwrap())):e instanceof Us?Us.create(e.items.map(t=>tl(t))):e}class Dt extends Qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=ut.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const i=this._getOrReturnCtx(t);return ve(i,{code:re.invalid_type,expected:be.object,received:i.parsedType}),Be}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof bo&&this._def.unknownKeys==="strip"))for(const i in s.data)a.includes(i)||l.push(i);const c=[];for(const i of a){const d=o[i],p=s.data[i];c.push({key:{status:"valid",value:i},value:d._parse(new zs(s,p,s.path,i)),alwaysSet:i in s.data})}if(this._def.catchall instanceof bo){const i=this._def.unknownKeys;if(i==="passthrough")for(const d of l)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(i==="strict")l.length>0&&(ve(s,{code:re.unrecognized_keys,keys:l}),r.dirty());else if(i!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const i=this._def.catchall;for(const d of l){const p=s.data[d];c.push({key:{status:"valid",value:d},value:i._parse(new zs(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const i=[];for(const d of c){const p=await d.key,f=await d.value;i.push({key:p,value:f,alwaysSet:d.alwaysSet})}return i}).then(i=>Dn.mergeObjectSync(r,i)):Dn.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return je.errToObj,new Dt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,a,l;const c=(a=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=je.errToObj(t).message)!==null&&l!==void 0?l:c}:{message:c}}}:{}})}strip(){return new Dt({...this._def,unknownKeys:"strip"})}passthrough(){return new Dt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Dt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Dt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Fe.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Dt({...this._def,catchall:t})}pick(t){const n={};return ut.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}omit(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Dt({...this._def,shape:()=>n})}deepPartial(){return tl(this)}partial(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new Dt({...this._def,shape:()=>n})}required(t){const n={};return ut.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ls;)o=o._def.innerType;n[r]=o}}),new Dt({...this._def,shape:()=>n})}keyof(){return bM(ut.objectKeys(this.shape))}}Dt.create=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.strictCreate=(e,t)=>new Dt({shape:()=>e,unknownKeys:"strict",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});Dt.lazycreate=(e,t)=>new Dt({shape:e,unknownKeys:"strip",catchall:bo.create(),typeName:Fe.ZodObject,...Ke(t)});class gd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const l of o)if(l.result.status==="valid")return l.result;for(const l of o)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const a=o.map(l=>new yr(l.ctx.common.issues));return ve(n,{code:re.invalid_union,unionErrors:a}),Be}if(n.common.async)return Promise.all(r.map(async o=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const c of r){const i={...n,common:{...n.common,issues:[]},parent:null},d=c._parseSync({data:n.data,path:n.path,parent:i});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:i}),i.common.issues.length&&a.push(i.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const l=a.map(c=>new yr(c));return ve(n,{code:re.invalid_union,unionErrors:l}),Be}}get options(){return this._def.options}}gd.create=(e,t)=>new gd({options:e,typeName:Fe.ZodUnion,...Ke(t)});const Qs=e=>e instanceof yd?Qs(e.schema):e instanceof ds?Qs(e.innerType()):e instanceof bd?[e.value]:e instanceof ba?e.options:e instanceof xd?ut.objectValues(e.enum):e instanceof wd?Qs(e._def.innerType):e instanceof pd?[void 0]:e instanceof hd?[null]:e instanceof Ls?[void 0,...Qs(e.unwrap())]:e instanceof xa?[null,...Qs(e.unwrap())]:e instanceof Sw||e instanceof Cd?Qs(e.unwrap()):e instanceof Sd?Qs(e._def.innerType):[];class Pg extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return ve(n,{code:re.invalid_type,expected:be.object,received:n.parsedType}),Be;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(ve(n,{code:re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const a=Qs(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of a){if(s.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);s.set(l,o)}}return new Pg({typeName:Fe.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Ke(r)})}}function nb(e,t){const n=Vo(e),r=Vo(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const s=ut.objectKeys(t),o=ut.objectKeys(e).filter(l=>s.indexOf(l)!==-1),a={...e,...t};for(const l of o){const c=nb(e[l],t[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(eb(o)||eb(a))return Be;const l=nb(o.value,a.value);return l.valid?((tb(o)||tb(a))&&n.dirty(),{status:n.value,value:l.data}):(ve(r,{code:re.invalid_intersection_types}),Be)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}md.create=(e,t,n)=>new md({left:e,right:t,typeName:Fe.ZodIntersection,...Ke(n)});class Us extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return ve(r,{code:re.invalid_type,expected:be.array,received:r.parsedType}),Be;if(r.data.lengththis._def.items.length&&(ve(r,{code:re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((a,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new zs(r,a,r.path,l)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>Dn.mergeArray(n,a)):Dn.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Us({...this._def,rest:t})}}Us.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Us({items:e,typeName:Fe.ZodTuple,rest:null,...Ke(t)})};class vd extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return ve(r,{code:re.invalid_type,expected:be.object,received:r.parsedType}),Be;const s=[],o=this._def.keyType,a=this._def.valueType;for(const l in r.data)s.push({key:o._parse(new zs(r,l,r.path,l)),value:a._parse(new zs(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?Dn.mergeObjectAsync(n,s):Dn.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Qe?new vd({keyType:t,valueType:n,typeName:Fe.ZodRecord,...Ke(r)}):new vd({keyType:es.create(),valueType:t,typeName:Fe.ZodRecord,...Ke(n)})}}class wh extends Qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return ve(r,{code:re.invalid_type,expected:be.map,received:r.parsedType}),Be;const s=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([l,c],i)=>({key:s._parse(new zs(r,l,r.path,[i,"key"])),value:o._parse(new zs(r,c,r.path,[i,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of a){const i=await c.key,d=await c.value;if(i.status==="aborted"||d.status==="aborted")return Be;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),l.set(i.value,d.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const c of a){const i=c.key,d=c.value;if(i.status==="aborted"||d.status==="aborted")return Be;(i.status==="dirty"||d.status==="dirty")&&n.dirty(),l.set(i.value,d.value)}return{status:n.value,value:l}}}}wh.create=(e,t,n)=>new wh({valueType:t,keyType:e,typeName:Fe.ZodMap,...Ke(n)});class ki extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return ve(r,{code:re.invalid_type,expected:be.set,received:r.parsedType}),Be;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(ve(r,{code:re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function a(c){const i=new Set;for(const d of c){if(d.status==="aborted")return Be;d.status==="dirty"&&n.dirty(),i.add(d.value)}return{status:n.value,value:i}}const l=[...r.data.values()].map((c,i)=>o._parse(new zs(r,c,r.path,i)));return r.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(t,n){return new ki({...this._def,minSize:{value:t,message:je.toString(n)}})}max(t,n){return new ki({...this._def,maxSize:{value:t,message:je.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ki.create=(e,t)=>new ki({valueType:e,minSize:null,maxSize:null,typeName:Fe.ZodSet,...Ke(t)});class jl extends Qe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return ve(n,{code:re.invalid_type,expected:be.function,received:n.parsedType}),Be;function r(l,c){return vh({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(i=>!!i),issueData:{code:re.invalid_arguments,argumentsError:c}})}function s(l,c){return vh({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mh(),nu].filter(i=>!!i),issueData:{code:re.invalid_return_type,returnTypeError:c}})}const o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof su){const l=this;return Kn(async function(...c){const i=new yr([]),d=await l._def.args.parseAsync(c,o).catch(h=>{throw i.addIssue(r(c,h)),i}),p=await Reflect.apply(a,this,d);return await l._def.returns._def.type.parseAsync(p,o).catch(h=>{throw i.addIssue(s(p,h)),i})})}else{const l=this;return Kn(function(...c){const i=l._def.args.safeParse(c,o);if(!i.success)throw new yr([r(c,i.error)]);const d=Reflect.apply(a,this,i.data),p=l._def.returns.safeParse(d,o);if(!p.success)throw new yr([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new jl({...this._def,args:Us.create(t).rest(fi.create())})}returns(t){return new jl({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new jl({args:t||Us.create([]).rest(fi.create()),returns:n||fi.create(),typeName:Fe.ZodFunction,...Ke(r)})}}class yd extends Qe{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}yd.create=(e,t)=>new yd({getter:e,typeName:Fe.ZodLazy,...Ke(t)});class bd extends Qe{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return ve(n,{received:n.data,code:re.invalid_literal,expected:this._def.value}),Be}return{status:"valid",value:t.data}}get value(){return this._def.value}}bd.create=(e,t)=>new bd({value:e,typeName:Fe.ZodLiteral,...Ke(t)});function bM(e,t){return new ba({values:e,typeName:Fe.ZodEnum,...Ke(t)})}class ba extends Qe{constructor(){super(...arguments),fc.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{expected:ut.joinValues(r),received:n.parsedType,code:re.invalid_type}),Be}if(yh(this,fc)||gM(this,fc,new Set(this._def.values)),!yh(this,fc).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return ve(n,{received:n.data,code:re.invalid_enum_value,options:r}),Be}return Kn(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return ba.create(t,{...this._def,...n})}exclude(t,n=this._def){return ba.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}fc=new WeakMap;ba.create=bM;class xd extends Qe{constructor(){super(...arguments),pc.set(this,void 0)}_parse(t){const n=ut.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const s=ut.objectValues(n);return ve(r,{expected:ut.joinValues(s),received:r.parsedType,code:re.invalid_type}),Be}if(yh(this,pc)||gM(this,pc,new Set(ut.getValidEnumValues(this._def.values))),!yh(this,pc).has(t.data)){const s=ut.objectValues(n);return ve(r,{received:r.data,code:re.invalid_enum_value,options:s}),Be}return Kn(t.data)}get enum(){return this._def.values}}pc=new WeakMap;xd.create=(e,t)=>new xd({values:e,typeName:Fe.ZodNativeEnum,...Ke(t)});class su extends Qe{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return ve(n,{code:re.invalid_type,expected:be.promise,received:n.parsedType}),Be;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return Kn(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}su.create=(e,t)=>new su({type:e,typeName:Fe.ZodPromise,...Ke(t)});class ds extends Qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:a=>{ve(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async l=>{if(n.value==="aborted")return Be;const c=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return c.status==="aborted"?Be:c.status==="dirty"||n.value==="dirty"?vl(c.value):c});{if(n.value==="aborted")return Be;const l=this._def.schema._parseSync({data:a,path:r.path,parent:r});return l.status==="aborted"?Be:l.status==="dirty"||n.value==="dirty"?vl(l.value):l}}if(s.type==="refinement"){const a=l=>{const c=s.refinement(l,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Be:(l.status==="dirty"&&n.dirty(),a(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Be:(l.status==="dirty"&&n.dirty(),a(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!cd(a))return a;const l=s.transform(a.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>cd(a)?Promise.resolve(s.transform(a.value,o)).then(l=>({status:n.value,value:l})):a);ut.assertNever(s)}}ds.create=(e,t,n)=>new ds({schema:e,typeName:Fe.ZodEffects,effect:t,...Ke(n)});ds.createWithPreprocess=(e,t,n)=>new ds({schema:t,effect:{type:"preprocess",transform:e},typeName:Fe.ZodEffects,...Ke(n)});class Ls extends Qe{_parse(t){return this._getType(t)===be.undefined?Kn(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ls.create=(e,t)=>new Ls({innerType:e,typeName:Fe.ZodOptional,...Ke(t)});class xa extends Qe{_parse(t){return this._getType(t)===be.null?Kn(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}xa.create=(e,t)=>new xa({innerType:e,typeName:Fe.ZodNullable,...Ke(t)});class wd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}wd.create=(e,t)=>new wd({innerType:e,typeName:Fe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ke(t)});class Sd extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return dd(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new yr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Sd.create=(e,t)=>new Sd({innerType:e,typeName:Fe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ke(t)});class Sh extends Qe{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return ve(r,{code:re.invalid_type,expected:be.nan,received:r.parsedType}),Be}return{status:"valid",value:t.data}}}Sh.create=e=>new Sh({typeName:Fe.ZodNaN,...Ke(e)});const w6=Symbol("zod_brand");class Sw extends Qe{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class Xd extends Qe{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Be:o.status==="dirty"?(n.dirty(),vl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Be:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new Xd({in:t,out:n,typeName:Fe.ZodPipeline})}}class Cd extends Qe{_parse(t){const n=this._def.innerType._parse(t),r=s=>(cd(s)&&(s.value=Object.freeze(s.value)),s);return dd(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Cd.create=(e,t)=>new Cd({innerType:e,typeName:Fe.ZodReadonly,...Ke(t)});function xM(e,t={},n){return e?ru.create().superRefine((r,s)=>{var o,a;if(!e(r)){const l=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,c=(a=(o=l.fatal)!==null&&o!==void 0?o:n)!==null&&a!==void 0?a:!0,i=typeof l=="string"?{message:l}:l;s.addIssue({code:"custom",...i,fatal:c})}}):ru.create()}const S6={object:Dt.lazycreate};var Fe;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Fe||(Fe={}));const C6=(e,t={message:`Input not instance of ${e.name}`})=>xM(n=>n instanceof e,t),wM=es.create,SM=va.create,E6=Sh.create,T6=ya.create,CM=fd.create,k6=Ti.create,_6=bh.create,j6=pd.create,R6=hd.create,P6=ru.create,M6=fi.create,O6=bo.create,N6=xh.create,I6=as.create,D6=Dt.create,A6=Dt.strictCreate,F6=gd.create,L6=Pg.create,$6=md.create,B6=Us.create,z6=vd.create,U6=wh.create,V6=ki.create,H6=jl.create,K6=yd.create,q6=bd.create,W6=ba.create,G6=xd.create,J6=su.create,DC=ds.create,Q6=Ls.create,Z6=xa.create,Y6=ds.createWithPreprocess,X6=Xd.create,e8=()=>wM().optional(),t8=()=>SM().optional(),n8=()=>CM().optional(),r8={string:e=>es.create({...e,coerce:!0}),number:e=>va.create({...e,coerce:!0}),boolean:e=>fd.create({...e,coerce:!0}),bigint:e=>ya.create({...e,coerce:!0}),date:e=>Ti.create({...e,coerce:!0})},s8=Be;var _=Object.freeze({__proto__:null,defaultErrorMap:nu,setErrorMap:s6,getErrorMap:mh,makeIssue:vh,EMPTY_PATH:o6,addIssueToContext:ve,ParseStatus:Dn,INVALID:Be,DIRTY:vl,OK:Kn,isAborted:eb,isDirty:tb,isValid:cd,isAsync:dd,get util(){return ut},get objectUtil(){return Xy},ZodParsedType:be,getParsedType:Vo,ZodType:Qe,datetimeRegex:yM,ZodString:es,ZodNumber:va,ZodBigInt:ya,ZodBoolean:fd,ZodDate:Ti,ZodSymbol:bh,ZodUndefined:pd,ZodNull:hd,ZodAny:ru,ZodUnknown:fi,ZodNever:bo,ZodVoid:xh,ZodArray:as,ZodObject:Dt,ZodUnion:gd,ZodDiscriminatedUnion:Pg,ZodIntersection:md,ZodTuple:Us,ZodRecord:vd,ZodMap:wh,ZodSet:ki,ZodFunction:jl,ZodLazy:yd,ZodLiteral:bd,ZodEnum:ba,ZodNativeEnum:xd,ZodPromise:su,ZodEffects:ds,ZodTransformer:ds,ZodOptional:Ls,ZodNullable:xa,ZodDefault:wd,ZodCatch:Sd,ZodNaN:Sh,BRAND:w6,ZodBranded:Sw,ZodPipeline:Xd,ZodReadonly:Cd,custom:xM,Schema:Qe,ZodSchema:Qe,late:S6,get ZodFirstPartyTypeKind(){return Fe},coerce:r8,any:P6,array:I6,bigint:T6,boolean:CM,date:k6,discriminatedUnion:L6,effect:DC,enum:W6,function:H6,instanceof:C6,intersection:$6,lazy:K6,literal:q6,map:U6,nan:E6,nativeEnum:G6,never:O6,null:R6,nullable:Z6,number:SM,object:D6,oboolean:n8,onumber:t8,optional:Q6,ostring:e8,pipeline:X6,preprocess:Y6,promise:J6,record:z6,set:V6,strictObject:A6,string:wM,symbol:_6,transformer:DC,tuple:B6,undefined:j6,union:F6,unknown:M6,void:N6,NEVER:s8,ZodIssueCode:re,quotelessJson:r6,ZodError:yr}),EM=v.createContext({dragDropManager:void 0}),Dr;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(Dr||(Dr={}));function Ve(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s-1})}var u8={type:Cw,payload:{clientOffset:null,sourceClientOffset:null}};function c8(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},s=r.publishSource,o=s===void 0?!0:s,a=r.clientOffset,l=r.getSourceClientOffset,c=e.getMonitor(),i=e.getRegistry();e.dispatch(AC(a)),d8(n,c,i);var d=h8(n,c);if(d===null){e.dispatch(u8);return}var p=null;if(a){if(!l)throw new Error("getSourceClientOffset must be defined");f8(l),p=l(d)}e.dispatch(AC(a,p));var f=i.getSource(d),h=f.beginDrag(c,d);if(h!=null){p8(h),i.pinSource(d);var g=i.getSourceType(d);return{type:Mg,payload:{itemType:g,item:h,sourceId:d,clientOffset:a||null,sourceClientOffset:p||null,isSourcePublic:!!o}}}}}function d8(e,t,n){Ve(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){Ve(n.getSource(r),"Expected sourceIds to be registered.")})}function f8(e){Ve(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function p8(e){Ve(TM(e),"Item must be an object.")}function h8(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function g8(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Ew}}}function rb(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function m8(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.clientOffset;v8(n);var o=n.slice(0),a=e.getMonitor(),l=e.getRegistry();y8(o,a,l);var c=a.getItemType();return b8(o,l,c),x8(o,a,l),{type:Og,payload:{targetIds:o,clientOffset:s||null}}}}function v8(e){Ve(Array.isArray(e),"Expected targetIds to be an array.")}function y8(e,t,n){Ve(t.isDragging(),"Cannot call hover while not dragging."),Ve(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var s=e[r],o=t.getTargetType(s);rb(o,n)||e.splice(r,1)}}function x8(e,t,n){e.forEach(function(r){var s=n.getTarget(r);s.hover(t,r)})}function FC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function LC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),s=e.getRegistry();C8(r);var o=k8(r);o.forEach(function(a,l){var c=E8(a,l,s,r),i={type:Ng,payload:{dropResult:LC(LC({},n),c)}};e.dispatch(i)})}}function C8(e){Ve(e.isDragging(),"Cannot call drop while not dragging."),Ve(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function E8(e,t,n,r){var s=n.getTarget(e),o=s?s.drop(r,e):void 0;return T8(o),typeof o>"u"&&(o=t===0?{}:r.getDropResult()),o}function T8(e){Ve(typeof e>"u"||TM(e),"Drop result must either be an object or undefined.")}function k8(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function _8(e){return function(){var n=e.getMonitor(),r=e.getRegistry();j8(n);var s=n.getSourceId();if(s!=null){var o=r.getSource(s,!0);o.endDrag(n,s),r.unpinSource()}return{type:Ig}}}function j8(e){Ve(e.isDragging(),"Cannot call endDrag while not dragging.")}function R8(e){return{beginDrag:c8(e),publishDragSource:g8(e),hover:m8(e),drop:S8(e),endDrag:_8(e)}}function P8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function M8(e,t){for(var n=0;n0;r.backend&&(s&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!s&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return O8(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function s(a){return function(){for(var l=arguments.length,c=new Array(l),i=0;i"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(_r(1));return n(kM)(e,t)}if(typeof e!="function")throw new Error(_r(2));var s=e,o=t,a=[],l=a,c=!1;function i(){l===a&&(l=a.slice())}function d(){if(c)throw new Error(_r(3));return o}function p(m){if(typeof m!="function")throw new Error(_r(4));if(c)throw new Error(_r(5));var x=!0;return i(),l.push(m),function(){if(x){if(c)throw new Error(_r(6));x=!1,i();var y=l.indexOf(m);l.splice(y,1),a=null}}}function f(m){if(!I8(m))throw new Error(_r(7));if(typeof m.type>"u")throw new Error(_r(8));if(c)throw new Error(_r(9));try{c=!0,o=s(o,m)}finally{c=!1}for(var x=a=l,b=0;b2&&arguments[2]!==void 0?arguments[2]:D8;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:VC,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Cw:case Mg:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Og:return A8(e.clientOffset,n.clientOffset)?e:UC(UC({},e),{},{clientOffset:n.clientOffset});case Ig:case Ng:return VC;default:return e}}var Tw="dnd-core/ADD_SOURCE",kw="dnd-core/ADD_TARGET",_w="dnd-core/REMOVE_SOURCE",Dg="dnd-core/REMOVE_TARGET";function B8(e){return{type:Tw,payload:{sourceId:e}}}function z8(e){return{type:kw,payload:{targetId:e}}}function U8(e){return{type:_w,payload:{sourceId:e}}}function V8(e){return{type:Dg,payload:{targetId:e}}}function HC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function jr(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:K8,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Mg:return jr(jr({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Ew:return jr(jr({},e),{},{isSourcePublic:!0});case Og:return jr(jr({},e),{},{targetIds:n.targetIds});case Dg:return e.targetIds.indexOf(n.targetId)===-1?e:jr(jr({},e),{},{targetIds:a8(e.targetIds,n.targetId)});case Ng:return jr(jr({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case Ig:return jr(jr({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function W8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case Tw:case kw:return e+1;case _w:case Dg:return e-1;default:return e}}var Ch=[],jw=[];Ch.__IS_NONE__=!0;jw.__IS_ALL__=!0;function G8(e,t){if(e===Ch)return!1;if(e===jw||typeof t>"u")return!0;var n=l8(t,e);return n.length>0}function J8(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Og:break;case Tw:case kw:case Dg:case _w:return Ch;case Mg:case Ew:case Ig:case Ng:default:return jw}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,s=t.prevTargetIds,o=s===void 0?[]:s,a=i8(r,o),l=a.length>0||!F8(r,o);if(!l)return Ch;var c=o[o.length-1],i=r[r.length-1];return c!==i&&(c&&a.push(c),i&&a.push(i)),a}function Q8(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function KC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function qC(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:J8(e.dirtyHandlerIds,{type:t.type,payload:qC(qC({},t.payload),{},{prevTargetIds:o8(e,"dragOperation.targetIds",[])})}),dragOffset:$8(e.dragOffset,t),refCount:W8(e.refCount,t),dragOperation:q8(e.dragOperation,t),stateId:Q8(e.stateId)}}function X8(e,t){return{x:e.x+t.x,y:e.y+t.y}}function _M(e,t){return{x:e.x-t.x,y:e.y-t.y}}function eH(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:_M(X8(t,r),n)}function tH(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:_M(t,n)}function nH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rH(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},o=s.handlerIds;Ve(typeof n=="function","listener must be a function."),Ve(typeof o>"u"||Array.isArray(o),"handlerIds, when specified, must be an array of strings.");var a=this.store.getState().stateId,l=function(){var i=r.store.getState(),d=i.stateId;try{var p=d===a||d===a+1&&!G8(i.dirtyHandlerIds,o);p||n()}finally{a=d}};return this.store.subscribe(l)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;Ve(typeof n=="function","listener must be a function.");var s=this.store.getState().dragOffset,o=function(){var l=r.store.getState().dragOffset;l!==s&&(s=l,n())};return this.store.subscribe(o)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return Ve(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(Ve(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var s=this.registry.getTargetType(n),o=this.getItemType();return rb(s,o)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(Ve(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var s=this.registry.getSourceType(n),o=this.getItemType();return s!==o?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var s=r.shallow;if(!this.isDragging())return!1;var o=this.registry.getTargetType(n),a=this.getItemType();if(a&&!rb(o,a))return!1;var l=this.getTargetIds();if(!l.length)return!1;var c=l.indexOf(n);return s?c===l.length-1:c>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return eH(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return tH(this.store.getState().dragOffset)}}]),e}(),aH=0;function iH(){return aH++}function bp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bp=function(n){return typeof n}:bp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},bp(e)}function lH(e){Ve(typeof e.canDrag=="function","Expected canDrag to be a function."),Ve(typeof e.beginDrag=="function","Expected beginDrag to be a function."),Ve(typeof e.endDrag=="function","Expected endDrag to be a function.")}function uH(e){Ve(typeof e.canDrop=="function","Expected canDrop to be a function."),Ve(typeof e.hover=="function","Expected hover to be a function."),Ve(typeof e.drop=="function","Expected beginDrag to be a function.")}function sb(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return sb(n,!1)});return}Ve(typeof e=="string"||bp(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const GC=typeof global<"u"?global:self,jM=GC.MutationObserver||GC.WebKitMutationObserver;function RM(e){return function(){const n=setTimeout(s,0),r=setInterval(s,50);function s(){clearTimeout(n),clearInterval(r),e()}}}function cH(e){let t=1;const n=new jM(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const dH=typeof jM=="function"?cH:RM;class fH{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,s=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=dH(this.flush),this.requestErrorThrow=RM(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class pH{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class hH{create(t){const n=this.freeTasks,r=n.length?n.pop():new pH(this.onError,s=>n[n.length]=s);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const PM=new fH,gH=new hH(PM.registerPendingError);function mH(e){PM.enqueueTask(gH.create(e))}function vH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function yH(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;Ve(this.isSourceId(n),"Expected a valid source ID.");var s=r&&n===this.pinnedSourceId,o=s?this.pinnedSource:this.dragSources.get(n);return o}},{key:"getTarget",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return Ve(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return Ve(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=QC(n);return r===Dr.SOURCE}},{key:"isTargetId",value:function(n){var r=QC(n);return r===Dr.TARGET}},{key:"removeSource",value:function(n){var r=this;Ve(this.getSource(n),"Expected an existing source."),this.store.dispatch(U8(n)),mH(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){Ve(this.getTarget(n),"Expected an existing target."),this.store.dispatch(V8(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);Ve(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){Ve(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,s){var o=TH(n);return this.types.set(o,r),n===Dr.SOURCE?this.dragSources.set(o,s):n===Dr.TARGET&&this.dropTargets.set(o,s),o}}]),e}();function _H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=jH(r),o=new oH(s,new kH(s)),a=new N8(s,o),l=e(a,t,n);return a.receiveBackend(l),a}function jH(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return kM(Y8,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var RH=["children"];function PH(e,t){return IH(e)||NH(e,t)||OH(e,t)||MH()}function MH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OH(e,t){if(e){if(typeof e=="string")return YC(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return YC(e,t)}}function YC(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function AH(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o=0)&&(n[s]=e[s]);return n}var XC=0,xp=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),FH=v.memo(function(t){var n=t.children,r=DH(t,RH),s=LH(r),o=PH(s,2),a=o[0],l=o[1];return v.useEffect(function(){if(l){var c=MM();return++XC,function(){--XC===0&&(c[xp]=null)}}},[]),u.jsx(EM.Provider,Object.assign({value:a},{children:n}),void 0)});function LH(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=$H(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function $H(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:MM(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=t;return s[xp]||(s[xp]={dragDropManager:_H(e,t,n,r)}),s[xp]}function MM(){return typeof global<"u"?global:window}function BH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function zH(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function JH(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!v.isValidElement(t)){var r=t;return e(r,n),r}var s=t;GH(s);var o=n?function(a){return e(a,n)}:e;return QH(s,o)}}function OM(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var s=JH(r);t[n]=function(){return s}}}),t}function n1(e,t){typeof e=="function"?e(t):e.current=t}function QH(e,t){var n=e.ref;return Ve(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?v.cloneElement(e,{ref:function(s){n1(n,s),n1(t,s)}}):v.cloneElement(e,{ref:t})}function wp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wp=function(n){return typeof n}:wp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},wp(e)}function ob(e){return e!==null&&wp(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function ab(e,t,n,r){var s=void 0;if(s!==void 0)return!!s;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var o=Object.keys(e),a=Object.keys(t);if(o.length!==a.length)return!1;for(var l=Object.prototype.hasOwnProperty.bind(t),c=0;ce.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=oK(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e}(),dK=DM(function(){return/firefox/i.test(navigator.userAgent)}),AM=DM(function(){return!!window.safari});function fK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pK(e,t){for(var n=0;nn)d=p-1;else return s[p]}c=Math.max(0,d);var h=n-r[c],g=h*h;return s[c]+o[c]*h+a[c]*g+l[c]*h*g}}]),e}(),gK=1;function FM(e){var t=e.nodeType===gK?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,s=n.left;return{x:s,y:r}}function Bf(e){return{x:e.clientX,y:e.clientY}}function mK(e){var t;return e.nodeName==="IMG"&&(dK()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function vK(e,t,n,r){var s=e?t.width:n,o=e?t.height:r;return AM()&&e&&(o/=window.devicePixelRatio,s/=window.devicePixelRatio),{dragPreviewWidth:s,dragPreviewHeight:o}}function yK(e,t,n,r,s){var o=mK(t),a=o?e:t,l=FM(a),c={x:n.x-l.x,y:n.y-l.y},i=e.offsetWidth,d=e.offsetHeight,p=r.anchorX,f=r.anchorY,h=vK(o,t,i,d),g=h.dragPreviewWidth,m=h.dragPreviewHeight,x=function(){var k=new u1([0,.5,1],[c.y,c.y/d*m,c.y+m-d]),T=k.interpolate(f);return AM()&&o&&(T+=(window.devicePixelRatio-1)*m),T},b=function(){var k=new u1([0,.5,1],[c.x,c.x/i*g,c.x+g-i]);return k.interpolate(p)},y=s.offsetX,w=s.offsetY,S=y===0||y,E=w===0||w;return{x:S?y:b(),y:E?w:x()}}var LM="__NATIVE_FILE__",$M="__NATIVE_URL__",BM="__NATIVE_TEXT__",zM="__NATIVE_HTML__";const c1=Object.freeze(Object.defineProperty({__proto__:null,FILE:LM,HTML:zM,TEXT:BM,URL:$M},Symbol.toStringTag,{value:"Module"}));function av(e,t,n){var r=t.reduce(function(s,o){return s||e.getData(o)},"");return r??n}var Qi;function zf(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var lb=(Qi={},zf(Qi,LM,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),zf(Qi,zM,{exposeProperties:{html:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),zf(Qi,$M,{exposeProperties:{urls:function(t,n){return av(t,n,"").split(` -`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),zf(Qi,BM,{exposeProperties:{text:function(t,n){return av(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),Qi);function bK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xK(e,t){for(var n=0;n-1})})[0]||null}function EK(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function TK(e,t){for(var n=0;n0&&s.actions.hover(a,{clientOffset:Bf(o)});var l=a.some(function(c){return s.monitor.canDropOnTarget(c)});l&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect()))}}),st(this,"handleTopDragOverCapture",function(){s.dragOverTargetIds=[]}),st(this,"handleTopDragOver",function(o){var a=s.dragOverTargetIds;if(s.dragOverTargetIds=[],!s.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}s.altKeyPressed=o.altKey,s.lastClientOffset=Bf(o),s.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(s.hoverRafId=requestAnimationFrame(function(){s.monitor.isDragging()&&s.actions.hover(a||[],{clientOffset:s.lastClientOffset}),s.hoverRafId=null}));var l=(a||[]).some(function(c){return s.monitor.canDropOnTarget(c)});l?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect())):s.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))}),st(this,"handleTopDragLeaveCapture",function(o){s.isDraggingNativeItem()&&o.preventDefault();var a=s.enterLeaveCounter.leave(o.target);a&&s.isDraggingNativeItem()&&setTimeout(function(){return s.endDragNativeItem()},0)}),st(this,"handleTopDropCapture",function(o){if(s.dropTargetIds=[],s.isDraggingNativeItem()){var a;o.preventDefault(),(a=s.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else iv(o.dataTransfer)&&o.preventDefault();s.enterLeaveCounter.reset()}),st(this,"handleTopDrop",function(o){var a=s.dropTargetIds;s.dropTargetIds=[],s.actions.hover(a,{clientOffset:Bf(o)}),s.actions.drop({dropEffect:s.getCurrentDropEffect()}),s.isDraggingNativeItem()?s.endDragNativeItem():s.monitor.isDragging()&&s.actions.endDrag()}),st(this,"handleSelectStart",function(o){var a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))}),this.options=new _K(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new cK(this.isNodeInDocument)}return PK(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,s){var o=this;return this.sourcePreviewNodeOptions.set(n,s),this.sourcePreviewNodes.set(n,r),function(){o.sourcePreviewNodes.delete(n),o.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,s){var o=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,s);var a=function(i){return o.handleDragStart(i,n)},l=function(i){return o.handleSelectStart(i)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",a),r.addEventListener("selectstart",l),function(){o.sourceNodes.delete(n),o.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",a),r.removeEventListener("selectstart",l),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var s=this,o=function(i){return s.handleDragEnter(i,n)},a=function(i){return s.handleDragOver(i,n)},l=function(i){return s.handleDrop(i,n)};return r.addEventListener("dragenter",o),r.addEventListener("dragover",a),r.addEventListener("drop",l),function(){r.removeEventListener("dragenter",o),r.removeEventListener("dragover",a),r.removeEventListener("drop",l)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return p1({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return p1({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(c1).some(function(r){return c1[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=CK(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var s=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var o;return(o=r.rootElement)===null||o===void 0?void 0:o.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},s)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e}(),OK=function(t,n,r){return new MK(t,n,r)},NK=Object.create,UM=Object.defineProperty,IK=Object.getOwnPropertyDescriptor,VM=Object.getOwnPropertyNames,DK=Object.getPrototypeOf,AK=Object.prototype.hasOwnProperty,FK=(e,t)=>function(){return t||(0,e[VM(e)[0]])((t={exports:{}}).exports,t),t.exports},LK=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of VM(t))!AK.call(e,s)&&s!==n&&UM(e,s,{get:()=>t[s],enumerable:!(r=IK(t,s))||r.enumerable});return e},HM=(e,t,n)=>(n=e!=null?NK(DK(e)):{},LK(UM(n,"default",{value:e,enumerable:!0}),e)),KM=FK({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var s=[],o=0;o-1}var Wq=qq,Gq=9007199254740991,Jq=/^(?:0|[1-9]\d*)$/;function Qq(e,t){var n=typeof e;return t=t??Gq,!!t&&(n=="number"||n!="symbol"&&Jq.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Xq}var YM=eW;function tW(e){return e!=null&&YM(e.length)&&!QM(e)}var nW=tW,rW=Object.prototype;function sW(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||rW;return e===n}var oW=sW;function aW(e,t){for(var n=-1,r=Array(e);++n-1}var FG=AG;function LG(e,t){var n=this.__data__,r=Ag(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var $G=LG;function Eu(e){var t=-1,n=e==null?0:e.length;for(this.clear();++tl))return!1;var i=o.get(e),d=o.get(t);if(i&&d)return i==t&&d==e;var p=-1,f=!0,h=n&q9?new oO:void 0;for(o.set(e,t),o.set(t,e);++p":">",'"':""","'":"'"},TJ=s9(EJ),kJ=TJ,uO=/[&<>"']/g,_J=RegExp(uO.source);function jJ(e){return e=sO(e),e&&_J.test(e)?e.replace(uO,kJ):e}var RJ=jJ,cO=/[\\^$.*+?()[\]{}|]/g,PJ=RegExp(cO.source);function MJ(e){return e=sO(e),e&&PJ.test(e)?e.replace(cO,"\\$&"):e}var OJ=MJ;function NJ(e,t){return wJ(e,t)}var IJ=NJ,DJ=1/0,AJ=Pl&&1/Rw(new Pl([,-0]))[1]==DJ?function(e){return new Pl(e)}:Fq,FJ=AJ,LJ=200;function $J(e,t,n){var r=-1,s=Wq,o=e.length,a=!0,l=[],c=l;if(n)a=!1,s=CJ;else if(o>=LJ){var i=t?null:FJ(e);if(i)return Rw(i);a=!1,s=aO,c=new oO}else c=t?[]:l;e:for(;++ru.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),HJ=VJ,KJ=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,s=e.offsetTop-t.scrollTop;s+r>=n?t.scrollTop+=s-n+r:s<0&&(t.scrollTop+=s)},pb=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,qJ=e=>{const t=v.createRef(),{labelField:n,minQueryLength:r,isFocused:s,classNames:o,selectedIndex:a,query:l}=e;v.useEffect(()=>{if(!t.current)return;const p=t.current.querySelector(`.${o.activeSuggestion}`);p&&KJ(p,t.current)},[a]);const c=(p,f)=>{const h=f.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:g}=p;return{__html:g.replace(RegExp(h,"gi"),m=>`${RJ(m)}`)}},i=(p,f)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(p,f):u.jsx("span",{dangerouslySetInnerHTML:c(p,f)}),d=e.suggestions.map((p,f)=>u.jsx("li",{onMouseDown:e.handleClick.bind(null,f),onTouchStart:e.handleClick.bind(null,f),onMouseOver:e.handleHover.bind(null,f),className:f===e.selectedIndex?e.classNames.activeSuggestion:"",children:i(p,e.query)},f));return d.length===0||!pb(l,r||2,s,e.shouldRenderSuggestions)?null:u.jsx("div",{ref:t,className:o.suggestions,"data-testid":"suggestions",children:u.jsxs("ul",{children:[" ",d," "]})})},WJ=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:s,suggestions:o}=t;return!!(e.isFocused===s&&IJ(e.suggestions,o)&&pb(n,r,s,t.shouldRenderSuggestions)===pb(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},GJ=v.memo(qJ,WJ),JJ=GJ,QJ=HM(KM()),ZJ=HM(KM());function YJ(e){const t=e.map(r=>{const s=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?s:r)}).join(""),n=OJ(t);return new RegExp(`[${n}]+`)}function XJ(e){switch(e){case Rs.ENTER:return[10,13];case Rs.TAB:return 9;case Rs.COMMA:return 188;case Rs.SPACE:return 32;case Rs.SEMICOLON:return 186;default:return 0}}function $1(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function eQ(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var tQ=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:s,tag:o,index:a}=e,l=i=>{if(Rl.ENTER.includes(i.keyCode)||i.keyCode===Rl.SPACE){i.preventDefault(),i.stopPropagation();return}i.keyCode===Rl.BACKSPACE&&r(i)};if(t)return u.jsx("span",{});const c=`Tag at index ${a} with value ${o.id} focussed. Press backspace to remove`;if(n){const i=n;return u.jsx(i,{"data-testid":"remove",onRemove:r,onKeyDown:l,className:s,"aria-label":c,tag:o,index:a})}return u.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:l,className:s,type:"button","aria-label":c,children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:u.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},nQ=tQ,B1={TAG:"tag"},rQ=e=>{const t=v.useRef(null),{readOnly:n=!1,tag:r,classNames:s,index:o,moveTag:a,allowDragDrop:l=!0,labelField:c="text",tags:i}=e,[{isDragging:d},p]=U7(()=>({type:B1.TAG,collect:x=>({isDragging:!!x.isDragging()}),item:e,canDrag:()=>$1({moveTag:a,readOnly:n,allowDragDrop:l})}),[i]),[,f]=sK(()=>({accept:B1.TAG,drop:x=>{var w;const b=x.index,y=o;b!==y&&((w=e==null?void 0:e.moveTag)==null||w.call(e,b,y))},canDrop:x=>eQ(x)}),[i]);p(f(t));const h=e.tag[c],{className:g=""}=r,m=d?0:1;return u.jsxs("span",{ref:t,className:(0,ZJ.default)("tag-wrapper",s.tag,g),style:{opacity:m,cursor:$1({moveTag:a,readOnly:n,allowDragDrop:l})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[h,u.jsx(nQ,{tag:e.tag,className:s.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:o})]})},sQ=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:s,allowDeleteFromEmptyInput:o,allowAdditionFromPaste:a,allowDragDrop:l,minQueryLength:c,shouldRenderSuggestions:i,removeComponent:d,autocomplete:p,inline:f,maxTags:h,allowUnique:g,editable:m,placeholder:x,delimiters:b,separators:y,tags:w,inputFieldPosition:S,inputProps:E,classNames:C,maxLength:k,inputValue:T,clearAll:P}=e,[N,U]=v.useState(e.suggestions),[I,Z]=v.useState(""),[V,Q]=v.useState(!1),[ee,W]=v.useState(-1),[F,A]=v.useState(!1),[Y,de]=v.useState(""),[z,se]=v.useState(-1),[ne,ie]=v.useState(""),oe=v.createRef(),J=v.useRef(null),Ce=v.useRef(null);v.useEffect(()=>{b.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),v.useEffect(()=>{typeof f<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[f]),v.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Me()},[n,n,r]),v.useEffect(()=>{Wt()},[I,e.suggestions]);const Pe=ue=>{let Ue=e.suggestions.slice();if(g){const _n=w.map(ms=>ms.id.trim().toLowerCase());Ue=Ue.filter(ms=>!_n.includes(ms.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(ue,Ue);const St=Ue.filter(_n=>Le(ue,_n)===0),dt=Ue.filter(_n=>Le(ue,_n)>0);return St.concat(dt)},Le=(ue,Ue)=>Ue[s].toLowerCase().indexOf(ue.toLowerCase()),Me=()=>{Z(""),J.current&&(J.current.value="",J.current.focus())},me=(ue,Ue)=>{var dt;Ue.preventDefault(),Ue.stopPropagation();const St=w.slice();St.length!==0&&(ie(""),(dt=e==null?void 0:e.handleDelete)==null||dt.call(e,ue,Ue),rt(ue,St))},rt=(ue,Ue)=>{var _n;if(!(oe!=null&&oe.current))return;const St=oe.current.querySelectorAll(".ReactTags__remove");let dt="";ue===0&&Ue.length>1?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index 0 with value ${Ue[1].id} focussed. Press backspace to remove`,St[0].focus()):ue>0?(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Tag at index ${ue-1} with value ${Ue[ue-1].id} focussed. Press backspace to remove`,St[ue-1].focus()):(dt=`Tag at index ${ue} with value ${Ue[ue].id} deleted. Input focussed. Press enter to add a new tag`,(_n=J.current)==null||_n.focus()),de(dt)},It=(ue,Ue,St)=>{var dt,_n;r||(m&&(se(ue),Z(Ue[s]),(dt=Ce.current)==null||dt.focus()),(_n=e.handleTagClick)==null||_n.call(e,ue,St))},Zt=ue=>{e.handleInputChange&&e.handleInputChange(ue.target.value,ue);const Ue=ue.target.value.trim();Z(Ue)},Wt=()=>{const ue=Pe(I);U(ue),W(ee>=ue.length?ue.length-1:ee)},an=ue=>{const Ue=ue.target.value;e.handleInputFocus&&e.handleInputFocus(Ue,ue),Q(!0)},j=ue=>{const Ue=ue.target.value;e.handleInputBlur&&(e.handleInputBlur(Ue,ue),J.current&&(J.current.value="")),Q(!1),se(-1)},D=ue=>{if(ue.key==="Escape"&&(ue.preventDefault(),ue.stopPropagation(),W(-1),A(!1),U([]),se(-1)),(y.indexOf(ue.key)!==-1||b.indexOf(ue.keyCode)!==-1)&&!ue.shiftKey){(ue.keyCode!==Rl.TAB||I!=="")&&ue.preventDefault();const Ue=F&&ee!==-1?N[ee]:{id:I.trim(),[s]:I.trim(),className:""};Object.keys(Ue)&&le(Ue)}ue.key==="Backspace"&&I===""&&(o||S===ec.INLINE)&&me(w.length-1,ue),ue.keyCode===Rl.UP_ARROW&&(ue.preventDefault(),W(ee<=0?N.length-1:ee-1),A(!0)),ue.keyCode===Rl.DOWN_ARROW&&(ue.preventDefault(),A(!0),N.length===0?W(-1):W((ee+1)%N.length))},B=()=>h&&w.length>=h,pe=ue=>{if(!a)return;if(B()){ie(g1.TAG_LIMIT),Me();return}ie(""),ue.preventDefault();const Ue=ue.clipboardData||window.clipboardData,St=Ue.getData("text"),{maxLength:dt=St.length}=e,_n=Math.min(dt,St.length),ms=Ue.getData("text").substr(0,_n);let Ro=b;y.length&&(Ro=[],y.forEach(vs=>{const Du=XJ(vs);Array.isArray(Du)?Ro=[...Ro,...Du]:Ro.push(Du)}));const Iu=YJ(Ro),$i=ms.split(Iu).map(vs=>vs.trim());UJ($i).forEach(vs=>le({id:vs.trim(),[s]:vs.trim(),className:""}))},le=ue=>{var St;if(!ue.id||!ue[s])return;if(z===-1){if(B()){ie(g1.TAG_LIMIT),Me();return}ie("")}const Ue=w.map(dt=>dt.id.toLowerCase());if(!(g&&Ue.indexOf(ue.id.trim().toLowerCase())>=0)){if(p){const dt=Pe(ue[s]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(p===1&&dt.length===1||p===!0&&dt.length)&&(ue=dt[0])}z!==-1&&e.onTagUpdate?e.onTagUpdate(z,ue):(St=e==null?void 0:e.handleAddition)==null||St.call(e,ue),Z(""),A(!1),W(-1),se(-1),Me()}},ae=ue=>{le(N[ue])},Ee=()=>{e.onClearAll&&e.onClearAll(),ie(""),Me()},et=ue=>{W(ue),A(!0)},kt=(ue,Ue)=>{var dt;const St=w[ue];(dt=e==null?void 0:e.handleDrag)==null||dt.call(e,St,ue,Ue)},yn=(()=>{const ue={...h1,...e.classNames};return w.map((Ue,St)=>u.jsx(v.Fragment,{children:z===St?u.jsx("div",{className:ue.editTagInput,children:u.jsx("input",{ref:dt=>{Ce.current=dt},onFocus:an,value:I,onChange:Zt,onKeyDown:D,onBlur:j,className:ue.editTagInputField,onPaste:pe,"data-testid":"tag-edit"})}):u.jsx(rQ,{index:St,tag:Ue,tags:w,labelField:s,onDelete:dt=>me(St,dt),moveTag:l?kt:void 0,removeComponent:d,onTagClicked:dt=>It(St,Ue,dt),readOnly:r,classNames:ue,allowDragDrop:l})},St))})(),gn={...h1,...C},{name:jo,id:gs}=e,Aa=f===!1?ec.BOTTOM:S,Fn=r?null:u.jsxs("div",{className:gn.tagInput,children:[u.jsx("input",{...E,ref:ue=>{J.current=ue},className:gn.tagInputField,type:"text",placeholder:x,"aria-label":x,onFocus:an,onBlur:j,onChange:Zt,onKeyDown:D,onPaste:pe,name:jo,id:gs,maxLength:k,value:T,"data-automation":"input","data-testid":"input"}),u.jsx(JJ,{query:I.trim(),suggestions:N,labelField:s,selectedIndex:ee,handleClick:ae,handleHover:et,minQueryLength:c,shouldRenderSuggestions:i,isFocused:V,classNames:gn,renderSuggestion:e.renderSuggestion}),P&&w.length>0&&u.jsx(HJ,{classNames:gn,onClick:Ee}),ne&&u.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:u.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),ne]})]});return u.jsxs("div",{className:(0,QJ.default)(gn.tags,"react-tags-wrapper"),ref:oe,children:[u.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:Y}),Aa===ec.TOP&&Fn,u.jsxs("div",{className:gn.selected,children:[yn,Aa===ec.INLINE&&Fn]}),Aa===ec.BOTTOM&&Fn]})},oQ=sQ,aQ=e=>{var ne;const{placeholder:t=$K,labelField:n=BK,suggestions:r=[],delimiters:s=[],separators:o=(ne=e.delimiters)!=null&&ne.length?[]:[Rs.ENTER,Rs.TAB],autofocus:a,autoFocus:l=!0,inline:c,inputFieldPosition:i="inline",allowDeleteFromEmptyInput:d=!1,allowAdditionFromPaste:p=!0,autocomplete:f=!1,readOnly:h=!1,allowUnique:g=!0,allowDragDrop:m=!0,tags:x=[],inputProps:b={},editable:y=!1,clearAll:w=!1,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:P,handleInputChange:N,handleInputFocus:U,handleInputBlur:I,minQueryLength:Z,shouldRenderSuggestions:V,removeComponent:Q,onClearAll:ee,classNames:W,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se}=e;return u.jsx(oQ,{placeholder:t,labelField:n,suggestions:r,delimiters:s,separators:o,autofocus:a,autoFocus:l,inline:c,inputFieldPosition:i,allowDeleteFromEmptyInput:d,allowAdditionFromPaste:p,autocomplete:f,readOnly:h,allowUnique:g,allowDragDrop:m,tags:x,inputProps:b,editable:y,clearAll:w,handleDelete:S,handleAddition:E,onTagUpdate:C,handleDrag:k,handleFilterSuggestions:T,handleTagClick:P,handleInputChange:N,handleInputFocus:U,handleInputBlur:I,minQueryLength:Z,shouldRenderSuggestions:V,removeComponent:Q,onClearAll:ee,classNames:W,name:F,id:A,maxLength:Y,inputValue:de,maxTags:z,renderSuggestion:se})},iQ=({...e})=>u.jsx(FH,{backend:OK,children:u.jsx(aQ,{...e})});/*! Bundled license information: - -classnames/index.js: - (*! - Copyright (c) 2018 Jed Watson. - Licensed under the MIT License (MIT), see - http://jedwatson.github.io/classnames - *) - -lodash-es/lodash.js: - (** - * @license - * Lodash (Custom Build) - * Build: `lodash modularize exports="es" -o ./` - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - *) -*/var lQ="Label",dO=v.forwardRef((e,t)=>u.jsx(Ne.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));dO.displayName=lQ;var fO=dO;const uQ=ig("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),pO=v.forwardRef(({className:e,...t},n)=>u.jsx(fO,{ref:n,className:ge(uQ(),e),...t}));pO.displayName=fO.displayName;function hO(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var cQ="VisuallyHidden",gO=v.forwardRef((e,t)=>u.jsx(Ne.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));gO.displayName=cQ;var dQ=[" ","Enter","ArrowUp","ArrowDown"],fQ=[" ","Enter"],ef="Select",[$g,Bg,pQ]=Fx(ef),[_u,Xse]=Vr(ef,[pQ,hg]),zg=hg(),[hQ,Ma]=_u(ef),[gQ,mQ]=_u(ef),mO=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:l,onValueChange:c,dir:i,name:d,autoComplete:p,disabled:f,required:h}=e,g=zg(t),[m,x]=v.useState(null),[b,y]=v.useState(null),[w,S]=v.useState(!1),E=Gd(i),[C=!1,k]=pa({prop:r,defaultProp:s,onChange:o}),[T,P]=pa({prop:a,defaultProp:l,onChange:c}),N=v.useRef(null),U=m?!!m.closest("form"):!0,[I,Z]=v.useState(new Set),V=Array.from(I).map(Q=>Q.props.value).join(";");return u.jsx($j,{...g,children:u.jsxs(hQ,{required:h,scope:t,trigger:m,onTriggerChange:x,valueNode:b,onValueNodeChange:y,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:os(),value:T,onValueChange:P,open:C,onOpenChange:k,dir:E,triggerPointerDownPosRef:N,disabled:f,children:[u.jsx($g.Provider,{scope:t,children:u.jsx(gQ,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(Q=>{Z(ee=>new Set(ee).add(Q))},[]),onNativeOptionRemove:v.useCallback(Q=>{Z(ee=>{const W=new Set(ee);return W.delete(Q),W})},[]),children:n})}),U?u.jsxs(zO,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:p,value:T,onChange:Q=>P(Q.target.value),disabled:f,children:[T===void 0?u.jsx("option",{value:""}):null,Array.from(I)]},V):null]})})};mO.displayName=ef;var vO="SelectTrigger",yO=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=zg(n),a=Ma(vO,n),l=a.disabled||r,c=it(t,a.onTriggerChange),i=Bg(n),[d,p,f]=UO(g=>{const m=i().filter(y=>!y.disabled),x=m.find(y=>y.value===a.value),b=VO(m,g,x);b!==void 0&&a.onValueChange(b.value)}),h=()=>{l||(a.onOpenChange(!0),f())};return u.jsx(Bj,{asChild:!0,...o,children:u.jsx(Ne.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":BO(a.value)?"":void 0,...s,ref:c,onClick:Se(s.onClick,g=>{g.currentTarget.focus()}),onPointerDown:Se(s.onPointerDown,g=>{const m=g.target;m.hasPointerCapture(g.pointerId)&&m.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&(h(),a.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)},g.preventDefault())}),onKeyDown:Se(s.onKeyDown,g=>{const m=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(m&&g.key===" ")&&dQ.includes(g.key)&&(h(),g.preventDefault())})})})});yO.displayName=vO;var bO="SelectValue",xO=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...l}=e,c=Ma(bO,n),{onValueNodeHasChildrenChange:i}=c,d=o!==void 0,p=it(t,c.onValueNodeChange);return fn(()=>{i(d)},[i,d]),u.jsx(Ne.span,{...l,ref:p,style:{pointerEvents:"none"},children:BO(c.value)?u.jsx(u.Fragment,{children:a}):o})});xO.displayName=bO;var vQ="SelectIcon",wO=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return u.jsx(Ne.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});wO.displayName=vQ;var yQ="SelectPortal",SO=e=>u.jsx(gg,{asChild:!0,...e});SO.displayName=yQ;var ji="SelectContent",CO=v.forwardRef((e,t)=>{const n=Ma(ji,e.__scopeSelect),[r,s]=v.useState();if(fn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?ka.createPortal(u.jsx(EO,{scope:e.__scopeSelect,children:u.jsx($g.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),o):null}return u.jsx(TO,{...e,ref:t})});CO.displayName=ji;var Ys=10,[EO,Oa]=_u(ji),bQ="SelectContentImpl",TO=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:l,sideOffset:c,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x,...b}=e,y=Ma(ji,n),[w,S]=v.useState(null),[E,C]=v.useState(null),k=it(t,J=>S(J)),[T,P]=v.useState(null),[N,U]=v.useState(null),I=Bg(n),[Z,V]=v.useState(!1),Q=v.useRef(!1);v.useEffect(()=>{if(w)return Wx(w)},[w]),Lx();const ee=v.useCallback(J=>{const[Ce,...Pe]=I().map(me=>me.ref.current),[Le]=Pe.slice(-1),Me=document.activeElement;for(const me of J)if(me===Me||(me==null||me.scrollIntoView({block:"nearest"}),me===Ce&&E&&(E.scrollTop=0),me===Le&&E&&(E.scrollTop=E.scrollHeight),me==null||me.focus(),document.activeElement!==Me))return},[I,E]),W=v.useCallback(()=>ee([T,w]),[ee,T,w]);v.useEffect(()=>{Z&&W()},[Z,W]);const{onOpenChange:F,triggerPointerDownPosRef:A}=y;v.useEffect(()=>{if(w){let J={x:0,y:0};const Ce=Le=>{var Me,me;J={x:Math.abs(Math.round(Le.pageX)-(((Me=A.current)==null?void 0:Me.x)??0)),y:Math.abs(Math.round(Le.pageY)-(((me=A.current)==null?void 0:me.y)??0))}},Pe=Le=>{J.x<=10&&J.y<=10?Le.preventDefault():w.contains(Le.target)||F(!1),document.removeEventListener("pointermove",Ce),A.current=null};return A.current!==null&&(document.addEventListener("pointermove",Ce),document.addEventListener("pointerup",Pe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ce),document.removeEventListener("pointerup",Pe,{capture:!0})}}},[w,F,A]),v.useEffect(()=>{const J=()=>F(!1);return window.addEventListener("blur",J),window.addEventListener("resize",J),()=>{window.removeEventListener("blur",J),window.removeEventListener("resize",J)}},[F]);const[Y,de]=UO(J=>{const Ce=I().filter(Me=>!Me.disabled),Pe=Ce.find(Me=>Me.ref.current===document.activeElement),Le=VO(Ce,J,Pe);Le&&setTimeout(()=>Le.ref.current.focus())}),z=v.useCallback((J,Ce,Pe)=>{const Le=!Q.current&&!Pe;(y.value!==void 0&&y.value===Ce||Le)&&(P(J),Le&&(Q.current=!0))},[y.value]),se=v.useCallback(()=>w==null?void 0:w.focus(),[w]),ne=v.useCallback((J,Ce,Pe)=>{const Le=!Q.current&&!Pe;(y.value!==void 0&&y.value===Ce||Le)&&U(J)},[y.value]),ie=r==="popper"?hb:kO,oe=ie===hb?{side:l,sideOffset:c,align:i,alignOffset:d,arrowPadding:p,collisionBoundary:f,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:x}:{};return u.jsx(EO,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:z,selectedItem:T,onItemLeave:se,itemTextRefCallback:ne,focusSelectedItem:W,selectedItemText:N,position:r,isPositioned:Z,searchRef:Y,children:u.jsx(bg,{as:mo,allowPinchZoom:!0,children:u.jsx(dg,{asChild:!0,trapped:y.open,onMountAutoFocus:J=>{J.preventDefault()},onUnmountAutoFocus:Se(s,J=>{var Ce;(Ce=y.trigger)==null||Ce.focus({preventScroll:!0}),J.preventDefault()}),children:u.jsx(cg,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:J=>J.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:u.jsx(ie,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:J=>J.preventDefault(),...b,...oe,onPlaced:()=>V(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Se(b.onKeyDown,J=>{const Ce=J.ctrlKey||J.altKey||J.metaKey;if(J.key==="Tab"&&J.preventDefault(),!Ce&&J.key.length===1&&de(J.key),["ArrowUp","ArrowDown","Home","End"].includes(J.key)){let Le=I().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(J.key)&&(Le=Le.slice().reverse()),["ArrowUp","ArrowDown"].includes(J.key)){const Me=J.target,me=Le.indexOf(Me);Le=Le.slice(me+1)}setTimeout(()=>ee(Le)),J.preventDefault()}})})})})})})});TO.displayName=bQ;var xQ="SelectItemAlignedPosition",kO=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Ma(ji,n),a=Oa(ji,n),[l,c]=v.useState(null),[i,d]=v.useState(null),p=it(t,k=>d(k)),f=Bg(n),h=v.useRef(!1),g=v.useRef(!0),{viewport:m,selectedItem:x,selectedItemText:b,focusSelectedItem:y}=a,w=v.useCallback(()=>{if(o.trigger&&o.valueNode&&l&&i&&m&&x&&b){const k=o.trigger.getBoundingClientRect(),T=i.getBoundingClientRect(),P=o.valueNode.getBoundingClientRect(),N=b.getBoundingClientRect();if(o.dir!=="rtl"){const Me=N.left-T.left,me=P.left-Me,rt=k.left-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);l.style.minWidth=It+"px",l.style.left=an+"px"}else{const Me=T.right-N.right,me=window.innerWidth-P.right-Me,rt=window.innerWidth-k.right-me,It=k.width+rt,Zt=Math.max(It,T.width),Wt=window.innerWidth-Ys,an=Zy(me,[Ys,Wt-Zt]);l.style.minWidth=It+"px",l.style.right=an+"px"}const U=f(),I=window.innerHeight-Ys*2,Z=m.scrollHeight,V=window.getComputedStyle(i),Q=parseInt(V.borderTopWidth,10),ee=parseInt(V.paddingTop,10),W=parseInt(V.borderBottomWidth,10),F=parseInt(V.paddingBottom,10),A=Q+ee+Z+F+W,Y=Math.min(x.offsetHeight*5,A),de=window.getComputedStyle(m),z=parseInt(de.paddingTop,10),se=parseInt(de.paddingBottom,10),ne=k.top+k.height/2-Ys,ie=I-ne,oe=x.offsetHeight/2,J=x.offsetTop+oe,Ce=Q+ee+J,Pe=A-Ce;if(Ce<=ne){const Me=x===U[U.length-1].ref.current;l.style.bottom="0px";const me=i.clientHeight-m.offsetTop-m.offsetHeight,rt=Math.max(ie,oe+(Me?se:0)+me+W),It=Ce+rt;l.style.height=It+"px"}else{const Me=x===U[0].ref.current;l.style.top="0px";const rt=Math.max(ne,Q+m.offsetTop+(Me?z:0)+oe)+Pe;l.style.height=rt+"px",m.scrollTop=Ce-ne+m.offsetTop}l.style.margin=`${Ys}px 0`,l.style.minHeight=Y+"px",l.style.maxHeight=I+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[f,o.trigger,o.valueNode,l,i,m,x,b,o.dir,r]);fn(()=>w(),[w]);const[S,E]=v.useState();fn(()=>{i&&E(window.getComputedStyle(i).zIndex)},[i]);const C=v.useCallback(k=>{k&&g.current===!0&&(w(),y==null||y(),g.current=!1)},[w,y]);return u.jsx(SQ,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:h,onScrollButtonChange:C,children:u.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:u.jsx(Ne.div,{...s,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});kO.displayName=xQ;var wQ="SelectPopperPosition",hb=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Ys,...o}=e,a=zg(n);return u.jsx(zj,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});hb.displayName=wQ;var[SQ,Pw]=_u(ji,{}),gb="SelectViewport",_O=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Oa(gb,n),a=Pw(gb,n),l=it(t,o.onViewportChange),c=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx($g.Slot,{scope:n,children:u.jsx(Ne.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:Se(s.onScroll,i=>{const d=i.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:f}=a;if(f!=null&&f.current&&p){const h=Math.abs(c.current-d.scrollTop);if(h>0){const g=window.innerHeight-Ys*2,m=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),b=Math.max(m,x);if(b0?S:0,p.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});_O.displayName=gb;var jO="SelectGroup",[CQ,EQ]=_u(jO),TQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=os();return u.jsx(CQ,{scope:n,id:s,children:u.jsx(Ne.div,{role:"group","aria-labelledby":s,...r,ref:t})})});TQ.displayName=jO;var RO="SelectLabel",PO=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=EQ(RO,n);return u.jsx(Ne.div,{id:s.id,...r,ref:t})});PO.displayName=RO;var Th="SelectItem",[kQ,MO]=_u(Th),OO=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,l=Ma(Th,n),c=Oa(Th,n),i=l.value===r,[d,p]=v.useState(o??""),[f,h]=v.useState(!1),g=it(t,b=>{var y;return(y=c.itemRefCallback)==null?void 0:y.call(c,b,r,s)}),m=os(),x=()=>{s||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(kQ,{scope:n,value:r,disabled:s,textId:m,isSelected:i,onItemTextChange:v.useCallback(b=>{p(y=>y||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx($g.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:u.jsx(Ne.div,{role:"option","aria-labelledby":m,"data-highlighted":f?"":void 0,"aria-selected":i&&f,"data-state":i?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:g,onFocus:Se(a.onFocus,()=>h(!0)),onBlur:Se(a.onBlur,()=>h(!1)),onPointerUp:Se(a.onPointerUp,x),onPointerMove:Se(a.onPointerMove,b=>{var y;s?(y=c.onItemLeave)==null||y.call(c):b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Se(a.onPointerLeave,b=>{var y;b.currentTarget===document.activeElement&&((y=c.onItemLeave)==null||y.call(c))}),onKeyDown:Se(a.onKeyDown,b=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&b.key===" "||(fQ.includes(b.key)&&x(),b.key===" "&&b.preventDefault())})})})})});OO.displayName=Th;var hc="SelectItemText",NO=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=Ma(hc,n),l=Oa(hc,n),c=MO(hc,n),i=mQ(hc,n),[d,p]=v.useState(null),f=it(t,b=>p(b),c.onItemTextChange,b=>{var y;return(y=l.itemTextRefCallback)==null?void 0:y.call(l,b,c.value,c.disabled)}),h=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:x}=i;return fn(()=>(m(g),()=>x(g)),[m,x,g]),u.jsxs(u.Fragment,{children:[u.jsx(Ne.span,{id:c.textId,...o,ref:f}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren?ka.createPortal(o.children,a.valueNode):null]})});NO.displayName=hc;var IO="SelectItemIndicator",DO=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return MO(IO,n).isSelected?u.jsx(Ne.span,{"aria-hidden":!0,...r,ref:t}):null});DO.displayName=IO;var mb="SelectScrollUpButton",AO=v.forwardRef((e,t)=>{const n=Oa(mb,e.__scopeSelect),r=Pw(mb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const i=c.scrollTop>0;o(i)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?u.jsx(LO,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});AO.displayName=mb;var vb="SelectScrollDownButton",FO=v.forwardRef((e,t)=>{const n=Oa(vb,e.__scopeSelect),r=Pw(vb,e.__scopeSelect),[s,o]=v.useState(!1),a=it(t,r.onScrollButtonChange);return fn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const i=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?u.jsx(LO,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});FO.displayName=vb;var LO=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Oa("SelectScrollButton",n),a=v.useRef(null),l=Bg(n),c=v.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return v.useEffect(()=>()=>c(),[c]),fn(()=>{var d;const i=l().find(p=>p.ref.current===document.activeElement);(d=i==null?void 0:i.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),u.jsx(Ne.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Se(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:Se(s.onPointerMove,()=>{var i;(i=o.onItemLeave)==null||i.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:Se(s.onPointerLeave,()=>{c()})})}),_Q="SelectSeparator",$O=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Ne.div,{"aria-hidden":!0,...r,ref:t})});$O.displayName=_Q;var yb="SelectArrow",jQ=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=zg(n),o=Ma(yb,n),a=Oa(yb,n);return o.open&&a.position==="popper"?u.jsx(Uj,{...s,...r,ref:t}):null});jQ.displayName=yb;function BO(e){return e===""||e===void 0}var zO=v.forwardRef((e,t)=>{const{value:n,...r}=e,s=v.useRef(null),o=it(t,s),a=hO(n);return v.useEffect(()=>{const l=s.current,c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(a!==n&&d){const p=new Event("change",{bubbles:!0});d.call(l,n),l.dispatchEvent(p)}},[a,n]),u.jsx(gO,{asChild:!0,children:u.jsx("select",{...r,ref:o,defaultValue:n})})});zO.displayName="BubbleSelect";function UO(e){const t=nn(e),n=v.useRef(""),r=v.useRef(0),s=v.useCallback(a=>{const l=n.current+a;t(l),function c(i){n.current=i,window.clearTimeout(r.current),i!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),o=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function VO(e,t,n){const s=t.length>1&&Array.from(t).every(i=>i===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=RQ(e,Math.max(o,0));s.length===1&&(a=a.filter(i=>i!==n));const c=a.find(i=>i.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var PQ=mO,HO=yO,MQ=xO,OQ=wO,NQ=SO,KO=CO,IQ=_O,qO=PO,WO=OO,DQ=NO,AQ=DO,GO=AO,JO=FO,QO=$O;const FQ=PQ,LQ=MQ,ZO=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(HO,{ref:r,className:ge("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(OQ,{asChild:!0,children:u.jsx(lg,{className:"h-4 w-4 opacity-50"})})]}));ZO.displayName=HO.displayName;const YO=v.forwardRef(({className:e,...t},n)=>u.jsx(GO,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(P3,{className:"h-4 w-4"})}));YO.displayName=GO.displayName;const XO=v.forwardRef(({className:e,...t},n)=>u.jsx(JO,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(lg,{className:"h-4 w-4"})}));XO.displayName=JO.displayName;const eN=v.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>u.jsx(NQ,{children:u.jsxs(KO,{ref:s,className:ge("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(YO,{}),u.jsx(IQ,{className:ge("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(XO,{})]})}));eN.displayName=KO.displayName;const $Q=v.forwardRef(({className:e,...t},n)=>u.jsx(qO,{ref:n,className:ge("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));$Q.displayName=qO.displayName;const tN=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(WO,{ref:r,className:ge("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(AQ,{children:u.jsx(cj,{className:"h-4 w-4"})})}),u.jsx(DQ,{children:t})]}));tN.displayName=WO.displayName;const BQ=v.forwardRef(({className:e,...t},n)=>u.jsx(QO,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));BQ.displayName=QO.displayName;var Mw="Switch",[zQ,eoe]=Vr(Mw),[UQ,VQ]=zQ(Mw),nN=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:l,value:c="on",onCheckedChange:i,...d}=e,[p,f]=v.useState(null),h=it(t,y=>f(y)),g=v.useRef(!1),m=p?!!p.closest("form"):!0,[x=!1,b]=pa({prop:s,defaultProp:o,onChange:i});return u.jsxs(UQ,{scope:n,checked:x,disabled:l,children:[u.jsx(Ne.button,{type:"button",role:"switch","aria-checked":x,"aria-required":a,"data-state":oN(x),"data-disabled":l?"":void 0,disabled:l,value:c,...d,ref:h,onClick:Se(e.onClick,y=>{b(w=>!w),m&&(g.current=y.isPropagationStopped(),g.current||y.stopPropagation())})}),m&&u.jsx(HQ,{control:p,bubbles:!g.current,name:r,value:c,checked:x,required:a,disabled:l,style:{transform:"translateX(-100%)"}})]})});nN.displayName=Mw;var rN="SwitchThumb",sN=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=VQ(rN,n);return u.jsx(Ne.span,{"data-state":oN(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});sN.displayName=rN;var HQ=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=v.useRef(null),a=hO(n),l=Rj(t);return v.useEffect(()=>{const c=o.current,i=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(i,"checked").set;if(a!==n&&p){const f=new Event("click",{bubbles:r});p.call(c,n),c.dispatchEvent(f)}},[a,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function oN(e){return e?"checked":"unchecked"}var aN=nN,KQ=sN;const ju=v.forwardRef(({className:e,...t},n)=>u.jsx(aN,{className:ge("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:u.jsx(KQ,{className:ge("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));ju.displayName=aN.displayName;const Na=Tr,iN=v.createContext({}),Ia=({...e})=>u.jsx(iN.Provider,{value:{name:e.name},children:u.jsx($V,{...e})}),Ug=()=>{const e=v.useContext(iN),t=v.useContext(lN),{getFieldState:n,formState:r}=Rg(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},lN=v.createContext({}),_o=v.forwardRef(({className:e,...t},n)=>{const r=v.useId();return u.jsx(lN.Provider,{value:{id:r},children:u.jsx("div",{ref:n,className:ge("space-y-2",e),...t})})});_o.displayName="FormItem";const xr=v.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Ug();return u.jsx(pO,{ref:n,className:ge(r&&"text-rose-600",e),htmlFor:s,...t})});xr.displayName="FormLabel";const Vs=v.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Ug();return u.jsx(mo,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});Vs.displayName="FormControl";const Vg=v.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Ug();return u.jsx("p",{ref:n,id:r,className:ge("text-sm text-muted-foreground",e),...t})});Vg.displayName="FormDescription";const tf=v.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Ug(),a=s?String(s==null?void 0:s.message):t;return a?u.jsx("p",{ref:r,id:o,className:ge("text-sm font-medium text-rose-600",e),...n,children:a}):null});tf.displayName="FormMessage";const G=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{className:o,children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:v.isValidElement(n)&&v.cloneElement(n,{...l,value:l.value??"",required:r,readOnly:s,checked:l.value,onCheckedChange:l.onChange})}),u.jsx(tf,{})]})}),ke=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{className:ge("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[u.jsx("div",{className:"flex flex-col gap-2",children:t&&u.jsxs(xr,{children:[u.jsxs("p",{className:"break-all",children:[t,n&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&u.jsx(Vg,{className:"mt-2",children:s})]})}),u.jsx(Vs,{children:u.jsx(ju,{checked:l.value,onCheckedChange:l.onChange,required:n})}),u.jsx(tf,{})]})}),Qt=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,...a})=>u.jsx(Ia,{...a,name:e,render:({field:l})=>u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsxs(FQ,{onValueChange:l.onChange,defaultValue:l.value,children:[u.jsx(Vs,{children:u.jsx(ZO,{children:u.jsx(LQ,{placeholder:o})})}),u.jsx(eN,{children:s.map(c=>u.jsx(tN,{value:c.value,children:c.label},c.value))})]})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}),Ru=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>u.jsx(Ia,{...o,name:e,render:({field:a})=>{let l=[];return Array.isArray(a.value)&&(l=a.value),u.jsxs(_o,{children:[t&&u.jsxs(xr,{children:[t,r&&u.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),u.jsx(Vs,{children:u.jsx(iQ,{tags:l.map(c=>({id:c,text:c,className:""})),handleDelete:c=>a.onChange(l.filter((i,d)=>d!==c)),handleAddition:c=>a.onChange([...l,c.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[Rs.ENTER,Rs.TAB,Rs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:QP,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&u.jsx(Vg,{children:n}),u.jsx(tf,{})]})}}),pv=_.string().optional().transform(e=>e===""?void 0:e),qQ=_.object({name:_.string(),token:pv,number:pv,businessId:pv,integration:_.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","EVOLUTION"])});function WQ({resetTable:e}){const{t}=ze(),{createInstance:n}=_g(),[r,s]=v.useState(!1),o=[{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}],a=sn({resolver:on(qQ),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:NC().replace("-","").toUpperCase(),number:"",businessId:""}}),l=a.watch("integration"),c=async d=>{var p,f,h;try{const g={instanceName:d.name,integration:d.integration,token:d.token===""?null:d.token,number:d.number===""?null:d.number,businessId:d.businessId===""?null:d.businessId};await n(g),X.success(t("toast.instance.created")),s(!1),i(),e()}catch(g){console.error("Error:",g),X.error(`Error : ${(h=(f=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:f.response)==null?void 0:h.message}`)}},i=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:NC().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"default",size:"sm",children:[t("instance.button.create")," ",u.jsx(Ni,{size:"18"})]})}),u.jsxs(xt,{className:"sm:max-w-[650px]",onCloseAutoFocus:i,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("instance.modal.title")})}),u.jsx(Tr,{...a,children:u.jsxs("form",{onSubmit:a.handleSubmit(c),className:"grid gap-4 py-4",children:[u.jsx(G,{required:!0,name:"name",label:t("instance.form.name"),children:u.jsx(K,{})}),u.jsx(Qt,{name:"integration",label:t("instance.form.integration.label"),options:o}),u.jsx(G,{required:!0,name:"token",label:t("instance.form.token"),children:u.jsx(K,{})}),u.jsx(G,{name:"number",label:t("instance.form.number"),children:u.jsx(K,{type:"tel"})}),l==="WHATSAPP-BUSINESS"&&u.jsx(G,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:u.jsx(K,{})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:t("instance.button.save")})})]})})]})]})}function GQ(){const{t:e}=ze(),[t,n]=v.useState(null),{deleteInstance:r,logout:s}=_g(),{data:o,refetch:a}=_V(),[l,c]=v.useState([]),[i,d]=v.useState("all"),[p,f]=v.useState(""),h=async()=>{await a()},g=async b=>{var y,w,S;n(null),c([...l,b]);try{try{await s(b)}catch(E){console.error("Error logout:",E)}await r(b),await new Promise(E=>setTimeout(E,1e3)),h()}catch(E){console.error("Error instance delete:",E),X.error(`Error : ${(S=(w=(y=E==null?void 0:E.response)==null?void 0:y.data)==null?void 0:w.response)==null?void 0:S.message}`)}finally{c(l.filter(E=>E!==b))}},m=v.useMemo(()=>{let b=o?[...o]:[];return i!=="all"&&(b=b.filter(y=>y.connectionStatus===i)),p!==""&&(b=b.filter(y=>y.name.toLowerCase().includes(p.toLowerCase()))),b},[o,p,i]),x=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return u.jsxs("div",{className:"my-4 px-4",children:[u.jsxs("div",{className:"flex w-full items-center justify-between",children:[u.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(q,{variant:"outline",size:"icon",children:u.jsx(fj,{onClick:h,size:"20"})}),u.jsx(WQ,{resetTable:h})]})]}),u.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[u.jsx("div",{className:"flex-1",children:u.jsx(K,{placeholder:e("dashboard.search"),value:p,onChange:b=>f(b.target.value)})}),u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"secondary",children:[e("dashboard.status")," ",u.jsx(M3,{size:"15"})]})}),u.jsx(ps,{children:x.map(b=>u.jsx(GR,{checked:i===b.value,onCheckedChange:y=>{y&&d(b.value)},children:b.label},b.value))})]})]}),u.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:m.length>0&&Array.isArray(o)&&o.map(b=>{var y,w;return u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs(nd,{to:`/manager/instance/${b.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[u.jsx("h3",{className:"text-wrap font-semibold",children:b.name}),u.jsx(q,{variant:"ghost",size:"icon",children:u.jsx(Oi,{className:"card-icon",size:"20"})})]})}),u.jsxs(Za,{className:"flex-1 space-y-6",children:[u.jsx(GP,{token:b.token}),u.jsxs("div",{className:"flex w-full flex-wrap",children:[u.jsx("div",{className:"flex flex-1 gap-2",children:b.profileName&&u.jsxs(u.Fragment,{children:[u.jsx(Sg,{children:u.jsx(Cg,{src:b.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:b.profileName}),u.jsx("p",{className:"text-sm text-muted-foreground",children:b.ownerJid&&b.ownerJid.split("@")[0]})]})]})}),u.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(dj,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((y=b==null?void 0:b._count)==null?void 0:y.Contact)||0)})]}),u.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[u.jsx(ug,{className:"text-muted-foreground",size:"20"}),u.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((w=b==null?void 0:b._count)==null?void 0:w.Message)||0)})]})]})]})]}),u.jsxs(kg,{className:"justify-between",children:[u.jsx(WP,{status:b.connectionStatus}),u.jsx(q,{variant:"destructive",size:"sm",onClick:()=>n(b.name),disabled:l.includes(b.name),children:l.includes(b.name)?u.jsx("span",{children:e("button.deleting")}):u.jsx("span",{children:e("button.delete")})})]})]},b.id)})}),!!t&&u.jsx(Tt,{onOpenChange:()=>n(null),open:!0,children:u.jsxs(xt,{children:[u.jsx(TP,{}),u.jsx(wt,{children:e("modal.delete.title")}),u.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),u.jsx(rn,{children:u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx(q,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),u.jsx(q,{onClick:()=>g(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:au,createContext:JQ,createRef:toe,forwardRef:uN,useCallback:ir,useContext:cN,useEffect:pi,useImperativeHandle:dN,useLayoutEffect:QQ,useMemo:ZQ,useRef:Yn,useState:Oc}=Nh,z1=Nh.useId,YQ=QQ,Hg=JQ(null);Hg.displayName="PanelGroupContext";const hi=YQ,XQ=typeof z1=="function"?z1:()=>null;let eZ=0;function Ow(e=null){const t=XQ(),n=Yn(e||t||null);return n.current===null&&(n.current=""+eZ++),e??n.current}function fN({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:l,minSize:c,onCollapse:i,onExpand:d,onResize:p,order:f,style:h,tagName:g="div",...m}){const x=cN(Hg);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:b,expandPanel:y,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:k,registerPanel:T,resizePanel:P,unregisterPanel:N}=x,U=Ow(a),I=Yn({callbacks:{onCollapse:i,onExpand:d,onResize:p},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:l,minSize:c},id:U,idIsFromProps:a!==void 0,order:f});Yn({didLogMissingDefaultSizeWarning:!1}),hi(()=>{const{callbacks:V,constraints:Q}=I.current,ee={...Q};I.current.id=U,I.current.idIsFromProps=a!==void 0,I.current.order=f,V.onCollapse=i,V.onExpand=d,V.onResize=p,Q.collapsedSize=n,Q.collapsible=r,Q.defaultSize=s,Q.maxSize=l,Q.minSize=c,(ee.collapsedSize!==Q.collapsedSize||ee.collapsible!==Q.collapsible||ee.maxSize!==Q.maxSize||ee.minSize!==Q.minSize)&&k(I.current,ee)}),hi(()=>{const V=I.current;return T(V),()=>{N(V)}},[f,U,T,N]),dN(o,()=>({collapse:()=>{b(I.current)},expand:V=>{y(I.current,V)},getId(){return U},getSize(){return w(I.current)},isCollapsed(){return C(I.current)},isExpanded(){return!C(I.current)},resize:V=>{P(I.current,V)}}),[b,y,w,C,U,P]);const Z=S(I.current,s);return au(g,{...m,children:e,className:t,id:a,style:{...Z,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":U,"data-panel-size":parseFloat(""+Z.flexGrow).toFixed(1)})}const pN=uN((e,t)=>au(fN,{...e,forwardedRef:t}));fN.displayName="Panel";pN.displayName="forwardRef(Panel)";let bb=null,Xa=null;function tZ(e,t){if(t){const n=(t&yN)!==0,r=(t&bN)!==0,s=(t&xN)!==0,o=(t&wN)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function nZ(){Xa!==null&&(document.head.removeChild(Xa),bb=null,Xa=null)}function hv(e,t){const n=tZ(e,t);bb!==n&&(bb=n,Xa===null&&(Xa=document.createElement("style"),document.head.appendChild(Xa)),Xa.innerHTML=`*{cursor: ${n}!important;}`)}function hN(e){return e.type==="keydown"}function gN(e){return e.type.startsWith("pointer")}function mN(e){return e.type.startsWith("mouse")}function Kg(e){if(gN(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(mN(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function rZ(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function sZ(e,t,n){return e.xt.x&&e.yt.y}function oZ(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:H1(e),b:H1(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;tt(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:V1(U1(n.a)),b:V1(U1(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const c=o[l];if(c===a.a)return 1;if(c===a.b)return-1}}return Math.sign(s.a-s.b)}const aZ=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function iZ(e){var t;const n=getComputedStyle((t=vN(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function lZ(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||iZ(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||aZ.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function U1(e){let t=e.length;for(;t--;){const n=e[t];if(tt(n,"Missing node"),lZ(n))return n}return null}function V1(e){return e&&Number(getComputedStyle(e).zIndex)||0}function H1(e){const t=[];for(;e;)t.push(e),e=vN(e);return t}function vN(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const yN=1,bN=2,xN=4,wN=8,uZ=rZ()==="coarse";let is=[],_d=!1,Ho=new Map,qg=new Map;const jd=new Set;function cZ(e,t,n,r,s){var o;const{ownerDocument:a}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},c=(o=Ho.get(a))!==null&&o!==void 0?o:0;return Ho.set(a,c+1),jd.add(l),kh(),function(){var d;qg.delete(e),jd.delete(l);const p=(d=Ho.get(a))!==null&&d!==void 0?d:1;if(Ho.set(a,p-1),kh(),p===1&&Ho.delete(a),is.includes(l)){const f=is.indexOf(l);f>=0&&is.splice(f,1),Iw()}}}function K1(e){const{target:t}=e,{x:n,y:r}=Kg(e);_d=!0,Nw({target:t,x:n,y:r}),kh(),is.length>0&&(_h("down",e),e.preventDefault(),e.stopPropagation())}function nc(e){const{x:t,y:n}=Kg(e);if(e.buttons===0&&(_d=!1,_h("up",e)),!_d){const{target:r}=e;Nw({target:r,x:t,y:n})}_h("move",e),Iw(),is.length>0&&e.preventDefault()}function Zi(e){const{target:t}=e,{x:n,y:r}=Kg(e);qg.clear(),_d=!1,is.length>0&&e.preventDefault(),_h("up",e),Nw({target:t,x:n,y:r}),Iw(),kh()}function Nw({target:e,x:t,y:n}){is.splice(0);let r=null;e instanceof HTMLElement&&(r=e),jd.forEach(s=>{const{element:o,hitAreaMargins:a}=s,l=o.getBoundingClientRect(),{bottom:c,left:i,right:d,top:p}=l,f=uZ?a.coarse:a.fine;if(t>=i-f&&t<=d+f&&n>=p-f&&n<=c+f){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&oZ(r,o)>0){let g=r,m=!1;for(;g&&!g.contains(o);){if(sZ(g.getBoundingClientRect(),l)){m=!0;break}g=g.parentElement}if(m)return}is.push(s)}})}function gv(e,t){qg.set(e,t)}function Iw(){let e=!1,t=!1;is.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;qg.forEach(r=>{n|=r}),e&&t?hv("intersection",n):e?hv("horizontal",n):t?hv("vertical",n):nZ()}function kh(){Ho.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",Zi),n.removeEventListener("pointerdown",K1),n.removeEventListener("pointerleave",nc),n.removeEventListener("pointermove",nc)}),window.removeEventListener("pointerup",Zi),window.removeEventListener("pointercancel",Zi),jd.size>0&&(_d?(is.length>0&&Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",Zi),n.addEventListener("pointerleave",nc),n.addEventListener("pointermove",nc))}),window.addEventListener("pointerup",Zi),window.addEventListener("pointercancel",Zi)):Ho.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",K1,{capture:!0}),n.addEventListener("pointermove",nc))}))}function _h(e,t){jd.forEach(n=>{const{setResizeHandlerState:r}=n,s=is.includes(n);r(e,s,t)})}function tt(e,t){if(!e)throw console.error(t),Error(t)}const Dw=10;function Ri(e,t,n=Dw){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function no(e,t,n=Dw){return Ri(e,t,n)===0}function dr(e,t,n){return Ri(e,t,n)===0}function dZ(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-b:b)}}}{const p=e<0?l:c,f=n[p];tt(f,`No panel constraints found for index ${p}`);const{collapsedSize:h=0,collapsible:g,minSize:m=0}=f;if(g){const x=t[p];if(tt(x!=null,`Previous layout not found for panel index ${p}`),dr(x,m)){const b=x-h;Ri(b,Math.abs(e))>0&&(e=e<0?0-b:b)}}}}{const p=e<0?1:-1;let f=e<0?c:l,h=0;for(;;){const m=t[f];tt(m!=null,`Previous layout not found for panel index ${f}`);const b=yl({panelConstraints:n,panelIndex:f,size:100})-m;if(h+=b,f+=p,f<0||f>=n.length)break}const g=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-g:g}{let f=e<0?l:c;for(;f>=0&&f=0))break;e<0?f--:f++}}if(dZ(s,a))return s;{const p=e<0?c:l,f=t[p];tt(f!=null,`Previous layout not found for panel index ${p}`);const h=f+i,g=yl({panelConstraints:n,panelIndex:p,size:h});if(a[p]=g,!dr(g,h)){let m=h-g,b=e<0?c:l;for(;b>=0&&b0?b--:b++}}}const d=a.reduce((p,f)=>f+p,0);return dr(d,100)?a:s}function fZ({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const l=n[0];tt(l!=null,"No pivot index found"),t.forEach((p,f)=>{const{constraints:h}=p,{maxSize:g=100,minSize:m=0}=h;f===l?(r=m,s=g):(o+=m,a+=g)});const c=Math.min(s,100-o),i=Math.max(r,100-a),d=e[l];return{valueMax:c,valueMin:i,valueNow:d}}function Rd(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function SN(e,t,n=document){const s=Rd(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function CN(e,t,n){const r=SN(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function EN(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function Wg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function pZ(e,t,n,r=document){var s,o,a,l;const c=Wg(t,r),i=Rd(e,r),d=c?i.indexOf(c):-1,p=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,f=(a=(l=n[d+1])===null||l===void 0?void 0:l.id)!==null&&a!==void 0?a:null;return[p,f]}function hZ({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){Yn({didWarnAboutMissingResizeHandle:!1}),hi(()=>{if(!o)return;const l=Rd(n,o);for(let c=0;c{l.forEach((c,i)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,s,o]),pi(()=>{if(!o)return;const l=t.current;tt(l,"Eager values not found");const{panelDataArray:c}=l,i=EN(n,o);tt(i!=null,`No group found for id "${n}"`);const d=Rd(n,o);tt(d,`No resize handles found for group id "${n}"`);const p=d.map(f=>{const h=f.getAttribute("data-panel-resize-handle-id");tt(h,"Resize handle element has no handle id attribute");const[g,m]=pZ(n,h,c,o);if(g==null||m==null)return()=>{};const x=b=>{if(!b.defaultPrevented)switch(b.key){case"Enter":{b.preventDefault();const y=c.findIndex(w=>w.id===g);if(y>=0){const w=c[y];tt(w,`No panel data found for index ${y}`);const S=r[y],{collapsedSize:E=0,collapsible:C,minSize:k=0}=w.constraints;if(S!=null&&C){const T=gc({delta:dr(S,E)?k-E:E-S,initialLayout:r,panelConstraints:c.map(P=>P.constraints),pivotIndices:CN(n,h,o),prevLayout:r,trigger:"keyboard"});r!==T&&a(T)}}break}}};return f.addEventListener("keydown",x),()=>{f.removeEventListener("keydown",x)}});return()=>{p.forEach(f=>f())}},[o,e,t,n,r,s,a])}function q1(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];tt(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:l,id:c}=o,{collapsedSize:i=0,collapsible:d}=l,p=n[c];if(p==null||r!==p){n[c]=r;const{onCollapse:f,onExpand:h,onResize:g}=a;g&&g(r,p),d&&(f||h)&&(h&&(p==null||no(p,i))&&!no(r,i)&&h(),f&&(p==null||!no(p,i))&&no(r,i)&&f())}})}function Vf(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function W1(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function kN(e){return`react-resizable-panels:${e}`}function _N(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function jN(e,t){try{const n=kN(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function xZ(e,t,n){var r,s;const o=(r=jN(e,n))!==null&&r!==void 0?r:{},a=_N(t);return(s=o[a])!==null&&s!==void 0?s:null}function wZ(e,t,n,r,s){var o;const a=kN(e),l=_N(t),c=(o=jN(e,s))!==null&&o!==void 0?o:{};c[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(c))}catch(i){console.error(i)}}function G1({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!dr(r,100))for(let o=0;o(W1(mc),mc.getItem(e)),setItem:(e,t)=>{W1(mc),mc.setItem(e,t)}},J1={};function RN({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:l=null,storage:c=mc,style:i,tagName:d="div",...p}){const f=Ow(o),h=Yn(null),[g,m]=Oc(null),[x,b]=Oc([]),y=Yn({}),w=Yn(new Map),S=Yn(0),E=Yn({autoSaveId:e,direction:r,dragState:g,id:f,keyboardResizeBy:l,onLayout:a,storage:c}),C=Yn({layout:x,panelDataArray:[],panelDataArrayChanged:!1});Yn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),dN(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:z}=C.current;return z},setLayout:z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current,oe=G1({layout:z,panelConstraints:ie.map(J=>J.constraints)});q1(ne,oe)||(b(oe),C.current.layout=oe,se&&se(oe),Yi(ie,oe,y.current))}}),[]),hi(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=g,E.current.id=f,E.current.onLayout=a,E.current.storage=c}),hZ({committedValuesRef:E,eagerValuesRef:C,groupId:f,layout:x,panelDataArray:C.current.panelDataArray,setLayout:b,panelGroupElement:h.current}),pi(()=>{const{panelDataArray:z}=C.current;if(e){if(x.length===0||x.length!==z.length)return;let se=J1[e];se==null&&(se=bZ(wZ,SZ),J1[e]=se);const ne=[...z],ie=new Map(w.current);se(e,ne,ie,x,c)}},[e,x,c]),pi(()=>{});const k=ir(z=>{const{onLayout:se}=E.current,{layout:ne,panelDataArray:ie}=C.current;if(z.constraints.collapsible){const oe=ie.map(Le=>Le.constraints),{collapsedSize:J=0,panelSize:Ce,pivotIndices:Pe}=Fa(ie,z,ne);if(tt(Ce!=null,`Panel size not found for panel "${z.id}"`),!no(Ce,J)){w.current.set(z.id,Ce);const Me=nl(ie,z)===ie.length-1?Ce-J:J-Ce,me=gc({delta:Me,initialLayout:ne,panelConstraints:oe,pivotIndices:Pe,prevLayout:ne,trigger:"imperative-api"});Vf(ne,me)||(b(me),C.current.layout=me,se&&se(me),Yi(ie,me,y.current))}}},[]),T=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;if(z.constraints.collapsible){const J=oe.map(rt=>rt.constraints),{collapsedSize:Ce=0,panelSize:Pe=0,minSize:Le=0,pivotIndices:Me}=Fa(oe,z,ie),me=se??Le;if(no(Pe,Ce)){const rt=w.current.get(z.id),It=rt!=null&&rt>=me?rt:me,Wt=nl(oe,z)===oe.length-1?Pe-It:It-Pe,an=gc({delta:Wt,initialLayout:ie,panelConstraints:J,pivotIndices:Me,prevLayout:ie,trigger:"imperative-api"});Vf(ie,an)||(b(an),C.current.layout=an,ne&&ne(an),Yi(oe,an,y.current))}}},[]),P=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{panelSize:ie}=Fa(ne,z,se);return tt(ie!=null,`Panel size not found for panel "${z.id}"`),ie},[]),N=ir((z,se)=>{const{panelDataArray:ne}=C.current,ie=nl(ne,z);return yZ({defaultSize:se,dragState:g,layout:x,panelData:ne,panelIndex:ie})},[g,x]),U=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:J}=Fa(ne,z,se);return tt(J!=null,`Panel size not found for panel "${z.id}"`),oe===!0&&no(J,ie)},[]),I=ir(z=>{const{layout:se,panelDataArray:ne}=C.current,{collapsedSize:ie=0,collapsible:oe,panelSize:J}=Fa(ne,z,se);return tt(J!=null,`Panel size not found for panel "${z.id}"`),!oe||Ri(J,ie)>0},[]),Z=ir(z=>{const{panelDataArray:se}=C.current;se.push(z),se.sort((ne,ie)=>{const oe=ne.order,J=ie.order;return oe==null&&J==null?0:oe==null?-1:J==null?1:oe-J}),C.current.panelDataArrayChanged=!0},[]);hi(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:se,storage:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current;let J=null;if(z){const Pe=xZ(z,oe,ne);Pe&&(w.current=new Map(Object.entries(Pe.expandToSizes)),J=Pe.layout)}J==null&&(J=vZ({panelDataArray:oe}));const Ce=G1({layout:J,panelConstraints:oe.map(Pe=>Pe.constraints)});q1(ie,Ce)||(b(Ce),C.current.layout=Ce,se&&se(Ce),Yi(oe,Ce,y.current))}}),hi(()=>{const z=C.current;return()=>{z.layout=[]}},[]);const V=ir(z=>function(ne){ne.preventDefault();const ie=h.current;if(!ie)return()=>null;const{direction:oe,dragState:J,id:Ce,keyboardResizeBy:Pe,onLayout:Le}=E.current,{layout:Me,panelDataArray:me}=C.current,{initialLayout:rt}=J??{},It=CN(Ce,z,ie);let Zt=mZ(ne,z,oe,J,Pe,ie);const Wt=oe==="horizontal";document.dir==="rtl"&&Wt&&(Zt=-Zt);const an=me.map(B=>B.constraints),j=gc({delta:Zt,initialLayout:rt??Me,panelConstraints:an,pivotIndices:It,prevLayout:Me,trigger:hN(ne)?"keyboard":"mouse-or-touch"}),D=!Vf(Me,j);(gN(ne)||mN(ne))&&S.current!=Zt&&(S.current=Zt,D?gv(z,0):Wt?gv(z,Zt<0?yN:bN):gv(z,Zt<0?xN:wN)),D&&(b(j),C.current.layout=j,Le&&Le(j),Yi(me,j,y.current))},[]),Q=ir((z,se)=>{const{onLayout:ne}=E.current,{layout:ie,panelDataArray:oe}=C.current,J=oe.map(rt=>rt.constraints),{panelSize:Ce,pivotIndices:Pe}=Fa(oe,z,ie);tt(Ce!=null,`Panel size not found for panel "${z.id}"`);const Me=nl(oe,z)===oe.length-1?Ce-se:se-Ce,me=gc({delta:Me,initialLayout:ie,panelConstraints:J,pivotIndices:Pe,prevLayout:ie,trigger:"imperative-api"});Vf(ie,me)||(b(me),C.current.layout=me,ne&&ne(me),Yi(oe,me,y.current))},[]),ee=ir((z,se)=>{const{layout:ne,panelDataArray:ie}=C.current,{collapsedSize:oe=0,collapsible:J}=se,{collapsedSize:Ce=0,collapsible:Pe,maxSize:Le=100,minSize:Me=0}=z.constraints,{panelSize:me}=Fa(ie,z,ne);me!=null&&(J&&Pe&&no(me,oe)?no(oe,Ce)||Q(z,Ce):meLe&&Q(z,Le))},[Q]),W=ir((z,se)=>{const{direction:ne}=E.current,{layout:ie}=C.current;if(!h.current)return;const oe=Wg(z,h.current);tt(oe,`Drag handle element not found for id "${z}"`);const J=TN(ne,se);m({dragHandleId:z,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:J,initialLayout:ie})},[]),F=ir(()=>{m(null)},[]),A=ir(z=>{const{panelDataArray:se}=C.current,ne=nl(se,z);ne>=0&&(se.splice(ne,1),delete y.current[z.id],C.current.panelDataArrayChanged=!0)},[]),Y=ZQ(()=>({collapsePanel:k,direction:r,dragState:g,expandPanel:T,getPanelSize:P,getPanelStyle:N,groupId:f,isPanelCollapsed:U,isPanelExpanded:I,reevaluatePanelConstraints:ee,registerPanel:Z,registerResizeHandle:V,resizePanel:Q,startDragging:W,stopDragging:F,unregisterPanel:A,panelGroupElement:h.current}),[k,g,r,T,P,N,f,U,I,ee,Z,V,Q,W,F,A]),de={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return au(Hg.Provider,{value:Y},au(d,{...p,children:t,className:n,id:o,ref:h,style:{...de,...i},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":f}))}const PN=uN((e,t)=>au(RN,{...e,forwardedRef:t}));RN.displayName="PanelGroup";PN.displayName="forwardRef(PanelGroup)";function nl(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Fa(e,t,n){const r=nl(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function CZ({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){pi(()=>{if(e||n==null||r==null)return;const s=Wg(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const l=s.getAttribute("data-panel-group-id");tt(l,`No group element found for id "${l}"`);const c=Rd(l,r),i=SN(l,t,r);tt(i!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?i>0?i-1:c.length-1:i+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function MN({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:l,style:c={},tabIndex:i=0,tagName:d="div",...p}){var f,h;const g=Yn(null),m=Yn({onDragging:a});pi(()=>{m.current.onDragging=a});const x=cN(Hg);if(x===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:b,groupId:y,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=x,k=Ow(s),[T,P]=Oc("inactive"),[N,U]=Oc(!1),[I,Z]=Oc(null),V=Yn({state:T});hi(()=>{V.current.state=T}),pi(()=>{if(n)Z(null);else{const F=w(k);Z(()=>F)}},[n,k,w]);const Q=(f=r==null?void 0:r.coarse)!==null&&f!==void 0?f:15,ee=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return pi(()=>{if(n||I==null)return;const F=g.current;return tt(F,"Element ref not attached"),cZ(k,F,b,{coarse:Q,fine:ee},(Y,de,z)=>{if(de)switch(Y){case"down":{P("drag"),S(k,z);const{onDragging:se}=m.current;se&&se(!0);break}case"move":{const{state:se}=V.current;se!=="drag"&&P("hover"),I(z);break}case"up":{P("hover"),E();const{onDragging:se}=m.current;se&&se(!1);break}}else P("inactive")})},[Q,b,n,ee,w,k,I,S,E]),CZ({disabled:n,handleId:k,resizeHandler:I,panelGroupElement:C}),au(d,{...p,children:e,className:t,id:s,onBlur:()=>{U(!1),o==null||o()},onFocus:()=>{U(!0),l==null||l()},ref:g,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:i,"data-panel-group-direction":b,"data-panel-group-id":y,"data-resize-handle":"","data-resize-handle-active":T==="drag"?"pointer":N?"keyboard":void 0,"data-resize-handle-state":T,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":k})}MN.displayName="PanelResizeHandle";const Pu=({className:e,...t})=>u.jsx(PN,{className:ge("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),Ur=pN,Mu=({withHandle:e,className:t,...n})=>u.jsx(MN,{className:ge("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&u.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:u.jsx($3,{className:"h-2.5 w-2.5"})})});var Aw="Tabs",[EZ,noe]=Vr(Aw,[vg]),ON=vg(),[TZ,Fw]=EZ(Aw),NN=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:l,activationMode:c="automatic",...i}=e,d=Gd(l),[p,f]=pa({prop:r,onChange:s,defaultProp:o});return u.jsx(TZ,{scope:n,baseId:os(),value:p,onValueChange:f,orientation:a,dir:d,activationMode:c,children:u.jsx(Ne.div,{dir:d,"data-orientation":a,...i,ref:t})})});NN.displayName=Aw;var IN="TabsList",DN=v.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=Fw(IN,n),a=ON(n);return u.jsx(Gj,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:u.jsx(Ne.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});DN.displayName=IN;var AN="TabsTrigger",FN=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=Fw(AN,n),l=ON(n),c=BN(a.baseId,r),i=zN(a.baseId,r),d=r===a.value;return u.jsx(Jj,{asChild:!0,...l,focusable:!s,active:d,children:u.jsx(Ne.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":i,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...o,ref:t,onMouseDown:Se(e.onMouseDown,p=>{!s&&p.button===0&&p.ctrlKey===!1?a.onValueChange(r):p.preventDefault()}),onKeyDown:Se(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&a.onValueChange(r)}),onFocus:Se(e.onFocus,()=>{const p=a.activationMode!=="manual";!d&&!s&&p&&a.onValueChange(r)})})})});FN.displayName=AN;var LN="TabsContent",$N=v.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,l=Fw(LN,n),c=BN(l.baseId,r),i=zN(l.baseId,r),d=r===l.value,p=v.useRef(d);return v.useEffect(()=>{const f=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(f)},[]),u.jsx(or,{present:s||d,children:({present:f})=>u.jsx(Ne.div,{"data-state":d?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!f,id:i,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:f&&o})})});$N.displayName=LN;function BN(e,t){return`${e}-trigger-${t}`}function zN(e,t){return`${e}-content-${t}`}var kZ=NN,UN=DN,VN=FN,HN=$N;const _Z=kZ,KN=v.forwardRef(({className:e,...t},n)=>u.jsx(UN,{ref:n,className:ge("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));KN.displayName=UN.displayName;const xb=v.forwardRef(({className:e,...t},n)=>u.jsx(VN,{ref:n,className:ge("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));xb.displayName=VN.displayName;const wb=v.forwardRef(({className:e,...t},n)=>u.jsx(HN,{ref:n,className:ge("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));wb.displayName=HN.displayName;const jZ=e=>["chats","findChats",JSON.stringify(e)],RZ=async({instanceName:e})=>(await he.post(`/chat/findChats/${e}`,{where:{}})).data,PZ=e=>{const{instanceName:t,...n}=e;return lt({...n,queryKey:jZ({instanceName:t}),queryFn:()=>RZ({instanceName:t}),enabled:!!t})};function Ou(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=v.useState(t(e));function s(){r(t(e))}return v.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const Ml=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ge("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Ml.displayName="Textarea";const MZ=e=>["chats","findChats",JSON.stringify(e)],OZ=async({instanceName:e,remoteJid:t})=>{const n=await he.post(`/chat/findChats/${e}`,{where:{remoteJid:t}});return Array.isArray(n.data)?n.data[0]:n.data},NZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:MZ({instanceName:t,remoteJid:n}),queryFn:()=>OZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},IZ=e=>["chats","findMessages",JSON.stringify(e)],DZ=async({instanceName:e,remoteJid:t})=>{var r,s;const n=await he.post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}});return(s=(r=n.data)==null?void 0:r.messages)!=null&&s.records?n.data.messages.records:n.data},AZ=e=>{const{instanceName:t,remoteJid:n,...r}=e;return lt({...r,queryKey:IZ({instanceName:t,remoteJid:n}),queryFn:()=>DZ({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})};function FZ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=nt(),{remoteJid:a}=So(),{data:l}=NZ({remoteJid:a,instanceName:o==null?void 0:o.name}),{data:c,isSuccess:i}=AZ({remoteJid:a,instanceName:o==null?void 0:o.name});v.useEffect(()=>{i&&c&&s()},[i,c,s]);const d=f=>u.jsx("div",{className:"bubble-right",children:u.jsx("div",{className:"flex items-start gap-4 self-end",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})}),p=f=>u.jsx("div",{className:"bubble-left",children:u.jsx("div",{className:"flex items-start gap-4",children:u.jsx("div",{className:"grid gap-1",children:u.jsx("div",{className:"prose text-muted-foreground",children:u.jsx("div",{className:"bubble",children:JSON.stringify(f.message)})})})})});return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(nw,{children:[u.jsx(rw,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(l==null?void 0:l.pushName)||(l==null?void 0:l.remoteJid.split("@")[0]),u.jsx(lg,{className:"h-4 w-4 text-muted-foreground"})]})}),u.jsxs(ps,{align:"start",className:"max-w-[300px]",children:[u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(W3,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-4"}),u.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),u.jsx(Pa,{}),u.jsxs(ft,{className:"items-start gap-2",children:[u.jsx(pj,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),u.jsxs("div",{children:[u.jsx("div",{className:"font-medium",children:"GPT-3"}),u.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),u.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[c==null?void 0:c.map(f=>f.key.fromMe?d(f):p(f)),u.jsx("div",{ref:r})]}),u.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:u.jsxs("div",{className:"input-message relative",children:[u.jsxs(q,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[u.jsx(q3,{className:"h-4 w-4 text-white"}),u.jsx("span",{className:"sr-only",children:"Anexar"})]}),u.jsx(Ml,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),u.jsxs(q,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[u.jsx(j3,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function Q1(){const e=Ou("(min-width: 768px)"),t=v.useRef(null),[n]=v.useState("auto"),r=v.useRef(null),{instance:s}=nt(),{data:o,isSuccess:a}=PZ({instanceName:s==null?void 0:s.name}),{instanceId:l,remoteJid:c}=So(),i=An(),d=v.useCallback(()=>{t.current&&t.current.scrollIntoView({})},[]),p=()=>{if(r.current){r.current.style.height="auto";const h=r.current.scrollHeight,m=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(h,m)}px`}};v.useEffect(()=>{a&&d()},[a,d]);const f=h=>{i(`/manager/instance/${l}/chat/${h}`)};return u.jsxs(Pu,{direction:e?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:20,children:u.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[u.jsx("div",{className:"sticky top-0 p-2",children:u.jsxs(q,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[u.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:u.jsx(ug,{className:"h-4 w-4"})}),u.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),u.jsx(Ni,{className:"h-4 w-4"})]})}),u.jsxs(_Z,{defaultValue:"contacts",children:[u.jsxs(KN,{className:"tabs-chat",children:[u.jsx(xb,{value:"contacts",children:"Contatos"}),u.jsx(xb,{value:"groups",children:"Grupos"})]}),u.jsx(wb,{value:"contacts",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[u.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),o==null?void 0:o.map(h=>h.remoteJid.includes("@s.whatsapp.net")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid.split("@")[0]})]})]},h.id))]})})}),u.jsx(wb,{value:"groups",children:u.jsx("div",{className:"flex-1 overflow-auto",children:u.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:o==null?void 0:o.map(h=>h.remoteJid.includes("@g.us")&&u.jsxs(nd,{to:"#",onClick:()=>f(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[u.jsx("span",{className:"chat-avatar mr-2",children:u.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),u.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid})]})]},h.id))})})})]})]})}),u.jsx(Mu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:c&&u.jsx(FZ,{textareaRef:r,handleTextareaChange:p,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const LZ=e=>["chatwoot","fetchChatwoot",JSON.stringify(e)],$Z=async({instanceName:e,token:t})=>(await he.get(`/chatwoot/find/${e}`,{headers:{apiKey:t}})).data,BZ=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:LZ({instanceName:t,token:n}),queryFn:()=>$Z({instanceName:t,token:n}),enabled:!!t})},zZ=async({instanceName:e,token:t,data:n})=>(await he.post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data;function UZ(){return{createChatwoot:Ye(zZ,{invalidateKeys:[["chatwoot","fetchChatwoot"]]})}}const Hf=_.string().optional().transform(e=>e===""?void 0:e),VZ=_.object({enabled:_.boolean(),accountId:_.string(),token:_.string(),url:_.string(),signMsg:_.boolean().optional(),signDelimiter:Hf,nameInbox:Hf,organization:Hf,logo:Hf,reopenConversation:_.boolean().optional(),conversationPending:_.boolean().optional(),mergeBrazilContacts:_.boolean().optional(),importContacts:_.boolean().optional(),importMessages:_.boolean().optional(),daysLimitImportMessages:_.coerce.number().optional(),autoCreate:_.boolean(),ignoreJids:_.array(_.string()).default([])});function HZ(){const{t:e}=ze(),{instance:t}=nt(),[,n]=v.useState(!1),{createChatwoot:r}=UZ(),{data:s}=BZ({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),o=sn({resolver:on(VZ),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});v.useEffect(()=>{if(s){o.setValue("ignoreJids",s.ignoreJids||[]);const l={enabled:s.enabled,accountId:s.accountId,token:s.token,url:s.url,signMsg:s.signMsg||!1,signDelimiter:s.signDelimiter||"\\n",nameInbox:s.nameInbox||"",organization:s.organization||"",logo:s.logo||"",reopenConversation:s.reopenConversation||!1,conversationPending:s.conversationPending||!1,mergeBrazilContacts:s.mergeBrazilContacts||!1,importContacts:s.importContacts||!1,importMessages:s.importMessages||!1,daysLimitImportMessages:s.daysLimitImportMessages||7,autoCreate:s.autoCreate||!1,ignoreJids:s.ignoreJids};o.reset(l)}},[s,o]);const a=async l=>{if(!t)return;n(!0);const c={enabled:l.enabled,accountId:l.accountId,token:l.token,url:l.url,signMsg:l.signMsg||!1,signDelimiter:l.signDelimiter||"\\n",nameInbox:l.nameInbox||"",organization:l.organization||"",logo:l.logo||"",reopenConversation:l.reopenConversation||!1,conversationPending:l.conversationPending||!1,mergeBrazilContacts:l.mergeBrazilContacts||!1,importContacts:l.importContacts||!1,importMessages:l.importMessages||!1,daysLimitImportMessages:l.daysLimitImportMessages||7,autoCreate:l.autoCreate,ignoreJids:l.ignoreJids};await r({instanceName:t.name,token:t.token,data:c},{onSuccess:()=>{X.success(e("chatwoot.toast.success"))},onError:i=>{var d,p,f;console.error(e("chatwoot.toast.error"),i),A4(i)?X.error(`Error: ${(f=(p=(d=i==null?void 0:i.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`):X.error(e("chatwoot.toast.error"))},onSettled:()=>{n(!1)}})};return u.jsx(u.Fragment,{children:u.jsx(Na,{...o,children:u.jsxs("form",{onSubmit:o.handleSubmit(a),className:"w-full space-y-6",children:[u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[u.jsx(ke,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),u.jsx(G,{name:"url",label:e("chatwoot.form.url.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"token",label:e("chatwoot.form.token.label"),children:u.jsx(K,{type:"password"})}),u.jsx(ke,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),u.jsx(G,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"organization",label:e("chatwoot.form.organization.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"logo",label:e("chatwoot.form.logo.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),u.jsx(ke,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),u.jsx(ke,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),u.jsx(ke,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),u.jsx(G,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),u.jsx(ke,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),u.jsx("div",{className:"mx-4 flex justify-end",children:u.jsx(q,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Gg={},qN={exports:{}},KZ="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",qZ=KZ,WZ=qZ;function WN(){}function GN(){}GN.resetWarningCache=WN;var GZ=function(){function e(r,s,o,a,l,c){if(c!==WZ){var i=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:GN,resetWarningCache:WN};return n.PropTypes=n,n};qN.exports=GZ();var JN=qN.exports,QN={L:1,M:0,Q:3,H:2},ZN={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},JZ=ZN;function YN(e){this.mode=JZ.MODE_8BIT_BYTE,this.data=e}YN.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var YZ=XN,Xr={glog:function(e){if(e<1)throw new Error("glog("+e+")");return Xr.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return Xr.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var Cn=0;Cn<8;Cn++)Xr.EXP_TABLE[Cn]=1<=0;)t^=wn.G15<=0;)t^=wn.G18<>>=1;return t},getPatternPosition:function(e){return wn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case Do.PATTERN000:return(t+n)%2==0;case Do.PATTERN001:return t%2==0;case Do.PATTERN010:return n%3==0;case Do.PATTERN011:return(t+n)%3==0;case Do.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case Do.PATTERN101:return t*n%2+t*n%3==0;case Do.PATTERN110:return(t*n%2+t*n%3)%2==0;case Do.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new Z1([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=Ns.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};kr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};kr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=Da.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};kr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};kr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=Da.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};kr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var l=0;l<2;l++)if(this.modules[r][a-l]==null){var c=!1;o>>s&1)==1);var i=Da.getMask(t,r,a-l);i&&(c=!c),this.modules[r][a-l]=c,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};Ns.PAD0=236;Ns.PAD1=17;Ns.createData=function(e,t,n){for(var r=nI.getRSBlocks(e,t),s=new rI,o=0;ol*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+l*8+")");for(s.getLengthInBits()+4<=l*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=l*8||(s.put(Ns.PAD0,8),s.getLengthInBits()>=l*8));)s.put(Ns.PAD1,8);return Ns.createBytes(s,r)};Ns.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),l=0;l=0?h.get(g):0}}for(var m=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var iY={bgColor:Pr.default.oneOfType([Pr.default.object,Pr.default.string]).isRequired,bgD:Pr.default.string.isRequired,fgColor:Pr.default.oneOfType([Pr.default.object,Pr.default.string]).isRequired,fgD:Pr.default.string.isRequired,size:Pr.default.number.isRequired,title:Pr.default.string,viewBoxSize:Pr.default.number.isRequired,xmlns:Pr.default.string},$w=(0,sI.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,l=e.title,c=e.viewBoxSize,i=e.xmlns,d=i===void 0?"http://www.w3.org/2000/svg":i,p=aY(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return qf.default.createElement("svg",sY({},p,{height:a,ref:t,viewBox:"0 0 "+c+" "+c,width:a,xmlns:d}),l?qf.default.createElement("title",null,l):null,qf.default.createElement("path",{d:r,fill:n}),qf.default.createElement("path",{d:s,fill:o}))});$w.displayName="QRCodeSvg";$w.propTypes=iY;Lw.default=$w;Object.defineProperty(Gg,"__esModule",{value:!0});Gg.QRCode=void 0;var lY=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var yY={bgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),fgColor:Gs.default.oneOfType([Gs.default.object,Gs.default.string]),level:Gs.default.string,size:Gs.default.number,value:Gs.default.string.isRequired},Jg=(0,aI.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,l=a===void 0?"L":a,c=e.size,i=c===void 0?256:c,d=e.value,p=vY(e,["bgColor","fgColor","level","size","value"]),f=new pY.default(-1,dY.default[l]);f.addData(d),f.make();var h=f.modules;return hY.default.createElement(mY.default,lY({},p,{bgColor:r,bgD:h.map(function(g,m){return g.map(function(x,b){return x?"":"M "+b+" "+m+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:h.map(function(g,m){return g.map(function(x,b){return x?"M "+b+" "+m+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:i,viewBoxSize:h.length}))});Gg.QRCode=Jg;Jg.displayName="QRCode";Jg.propTypes=yY;var bY=Gg.default=Jg;const xY=ig("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),iI=v.forwardRef(({className:e,variant:t,...n},r)=>u.jsx("div",{ref:r,role:"alert",className:ge(xY({variant:t}),e),...n}));iI.displayName="Alert";const lI=v.forwardRef(({className:e,...t},n)=>u.jsx("h5",{ref:n,className:ge("font-medium leading-none tracking-tight",e),...t}));lI.displayName="AlertTitle";const wY=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ge("text-sm [&_p]:leading-relaxed",e),...t}));wY.displayName="AlertDescription";const wr=({size:e=45,className:t,...n})=>u.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:u.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:ge("animate-spin",t),children:u.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})});function SY(){const{t:e,i18n:t}=ze(),n=new Intl.NumberFormat(t.language),[r,s]=v.useState(null),[o,a]=v.useState(""),l=Fs(rs.TOKEN),{theme:c}=R_(),{connect:i,logout:d,restart:p}=_g(),{instance:f,reloadInstance:h}=nt(),g=async()=>{await h()},m=async E=>{try{await p(E),await h()}catch(C){console.error("Error:",C)}},x=async E=>{try{await d(E),await h()}catch(C){console.error("Error:",C)}},b=async(E,C)=>{try{if(s(null),!l){console.error("Token not found.");return}if(C){const k=await i({instanceName:E,token:l,number:f==null?void 0:f.number});a(k.pairingCode)}else{const k=await i({instanceName:E,token:l});s(k.code)}}catch(k){console.error("Error:",k)}},y=async()=>{s(null),a(""),await h()},w=v.useMemo(()=>{var E,C,k;return f?{contacts:((E=f._count)==null?void 0:E.Contact)||0,chats:((C=f._count)==null?void 0:C.Chat)||0,messages:((k=f._count)==null?void 0:k.Message)||0}:{contacts:0,chats:0,messages:0}},[f]),S=v.useMemo(()=>c==="dark"?"#fff":c==="light"?"#000":"#189d68",[c]);return f?u.jsxs("main",{className:"flex flex-col gap-8",children:[u.jsx("section",{children:u.jsxs(Ja,{children:[u.jsx(Qa,{children:u.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[u.jsx("h2",{className:"break-all text-lg font-semibold",children:f.name}),u.jsx(WP,{status:f.connectionStatus})]})}),u.jsxs(Za,{className:"flex flex-col items-start space-y-6",children:[u.jsx("div",{className:"flex w-full flex-1",children:u.jsx(GP,{token:f.token})}),f.profileName&&u.jsxs("div",{className:"flex flex-1 gap-2",children:[u.jsx(Sg,{children:u.jsx(Cg,{src:f.profilePicUrl,alt:""})}),u.jsxs("div",{className:"space-y-1",children:[u.jsx("strong",{children:f.profileName}),u.jsx("p",{className:"break-all text-sm text-muted-foreground",children:f.ownerJid})]})]}),f.connectionStatus!=="open"&&u.jsxs(iI,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[u.jsx(lI,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),u.jsxs(Tt,{children:[u.jsx(Nt,{onClick:()=>b(f.name,!1),asChild:!0,children:u.jsx(q,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),u.jsxs(xt,{onCloseAutoFocus:y,children:[u.jsx(wt,{children:e("instance.dashboard.button.qrcode.title")}),u.jsx("div",{className:"flex items-center justify-center",children:r&&u.jsx(bY,{value:r,size:256,bgColor:"transparent",fgColor:S,className:"rounded-sm"})})]})]}),f.number&&u.jsxs(Tt,{children:[u.jsx(Nt,{className:"connect-code-button",onClick:()=>b(f.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),u.jsx(xt,{onCloseAutoFocus:y,children:u.jsx(wt,{children:u.jsx(Fi,{children:o?u.jsxs("div",{className:"py-3",children:[u.jsx("p",{className:"text-center",children:u.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),u.jsxs("p",{className:"pairing-code text-center",children:[o.substring(0,4),"-",o.substring(4,8)]})]}):u.jsx(wr,{})})})})]})]})]}),u.jsxs(kg,{className:"flex flex-wrap items-center justify-end gap-3",children:[u.jsx(q,{variant:"outline",className:"refresh-button",size:"icon",onClick:g,children:u.jsx(fj,{size:"20"})}),u.jsx(q,{className:"action-button",variant:"secondary",onClick:()=>m(f.name),children:e("instance.dashboard.button.restart").toUpperCase()}),u.jsx(q,{variant:"destructive",onClick:()=>x(f.name),disabled:f.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),u.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(dj,{size:"20"}),e("instance.dashboard.contacts")]})}),u.jsx(Za,{children:n.format(w.contacts)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(J3,{size:"20"}),e("instance.dashboard.chats")]})}),u.jsx(Za,{children:n.format(w.chats)})]}),u.jsxs(Ja,{className:"instance-card",children:[u.jsx(Qa,{children:u.jsxs(jc,{className:"flex items-center gap-2",children:[u.jsx(ug,{size:"20"}),e("instance.dashboard.messages")]})}),u.jsx(Za,{children:n.format(w.messages)})]})]})]}):u.jsx(wr,{})}var CY="Separator",Y1="horizontal",EY=["horizontal","vertical"],uI=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Y1,...s}=e,o=TY(r)?r:Y1,l=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return u.jsx(Ne.div,{"data-orientation":o,...l,...s,ref:t})});uI.displayName=CY;function TY(e){return EY.includes(e)}var cI=uI;const $t=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>u.jsx(cI,{ref:s,decorative:n,orientation:t,className:ge("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));$t.displayName=cI.displayName;const kY=e=>["dify","fetchDify",JSON.stringify(e)],_Y=async({instanceName:e,token:t})=>(await he.get(`/dify/find/${e}`,{headers:{apikey:t}})).data,dI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:kY({instanceName:t,token:n}),queryFn:()=>_Y({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},jY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,RY=async({instanceName:e,difyId:t,data:n})=>(await he.put(`/dify/update/${t}/${e}`,n)).data,PY=async({instanceName:e,difyId:t})=>(await he.delete(`/dify/delete/${t}/${e}`)).data,MY=async({instanceName:e,token:t,data:n})=>(await he.post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,OY=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Qg(){const e=Ye(MY,{invalidateKeys:[["dify","fetchDefaultSettings"]]}),t=Ye(OY,{invalidateKeys:[["dify","getDify"],["dify","fetchSessions"]]}),n=Ye(PY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),r=Ye(RY,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),s=Ye(jY,{invalidateKeys:[["dify","fetchDify"]]});return{setDefaultSettingsDify:e,changeStatusDify:t,deleteDify:n,updateDify:r,createDify:s}}const NY=e=>["dify","fetchDefaultSettings",JSON.stringify(e)],IY=async({instanceName:e,token:t})=>(await he.get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,DY=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:NY({instanceName:t,token:n}),queryFn:()=>IY({instanceName:t,token:n}),enabled:!!t})},AY=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),difyIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function FY(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsDify:n}=Qg(),[r,s]=v.useState(!1),{data:o,refetch:a}=dI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:r}),{data:l,refetch:c}=DY({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),i=sn({resolver:on(AY),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{l&&i.reset({expire:l!=null&&l.expire?l.expire.toString():"0",keywordFinish:l.keywordFinish,delayMessage:l.delayMessage?l.delayMessage.toString():"0",unknownMessage:l.unknownMessage,listeningFromMe:l.listeningFromMe,stopBotFromMe:l.stopBotFromMe,keepOpen:l.keepOpen,debounceTime:l.debounceTime?l.debounceTime.toString():"0",ignoreJids:l.ignoreJids,difyIdFallback:l.difyIdFallback,splitMessages:l.splitMessages,timePerChar:l.timePerChar?l.timePerChar.toString():"0"})},[l]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("dify.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){c(),a()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("dify.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(o==null?void 0:o.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("dify.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("dify.form.splitMessages.label"),reverse:!0}),u.jsx(G,{name:"timePerChar",label:e("dify.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("dify.button.save")})})]})})]})]})}/** - * table-core - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function na(e,t){return typeof e=="function"?e(t):e}function Sr(e,t){return n=>{t.setState(r=>({...r,[e]:na(n,r[e])}))}}function Zg(e){return e instanceof Function}function LY(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function fI(e,t){const n=[],r=s=>{s.forEach(o=>{n.push(o);const a=t(o);a!=null&&a.length&&r(a)})};return r(e),n}function De(e,t,n){let r=[],s;return o=>{let a;n.key&&n.debug&&(a=Date.now());const l=e(o);if(!(l.length!==r.length||l.some((d,p)=>r[p]!==d)))return s;r=l;let i;if(n.key&&n.debug&&(i=Date.now()),s=t(...l),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const d=Math.round((Date.now()-a)*100)/100,p=Math.round((Date.now()-i)*100)/100,f=p/16,h=(g,m)=>{for(g=String(g);g.length{var s;return(s=e==null?void 0:e.debugAll)!=null?s:e[t]},key:!1,onChange:r}}function $Y(e,t,n,r){const s=()=>{var a;return(a=o.getValue())!=null?a:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:s,getContext:De(()=>[e,n,t,o],(a,l,c,i)=>({table:a,column:l,row:c,cell:i,getValue:i.getValue,renderValue:i.renderValue}),Ae(e.options,"debugCells"))};return e._features.forEach(a=>{a.createCell==null||a.createCell(o,n,t,e)},{}),o}function BY(e,t,n,r){var s,o;const l={...e._getDefaultColumnDef(),...t},c=l.accessorKey;let i=(s=(o=l.id)!=null?o:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?s:typeof l.header=="string"?l.header:void 0,d;if(l.accessorFn?d=l.accessorFn:c&&(c.includes(".")?d=f=>{let h=f;for(const m of c.split(".")){var g;h=(g=h)==null?void 0:g[m]}return h}:d=f=>f[l.accessorKey]),!i)throw new Error;let p={id:`${String(i)}`,accessorFn:d,parent:r,depth:n,columnDef:l,columns:[],getFlatColumns:De(()=>[!0],()=>{var f;return[p,...(f=p.columns)==null?void 0:f.flatMap(h=>h.getFlatColumns())]},Ae(e.options,"debugColumns")),getLeafColumns:De(()=>[e._getOrderColumnsFn()],f=>{var h;if((h=p.columns)!=null&&h.length){let g=p.columns.flatMap(m=>m.getLeafColumns());return f(g)}return[p]},Ae(e.options,"debugColumns"))};for(const f of e._features)f.createColumn==null||f.createColumn(p,e);return p}const Mn="debugHeaders";function X1(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const a=[],l=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(l),a.push(c)};return l(o),a},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(a=>{a.createHeader==null||a.createHeader(o,e)}),o}const zY={createTable:e=>{e.getHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>{var o,a;const l=(o=r==null?void 0:r.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?o:[],c=(a=s==null?void 0:s.map(p=>n.find(f=>f.id===p)).filter(Boolean))!=null?a:[],i=n.filter(p=>!(r!=null&&r.includes(p.id))&&!(s!=null&&s.includes(p.id)));return Wf(t,[...l,...i,...c],e)},Ae(e.options,Mn)),e.getCenterHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),Wf(t,n,e,"center")),Ae(e.options,Mn)),e.getLeftHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(l=>l.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"left")},Ae(e.options,Mn)),e.getRightHeaderGroups=De(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var s;const o=(s=r==null?void 0:r.map(a=>n.find(l=>l.id===a)).filter(Boolean))!=null?s:[];return Wf(t,o,e,"right")},Ae(e.options,Mn)),e.getFooterGroups=De(()=>[e.getHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getLeftFooterGroups=De(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getCenterFooterGroups=De(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getRightFooterGroups=De(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),Ae(e.options,Mn)),e.getFlatHeaders=De(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getLeftFlatHeaders=De(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getCenterFlatHeaders=De(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getRightFlatHeaders=De(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),Ae(e.options,Mn)),e.getCenterLeafHeaders=De(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getLeftLeafHeaders=De(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getRightLeafHeaders=De(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),Ae(e.options,Mn)),e.getLeafHeaders=De(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var s,o,a,l,c,i;return[...(s=(o=t[0])==null?void 0:o.headers)!=null?s:[],...(a=(l=n[0])==null?void 0:l.headers)!=null?a:[],...(c=(i=r[0])==null?void 0:i.headers)!=null?c:[]].map(d=>d.getLeafHeaders()).flat()},Ae(e.options,Mn))}};function Wf(e,t,n,r){var s,o;let a=0;const l=function(f,h){h===void 0&&(h=1),a=Math.max(a,h),f.filter(g=>g.getIsVisible()).forEach(g=>{var m;(m=g.columns)!=null&&m.length&&l(g.columns,h+1)},0)};l(e);let c=[];const i=(f,h)=>{const g={depth:h,id:[r,`${h}`].filter(Boolean).join("_"),headers:[]},m=[];f.forEach(x=>{const b=[...m].reverse()[0],y=x.column.depth===g.depth;let w,S=!1;if(y&&x.column.parent?w=x.column.parent:(w=x.column,S=!0),b&&(b==null?void 0:b.column)===w)b.subHeaders.push(x);else{const E=X1(n,w,{id:[r,h,w.id,x==null?void 0:x.id].filter(Boolean).join("_"),isPlaceholder:S,placeholderId:S?`${m.filter(C=>C.column===w).length}`:void 0,depth:h,index:m.length});E.subHeaders.push(x),m.push(E)}g.headers.push(x),x.headerGroup=g}),c.push(g),h>0&&i(m,h-1)},d=t.map((f,h)=>X1(n,f,{depth:a,index:h}));i(d,a-1),c.reverse();const p=f=>f.filter(g=>g.column.getIsVisible()).map(g=>{let m=0,x=0,b=[0];g.subHeaders&&g.subHeaders.length?(b=[],p(g.subHeaders).forEach(w=>{let{colSpan:S,rowSpan:E}=w;m+=S,b.push(E)})):m=1;const y=Math.min(...b);return x=x+y,g.colSpan=m,g.rowSpan=x,{colSpan:m,rowSpan:x}});return p((s=(o=c[0])==null?void 0:o.headers)!=null?s:[]),c}const Yg=(e,t,n,r,s,o,a)=>{let l={id:t,index:r,original:n,depth:s,parentId:a,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(l._valuesCache.hasOwnProperty(c))return l._valuesCache[c];const i=e.getColumn(c);if(i!=null&&i.accessorFn)return l._valuesCache[c]=i.accessorFn(l.original,r),l._valuesCache[c]},getUniqueValues:c=>{if(l._uniqueValuesCache.hasOwnProperty(c))return l._uniqueValuesCache[c];const i=e.getColumn(c);if(i!=null&&i.accessorFn)return i.columnDef.getUniqueValues?(l._uniqueValuesCache[c]=i.columnDef.getUniqueValues(l.original,r),l._uniqueValuesCache[c]):(l._uniqueValuesCache[c]=[l.getValue(c)],l._uniqueValuesCache[c])},renderValue:c=>{var i;return(i=l.getValue(c))!=null?i:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>fI(l.subRows,c=>c.subRows),getParentRow:()=>l.parentId?e.getRow(l.parentId,!0):void 0,getParentRows:()=>{let c=[],i=l;for(;;){const d=i.getParentRow();if(!d)break;c.push(d),i=d}return c.reverse()},getAllCells:De(()=>[e.getAllLeafColumns()],c=>c.map(i=>$Y(e,l,i,i.id)),Ae(e.options,"debugRows")),_getAllCellsByColumnId:De(()=>[l.getAllCells()],c=>c.reduce((i,d)=>(i[d.column.id]=d,i),{}),Ae(e.options,"debugRows"))};for(let c=0;c{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},pI=(e,t,n)=>{var r;const s=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(s))};pI.autoRemove=e=>ls(e);const hI=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};hI.autoRemove=e=>ls(e);const gI=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===(n==null?void 0:n.toLowerCase())};gI.autoRemove=e=>ls(e);const mI=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};mI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const vI=(e,t,n)=>!n.some(r=>{var s;return!((s=e.getValue(t))!=null&&s.includes(r))});vI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const yI=(e,t,n)=>n.some(r=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(r)});yI.autoRemove=e=>ls(e)||!(e!=null&&e.length);const bI=(e,t,n)=>e.getValue(t)===n;bI.autoRemove=e=>ls(e);const xI=(e,t,n)=>e.getValue(t)==n;xI.autoRemove=e=>ls(e);const Bw=(e,t,n)=>{let[r,s]=n;const o=e.getValue(t);return o>=r&&o<=s};Bw.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,s=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,a=n===null||Number.isNaN(s)?1/0:s;if(o>a){const l=o;o=a,a=l}return[o,a]};Bw.autoRemove=e=>ls(e)||ls(e[0])&&ls(e[1]);const Xs={includesString:pI,includesStringSensitive:hI,equalsString:gI,arrIncludes:mI,arrIncludesAll:vI,arrIncludesSome:yI,equals:bI,weakEquals:xI,inNumberRange:Bw};function ls(e){return e==null||e===""}const VY={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Sr("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);return typeof r=="string"?Xs.includesString:typeof r=="number"?Xs.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?Xs.equals:Array.isArray(r)?Xs.arrIncludes:Xs.weakEquals},e.getFilterFn=()=>{var n,r;return Zg(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:Xs[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,s;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const s=e.getFilterFn(),o=r==null?void 0:r.find(d=>d.id===e.id),a=na(n,o?o.value:void 0);if(eE(s,a,e)){var l;return(l=r==null?void 0:r.filter(d=>d.id!==e.id))!=null?l:[]}const c={id:e.id,value:a};if(o){var i;return(i=r==null?void 0:r.map(d=>d.id===e.id?c:d))!=null?i:[]}return r!=null&&r.length?[...r,c]:[c]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=s=>{var o;return(o=na(t,s))==null?void 0:o.filter(a=>{const l=n.find(c=>c.id===a.id);if(l){const c=l.getFilterFn();if(eE(c,a.value,l))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function eE(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const HY=(e,t,n)=>n.reduce((r,s)=>{const o=s.getValue(e);return r+(typeof o=="number"?o:0)},0),KY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},qY=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r=o)&&(r=o)}),r},WY=(e,t,n)=>{let r,s;return n.forEach(o=>{const a=o.getValue(e);a!=null&&(r===void 0?a>=a&&(r=s=a):(r>a&&(r=a),s{let n=0,r=0;if(t.forEach(s=>{let o=s.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},JY=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!LY(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,a)=>o-a);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},QY=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),ZY=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,YY=(e,t)=>t.length,mv={sum:HY,min:KY,max:qY,extent:WY,mean:GY,median:JY,unique:QY,uniqueCount:ZY,count:YY},XY={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Sr("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n==null?void 0:n.getValue(e.id);if(typeof r=="number")return mv.sum;if(Object.prototype.toString.call(r)==="[object Date]")return mv.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:mv[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function eX(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(a=>a.id===o)).filter(Boolean),...r]}const tX={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Sr("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=De(n=>[Nc(t,n)],n=>n.findIndex(r=>r.id===e.id),Ae(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Nc(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const s=Nc(t,n);return((r=s[s.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=De(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>s=>{let o=[];if(!(t!=null&&t.length))o=s;else{const a=[...t],l=[...s];for(;l.length&&a.length;){const c=a.shift(),i=l.findIndex(d=>d.id===c);i>-1&&o.push(l.splice(i,1)[0])}o=[...o,...l]}return eX(o,n,r)},Ae(e.options,"debugTable"))}},vv=()=>({left:[],right:[]}),nX={getInitialState:e=>({columnPinning:vv(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Sr("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var o,a;if(n==="right"){var l,c;return{left:((l=s==null?void 0:s.left)!=null?l:[]).filter(p=>!(r!=null&&r.includes(p))),right:[...((c=s==null?void 0:s.right)!=null?c:[]).filter(p=>!(r!=null&&r.includes(p))),...r]}}if(n==="left"){var i,d;return{left:[...((i=s==null?void 0:s.left)!=null?i:[]).filter(p=>!(r!=null&&r.includes(p))),...r],right:((d=s==null?void 0:s.right)!=null?d:[]).filter(p=>!(r!=null&&r.includes(p)))}}return{left:((o=s==null?void 0:s.left)!=null?o:[]).filter(p=>!(r!=null&&r.includes(p))),right:((a=s==null?void 0:s.right)!=null?a:[]).filter(p=>!(r!=null&&r.includes(p)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var s,o,a;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(a=t.options.enableColumnPinning)!=null?a:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(l=>l.id),{left:r,right:s}=t.getState().columnPinning,o=n.some(l=>r==null?void 0:r.includes(l)),a=n.some(l=>s==null?void 0:s.includes(l));return o?"left":a?"right":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();return s?(n=(r=t.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(a=>!o.includes(a.column.id))},Ae(t.options,"debugRows")),e.getLeftVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),Ae(t.options,"debugRows")),e.getRightVisibleCells=De(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(a=>a.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),Ae(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?vv():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:vv())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getRightLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),Ae(e.options,"debugColumns")),e.getCenterLeafColumns=De(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const s=[...n??[],...r??[]];return t.filter(o=>!s.includes(o.id))},Ae(e.options,"debugColumns"))}},Gf={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},yv=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),rX={getDefaultColumnDef:()=>Gf,getInitialState:e=>({columnSizing:{},columnSizingInfo:yv(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Sr("columnSizing",e),onColumnSizingInfoChange:Sr("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,s;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:Gf.minSize,(r=o??e.columnDef.size)!=null?r:Gf.size),(s=e.columnDef.maxSize)!=null?s:Gf.maxSize)},e.getStart=De(n=>[n,Nc(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.getAfter=De(n=>[n,Nc(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),Ae(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...s}=n;return s})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),s=r==null?void 0:r.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),bv(o)&&o.touches&&o.touches.length>1))return;const a=e.getSize(),l=e?e.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[r.id,r.getSize()]],c=bv(o)?Math.round(o.touches[0].clientX):o.clientX,i={},d=(b,y)=>{typeof y=="number"&&(t.setColumnSizingInfo(w=>{var S,E;const C=t.options.columnResizeDirection==="rtl"?-1:1,k=(y-((S=w==null?void 0:w.startOffset)!=null?S:0))*C,T=Math.max(k/((E=w==null?void 0:w.startSize)!=null?E:0),-.999999);return w.columnSizingStart.forEach(P=>{let[N,U]=P;i[N]=Math.round(Math.max(U+U*T,0)*100)/100}),{...w,deltaOffset:k,deltaPercentage:T}}),(t.options.columnResizeMode==="onChange"||b==="end")&&t.setColumnSizing(w=>({...w,...i})))},p=b=>d("move",b),f=b=>{d("end",b),t.setColumnSizingInfo(y=>({...y,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},h=n||typeof document<"u"?document:null,g={moveHandler:b=>p(b.clientX),upHandler:b=>{h==null||h.removeEventListener("mousemove",g.moveHandler),h==null||h.removeEventListener("mouseup",g.upHandler),f(b.clientX)}},m={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),p(b.touches[0].clientX),!1),upHandler:b=>{var y;h==null||h.removeEventListener("touchmove",m.moveHandler),h==null||h.removeEventListener("touchend",m.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),f((y=b.touches[0])==null?void 0:y.clientX)}},x=sX()?{passive:!1}:!1;bv(o)?(h==null||h.addEventListener("touchmove",m.moveHandler,x),h==null||h.addEventListener("touchend",m.upHandler,x)):(h==null||h.addEventListener("mousemove",g.moveHandler,x),h==null||h.addEventListener("mouseup",g.upHandler,x)),t.setColumnSizingInfo(b=>({...b,startOffset:c,startSize:a,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?yv():(n=e.initialState.columnSizingInfo)!=null?n:yv())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0}}};let Jf=null;function sX(){if(typeof Jf=="boolean")return Jf;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return Jf=e,Jf}function bv(e){return e.type==="touchstart"}const oX={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Sr("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const s=e.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=De(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),Ae(t.options,"debugRows")),e.getVisibleCells=De(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],Ae(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>De(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),Ae(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Nc(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const aX={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},iX={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Sr("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,s,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>Xs.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return Zg(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:Xs[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},lX={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Sr("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var s,o;e.setExpanded(r?{}:(s=(o=e.initialState)==null?void 0:o.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const a=o.split(".");r=Math.max(r,a.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[e.id]);let a={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(l=>{a[l]=!0}):a=r,n=(s=n)!=null?s:!o,!o&&n)return{...a,[e.id]:!0};if(o&&!n){const{[e.id]:l,...c}=a;return c}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r!=null&&r[e.id])},e.getCanExpand=()=>{var n,r,s;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Sb=0,Cb=10,xv=()=>({pageIndex:Sb,pageSize:Cb}),uX={getInitialState:e=>({...e,pagination:{...xv(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:Sr("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const s=o=>na(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=r=>{var s;e.setPagination(r?xv():(s=e.initialState.pagination)!=null?s:xv())},e.setPageIndex=r=>{e.setPagination(s=>{let o=na(r,s.pageIndex);const a=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,a)),{...s,pageIndex:o}})},e.resetPageIndex=r=>{var s,o;e.setPageIndex(r?Sb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Sb)},e.resetPageSize=r=>{var s,o;e.setPageSize(r?Cb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:Cb)},e.setPageSize=r=>{e.setPagination(s=>{const o=Math.max(1,na(r,s.pageSize)),a=s.pageSize*s.pageIndex,l=Math.floor(a/o);return{...s,pageIndex:l,pageSize:o}})},e.setPageCount=r=>e.setPagination(s=>{var o;let a=na(r,(o=e.options.pageCount)!=null?o:-1);return typeof a=="number"&&(a=Math.max(-1,a)),{...s,pageCount:a}}),e.getPageOptions=De(()=>[e.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,a)=>a)),s},Ae(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},wv=()=>({top:[],bottom:[]}),cX={getInitialState:e=>({rowPinning:wv(),...e}),getDefaultOptions:e=>({onRowPinningChange:Sr("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,s)=>{const o=r?e.getLeafRows().map(c=>{let{id:i}=c;return i}):[],a=s?e.getParentRows().map(c=>{let{id:i}=c;return i}):[],l=new Set([...a,e.id,...o]);t.setRowPinning(c=>{var i,d;if(n==="bottom"){var p,f;return{top:((p=c==null?void 0:c.top)!=null?p:[]).filter(m=>!(l!=null&&l.has(m))),bottom:[...((f=c==null?void 0:c.bottom)!=null?f:[]).filter(m=>!(l!=null&&l.has(m))),...Array.from(l)]}}if(n==="top"){var h,g;return{top:[...((h=c==null?void 0:c.top)!=null?h:[]).filter(m=>!(l!=null&&l.has(m))),...Array.from(l)],bottom:((g=c==null?void 0:c.bottom)!=null?g:[]).filter(m=>!(l!=null&&l.has(m)))}}return{top:((i=c==null?void 0:c.top)!=null?i:[]).filter(m=>!(l!=null&&l.has(m))),bottom:((d=c==null?void 0:c.bottom)!=null?d:[]).filter(m=>!(l!=null&&l.has(m)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=t.options;return typeof r=="function"?r(e):(n=r??s)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:s}=t.getState().rowPinning,o=n.some(l=>r==null?void 0:r.includes(l)),a=n.some(l=>s==null?void 0:s.includes(l));return o?"top":a?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();if(!s)return-1;const o=(n=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(a=>{let{id:l}=a;return l});return(r=o==null?void 0:o.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?wv():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:wv())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(n??[]).map(a=>{const l=e.getRow(a,!0);return l.getIsAllParentsExpanded()?l:null}):(n??[]).map(a=>t.find(l=>l.id===a))).filter(Boolean).map(a=>({...a,position:r}))},e.getTopRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),Ae(e.options,"debugRows")),e.getBottomRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),Ae(e.options,"debugRows")),e.getCenterRows=De(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const s=new Set([...n??[],...r??[]]);return t.filter(o=>!s.has(o.id))},Ae(e.options,"debugRows"))}},dX={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Sr("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...n};return e.getRowModel().rows.forEach(o=>{Eb(s,o.id,r,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=De(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getFilteredSelectedRowModel=De(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getGroupedSelectedRowModel=De(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?Sv(e,n):{rows:[],flatRows:[],rowsById:{}},Ae(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(s=>!n[s.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const s=e.getIsSelected();t.setRowSelection(o=>{var a;if(n=typeof n<"u"?n:!s,e.getCanSelect()&&s===n)return o;const l={...o};return Eb(l,e.id,n,(a=r==null?void 0:r.selectChildren)!=null?a:!0,t),l})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return zw(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var s;n&&e.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},Eb=(e,t,n,r,s)=>{var o;const a=s.getRow(t,!0);n?(a.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),a.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=a.subRows)!=null&&o.length&&a.getCanSelectSubRows()&&a.subRows.forEach(l=>Eb(e,l.id,n,r,s))};function Sv(e,t){const n=e.getState().rowSelection,r=[],s={},o=function(a,l){return a.map(c=>{var i;const d=zw(c,n);if(d&&(r.push(c),s[c.id]=c),(i=c.subRows)!=null&&i.length&&(c={...c,subRows:o(c.subRows)}),d)return c}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:s}}function zw(e,t){var n;return(n=t[e.id])!=null?n:!1}function Tb(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return e.subRows.forEach(a=>{if(!(o&&!s)&&(a.getCanSelect()&&(zw(a,t)?o=!0:s=!1),a.subRows&&a.subRows.length)){const l=Tb(a,t);l==="all"?o=!0:(l==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const kb=/([0-9]+)/gm,fX=(e,t,n)=>wI(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),pX=(e,t,n)=>wI(Sa(e.getValue(n)),Sa(t.getValue(n))),hX=(e,t,n)=>Uw(Sa(e.getValue(n)).toLowerCase(),Sa(t.getValue(n)).toLowerCase()),gX=(e,t,n)=>Uw(Sa(e.getValue(n)),Sa(t.getValue(n))),mX=(e,t,n)=>{const r=e.getValue(n),s=t.getValue(n);return r>s?1:rUw(e.getValue(n),t.getValue(n));function Uw(e,t){return e===t?0:e>t?1:-1}function Sa(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function wI(e,t){const n=e.split(kb).filter(Boolean),r=t.split(kb).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),a=parseInt(s,10),l=parseInt(o,10),c=[a,l].sort();if(isNaN(c[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(c[1]))return isNaN(a)?-1:1;if(a>l)return 1;if(l>a)return-1}return n.length-r.length}const rc={alphanumeric:fX,alphanumericCaseSensitive:pX,text:hX,textCaseSensitive:gX,datetime:mX,basic:vX},yX={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Sr("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s==null?void 0:s.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return rc.datetime;if(typeof o=="string"&&(r=!0,o.split(kb).length>1))return rc.alphanumeric}return r?rc.text:rc.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof(n==null?void 0:n.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return Zg(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:rc[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const s=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(a=>{const l=a==null?void 0:a.find(h=>h.id===e.id),c=a==null?void 0:a.findIndex(h=>h.id===e.id);let i=[],d,p=o?n:s==="desc";if(a!=null&&a.length&&e.getCanMultiSort()&&r?l?d="toggle":d="add":a!=null&&a.length&&c!==a.length-1?d="replace":l?d="toggle":d="replace",d==="toggle"&&(o||s||(d="remove")),d==="add"){var f;i=[...a,{id:e.id,desc:p}],i.splice(0,i.length-((f=t.options.maxMultiSortColCount)!=null?f:Number.MAX_SAFE_INTEGER))}else d==="toggle"?i=a.map(h=>h.id===e.id?{...h,desc:p}:h):d==="remove"?i=a.filter(h=>h.id!==e.id):i=[{id:e.id,desc:p}];return i})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,s;const o=e.getFirstSortDir(),a=e.getIsSorted();return a?a!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(s=t.options.enableMultiRemove)!=null)||s)?!1:a==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(s=>s.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},bX=[zY,oX,tX,nX,UY,VY,aX,iX,yX,XY,lX,uX,cX,dX,rX];function xX(e){var t,n;const r=[...bX,...(t=e._features)!=null?t:[]];let s={_features:r};const o=s._features.reduce((f,h)=>Object.assign(f,h.getDefaultOptions==null?void 0:h.getDefaultOptions(s)),{}),a=f=>s.options.mergeOptions?s.options.mergeOptions(o,f):{...o,...f};let c={...{},...(n=e.initialState)!=null?n:{}};s._features.forEach(f=>{var h;c=(h=f.getInitialState==null?void 0:f.getInitialState(c))!=null?h:c});const i=[];let d=!1;const p={_features:r,options:{...o,...e},initialState:c,_queue:f=>{i.push(f),d||(d=!0,Promise.resolve().then(()=>{for(;i.length;)i.shift()();d=!1}).catch(h=>setTimeout(()=>{throw h})))},reset:()=>{s.setState(s.initialState)},setOptions:f=>{const h=na(f,s.options);s.options=a(h)},getState:()=>s.options.state,setState:f=>{s.options.onStateChange==null||s.options.onStateChange(f)},_getRowId:(f,h,g)=>{var m;return(m=s.options.getRowId==null?void 0:s.options.getRowId(f,h,g))!=null?m:`${g?[g.id,h].join("."):h}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(f,h)=>{let g=(h?s.getPrePaginationRowModel():s.getRowModel()).rowsById[f];if(!g&&(g=s.getCoreRowModel().rowsById[f],!g))throw new Error;return g},_getDefaultColumnDef:De(()=>[s.options.defaultColumn],f=>{var h;return f=(h=f)!=null?h:{},{header:g=>{const m=g.header.column.columnDef;return m.accessorKey?m.accessorKey:m.accessorFn?m.id:null},cell:g=>{var m,x;return(m=(x=g.renderValue())==null||x.toString==null?void 0:x.toString())!=null?m:null},...s._features.reduce((g,m)=>Object.assign(g,m.getDefaultColumnDef==null?void 0:m.getDefaultColumnDef()),{}),...f}},Ae(e,"debugColumns")),_getColumnDefs:()=>s.options.columns,getAllColumns:De(()=>[s._getColumnDefs()],f=>{const h=function(g,m,x){return x===void 0&&(x=0),g.map(b=>{const y=BY(s,b,x,m),w=b;return y.columns=w.columns?h(w.columns,y,x+1):[],y})};return h(f)},Ae(e,"debugColumns")),getAllFlatColumns:De(()=>[s.getAllColumns()],f=>f.flatMap(h=>h.getFlatColumns()),Ae(e,"debugColumns")),_getAllFlatColumnsById:De(()=>[s.getAllFlatColumns()],f=>f.reduce((h,g)=>(h[g.id]=g,h),{}),Ae(e,"debugColumns")),getAllLeafColumns:De(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(f,h)=>{let g=f.flatMap(m=>m.getLeafColumns());return h(g)},Ae(e,"debugColumns")),getColumn:f=>s._getAllFlatColumnsById()[f]};Object.assign(s,p);for(let f=0;fDe(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,a){o===void 0&&(o=0);const l=[];for(let i=0;ie._autoResetPageIndex()))}function SX(e,t,n){return n.options.filterFromLeafRows?CX(e,t,n):EX(e,t,n)}function CX(e,t,n){var r;const s=[],o={},a=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,l=function(c,i){i===void 0&&(i=0);const d=[];for(let f=0;fDe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let f=0;f{var h;const g=e.getColumn(f.id);if(!g)return;const m=g.getFilterFn();m&&s.push({id:f.id,filterFn:m,resolvedValue:(h=m.resolveFilterValue==null?void 0:m.resolveFilterValue(f.value))!=null?h:f.value})});const a=(n??[]).map(f=>f.id),l=e.getGlobalFilterFn(),c=e.getAllLeafColumns().filter(f=>f.getCanGlobalFilter());r&&l&&c.length&&(a.push("__global__"),c.forEach(f=>{var h;o.push({id:f.id,filterFn:l,resolvedValue:(h=l.resolveFilterValue==null?void 0:l.resolveFilterValue(r))!=null?h:r})}));let i,d;for(let f=0;f{h.columnFiltersMeta[m]=x})}if(o.length){for(let g=0;g{h.columnFiltersMeta[m]=x})){h.columnFilters.__global__=!0;break}}h.columnFilters.__global__!==!0&&(h.columnFilters.__global__=!1)}}const p=f=>{for(let h=0;he._autoResetPageIndex()))}function kX(){return e=>De(()=>[e.getState().grouping,e.getPreGroupedRowModel()],(t,n)=>{if(!n.rows.length||!t.length)return n.rows.forEach(c=>{c.depth=0,c.parentId=void 0}),n;const r=t.filter(c=>e.getColumn(c)),s=[],o={},a=function(c,i,d){if(i===void 0&&(i=0),i>=r.length)return c.map(g=>(g.depth=i,s.push(g),o[g.id]=g,g.subRows&&(g.subRows=a(g.subRows,i+1,g.id)),g));const p=r[i],f=_X(c,p);return Array.from(f.entries()).map((g,m)=>{let[x,b]=g,y=`${p}:${x}`;y=d?`${d}>${y}`:y;const w=a(b,i+1,y);w.forEach(C=>{C.parentId=y});const S=i?fI(b,C=>C.subRows):b,E=Yg(e,y,S[0].original,m,i,void 0,d);return Object.assign(E,{groupingColumnId:p,groupingValue:x,subRows:w,leafRows:S,getValue:C=>{if(r.includes(C)){if(E._valuesCache.hasOwnProperty(C))return E._valuesCache[C];if(b[0]){var k;E._valuesCache[C]=(k=b[0].getValue(C))!=null?k:void 0}return E._valuesCache[C]}if(E._groupingValuesCache.hasOwnProperty(C))return E._groupingValuesCache[C];const T=e.getColumn(C),P=T==null?void 0:T.getAggregationFn();if(P)return E._groupingValuesCache[C]=P(C,S,b),E._groupingValuesCache[C]}}),w.forEach(C=>{s.push(C),o[C.id]=C}),E})},l=a(n.rows,0);return l.forEach(c=>{s.push(c),o[c.id]=c}),{rows:l,flatRows:s,rowsById:o}},Ae(e.options,"debugTable","getGroupedRowModel",()=>{e._queue(()=>{e._autoResetExpanded(),e._autoResetPageIndex()})}))}function _X(e,t){const n=new Map;return e.reduce((r,s)=>{const o=`${s.getGroupingValue(t)}`,a=r.get(o);return a?a.push(s):r.set(o,[s]),r},n)}function jX(){return e=>De(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,s=[],o=r.filter(c=>{var i;return(i=e.getColumn(c.id))==null?void 0:i.getCanSort()}),a={};o.forEach(c=>{const i=e.getColumn(c.id);i&&(a[c.id]={sortUndefined:i.columnDef.sortUndefined,invertSorting:i.columnDef.invertSorting,sortingFn:i.getSortingFn()})});const l=c=>{const i=c.map(d=>({...d}));return i.sort((d,p)=>{for(let h=0;h{var p;s.push(d),(p=d.subRows)!=null&&p.length&&(d.subRows=l(d.subRows))}),i};return{rows:l(n.rows),flatRows:s,rowsById:n.rowsById}},Ae(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** - * react-table - * - * Copyright (c) TanStack - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function tE(e,t){return e?RX(e)?v.createElement(e,t):e:null}function RX(e){return PX(e)||typeof e=="function"||MX(e)}function PX(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function MX(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function OX(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=v.useState(()=>({current:xX(t)})),[r,s]=v.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const SI=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{className:"relative w-full overflow-auto",children:u.jsx("table",{ref:n,className:ge("w-full caption-bottom text-sm",e),...t})}));SI.displayName="Table";const CI=v.forwardRef(({className:e,...t},n)=>u.jsx("thead",{ref:n,className:ge("[&_tr]:border-b",e),...t}));CI.displayName="TableHeader";const EI=v.forwardRef(({className:e,...t},n)=>u.jsx("tbody",{ref:n,className:ge("[&_tr:last-child]:border-0",e),...t}));EI.displayName="TableBody";const NX=v.forwardRef(({className:e,...t},n)=>u.jsx("tfoot",{ref:n,className:ge("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));NX.displayName="TableFooter";const vc=v.forwardRef(({className:e,...t},n)=>u.jsx("tr",{ref:n,className:ge("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));vc.displayName="TableRow";const TI=v.forwardRef(({className:e,...t},n)=>u.jsx("th",{ref:n,className:ge("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));TI.displayName="TableHead";const Ep=v.forwardRef(({className:e,...t},n)=>u.jsx("td",{ref:n,className:ge("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));Ep.displayName="TableCell";const IX=v.forwardRef(({className:e,...t},n)=>u.jsx("caption",{ref:n,className:ge("mt-4 text-sm text-muted-foreground",e),...t}));IX.displayName="TableCaption";function Nu({columns:e,data:t,isLoading:n,loadingMessage:r,noResultsMessage:s,enableHeaders:o=!0,className:a,highlightedRows:l,...c}){var d;const i=OX({...c,data:t,columns:e,getCoreRowModel:wX(),getFilteredRowModel:TX(),getGroupedRowModel:kX(),getSortedRowModel:jX()});return u.jsx("div",{className:ge("rounded-md border",a),children:u.jsxs(SI,{children:[o&&u.jsx(CI,{children:i.getHeaderGroups().map(p=>u.jsx(vc,{children:p.headers.map(f=>u.jsx(TI,{children:f.isPlaceholder?null:tE(f.column.columnDef.header,f.getContext())},f.id))},p.id))}),u.jsx(EI,{children:n?u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center text-muted-foreground",children:r??"Carregando..."})}):u.jsx(u.Fragment,{children:(d=i.getRowModel().rows)!=null&&d.length?i.getRowModel().rows.map(p=>u.jsx(vc,{"data-state":p.getIsSelected()?"selected":l!=null&&l.includes(p.id)?"highlighted":"",children:p.getVisibleCells().map(f=>u.jsx(Ep,{children:tE(f.column.columnDef.cell,f.getContext())},f.id))},p.id)):u.jsx(vc,{children:u.jsx(Ep,{colSpan:e.length,className:"h-24 text-center",children:s??"Nenhum resultado encontrado!"})})})})]})})}const DX=e=>["dify","fetchSessions",JSON.stringify(e)],AX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetchSessions/${e}/${t}`)).data,FX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:DX({difyId:t,instanceName:n}),queryFn:()=>AX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function kI({difyId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusDify:r}=Qg(),[s,o]=v.useState([]),{data:a,refetch:l}=FX({difyId:e,instanceName:n==null?void 0:n.name}),[c,i]=v.useState(!1),[d,p]=v.useState("");function f(){l()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("dify.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("dify.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:c,onOpenChange:i,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("dify.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:a??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("dify.sessions.table.none")})]})]})]})}const LX=_.object({enabled:_.boolean(),description:_.string(),botType:_.string(),apiUrl:_.string(),apiKey:_.string(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function _I({initialData:e,onSubmit:t,handleDelete:n,difyId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(LX),defaultValues:e||{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("dify.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("dify.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.difySettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:c("dify.form.botType.label"),options:[{label:c("dify.form.botType.chatBot"),value:"chatBot"},{label:c("dify.form.botType.textGenerator"),value:"textGenerator"},{label:c("dify.form.botType.agent"),value:"agent"},{label:c("dify.form.botType.workflow"),value:"workflow"}]}),u.jsx(G,{name:"apiUrl",label:c("dify.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("dify.form.apiKey.label"),required:!0,children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("dify.form.triggerType.label"),options:[{label:c("dify.form.triggerType.keyword"),value:"keyword"},{label:c("dify.form.triggerType.all"),value:"all"},{label:c("dify.form.triggerType.advanced"),value:"advanced"},{label:c("dify.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("dify.form.triggerOperator.label"),options:[{label:c("dify.form.triggerOperator.contains"),value:"contains"},{label:c("dify.form.triggerOperator.equals"),value:"equals"},{label:c("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("dify.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("dify.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("dify.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("dify.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("dify.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("dify.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("dify.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("dify.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("dify.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("dify.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("dify.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("dify.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("dify.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("dify.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(kI,{difyId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"dify.button.saving":"dify.button.update")})]})]})]})})}function $X({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createDify:l}=Qg(),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:i.enabled,description:i.description,botType:i.botType,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await l({instanceName:n.name,token:n.token,data:h}),X.success(t("dify.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("dify.form.title")})}),u.jsx(_I,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const BX=e=>["dify","getDify",JSON.stringify(e)],zX=async({difyId:e,instanceName:t})=>(await he.get(`/dify/fetch/${e}/${t}`)).data,UX=e=>{const{difyId:t,instanceName:n,...r}=e;return lt({...r,queryKey:BX({difyId:t,instanceName:n}),queryFn:()=>zX({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function VX({difyId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteDify:l,updateDify:c}=Qg(),{data:i,isLoading:d}=UX({difyId:e,instanceName:r==null?void 0:r.name}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",botType:(i==null?void 0:i.botType)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:(i==null?void 0:i.triggerValue)??"",expire:(i==null?void 0:i.expire)??0,keywordFinish:(i==null?void 0:i.keywordFinish)??"",delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:(i==null?void 0:i.unknownMessage)??"",listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,difyId:e,data:y}),X.success(n("dify.toast.success.update")),t(),s(`/manager/instance/${r.id}/dify/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,difyId:e}),X.success(n("dify.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/dify`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(_I,{initialData:p,onSubmit:f,difyId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function nE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{difyId:r}=So(),{data:s,refetch:o,isLoading:a}=dI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/dify/${d}`)},i=()=>{o()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(kI,{}),u.jsx(FY,{}),u.jsx($X,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(q,{variant:"link",children:e("dify.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(VX,{difyId:r,resetTable:i})})]})]})]})}const HX=e=>["evolutionBot","findEvolutionBot",JSON.stringify(e)],KX=async({instanceName:e,token:t})=>(await he.get(`/evolutionBot/find/${e}`,{headers:{apiKey:t}})).data,jI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:HX({instanceName:t}),queryFn:()=>KX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},qX=e=>["evolutionBot","fetchDefaultSettings",JSON.stringify(e)],WX=async({instanceName:e,token:t})=>{const n=await he.get(`/evolutionBot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},GX=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:qX({instanceName:t}),queryFn:()=>WX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},JX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/create/${e}`,n,{headers:{apikey:t}})).data,QX=async({instanceName:e,token:t,evolutionBotId:n,data:r})=>(await he.put(`/evolutionBot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,ZX=async({instanceName:e,evolutionBotId:t})=>(await he.delete(`/evolutionBot/delete/${t}/${e}`)).data,YX=async({instanceName:e,token:t,data:n})=>(await he.post(`/evolutionBot/settings/${e}`,n,{headers:{apikey:t}})).data,XX=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/evolutionBot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Xg(){const e=Ye(YX,{invalidateKeys:[["evolutionBot","fetchDefaultSettings"]]}),t=Ye(XX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","fetchSessions"]]}),n=Ye(ZX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),r=Ye(QX,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),s=Ye(JX,{invalidateKeys:[["evolutionBot","findEvolutionBot"]]});return{setDefaultSettingsEvolutionBot:e,changeStatusEvolutionBot:t,deleteEvolutionBot:n,updateEvolutionBot:r,createEvolutionBot:s}}const eee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),botIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function tee(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{data:s,refetch:o}=GX({instanceName:t==null?void 0:t.name,enabled:n}),{data:a,refetch:l}=jI({instanceName:t==null?void 0:t.name,enabled:n}),{setDefaultSettingsEvolutionBot:c}=Xg(),i=sn({resolver:on(eee),defaultValues:{expire:"0",keywordFinish:e("evolutionBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evolutionBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{s&&i.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback,splitMessages:s.splitMessages,timePerChar:s.timePerChar?s.timePerChar.toString():"0"})},[s]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await c({instanceName:t.name,token:t.token,data:x}),X.success(e("evolutionBot.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){o(),l()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("evolutionBot.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("evolutionBot.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"botIdFallback",label:e("evolutionBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("evolutionBot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("evolutionBot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("evolutionBot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("evolutionBot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("evolutionBot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("evolutionBot.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("evolutionBot.form.ignoreJids.label"),placeholder:e("evolutionBot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("evolutionBot.button.save")})})]})})]})]})}const nee=e=>["evolutionBot","fetchSessions",JSON.stringify(e)],ree=async({instanceName:e,evolutionBotId:t,token:n})=>(await he.get(`/evolutionBot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,see=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:nee({instanceName:t}),queryFn:()=>ree({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function RI({evolutionBotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[l,c]=v.useState(""),{data:i,refetch:d}=see({instanceName:n==null?void 0:n.name,evolutionBotId:e,enabled:o}),{changeStatusEvolutionBot:p}=Xg();function f(){d()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await p({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("evolutionBot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("evolutionBot.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("evolutionBot.sessions.search"),value:l,onChange:m=>c(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:i??[],onSortingChange:s,state:{sorting:r,globalFilter:l},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("evolutionBot.sessions.table.none")})]})]})]})}const oee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function PI({initialData:e,onSubmit:t,handleDelete:n,evolutionBotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(oee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("evolutionBot.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("evolutionBot.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.evolutionBotSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"apiUrl",label:c("evolutionBot.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("evolutionBot.form.apiKey.label"),children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("evolutionBot.form.triggerType.label"),options:[{label:c("evolutionBot.form.triggerType.keyword"),value:"keyword"},{label:c("evolutionBot.form.triggerType.all"),value:"all"},{label:c("evolutionBot.form.triggerType.advanced"),value:"advanced"},{label:c("evolutionBot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("evolutionBot.form.triggerOperator.label"),options:[{label:c("evolutionBot.form.triggerOperator.contains"),value:"contains"},{label:c("evolutionBot.form.triggerOperator.equals"),value:"equals"},{label:c("evolutionBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("evolutionBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("evolutionBot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("evolutionBot.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("evolutionBot.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("evolutionBot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("evolutionBot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("evolutionBot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("evolutionBot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("evolutionBot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("evolutionBot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("evolutionBot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("evolutionBot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("evolutionBot.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("evolutionBot.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(RI,{evolutionBotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"evolutionBot.button.saving":"evolutionBot.button.update")})]})]})]})})}function aee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState(!1),[o,a]=v.useState(!1),{createEvolutionBot:l}=Xg(),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar?i.timePerChar:0};await l({instanceName:n.name,token:n.token,data:h}),X.success(t("evolutionBot.toast.success.create")),a(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{s(!1)}};return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("evolutionBot.form.title")})}),u.jsx(PI,{onSubmit:c,isModal:!0,isLoading:r})]})]})}const iee=e=>["evolutionBot","getEvolutionBot",JSON.stringify(e)],lee=async({instanceName:e,token:t,evolutionBotId:n})=>{const r=await he.get(`/evolutionBot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},uee=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return lt({...s,queryKey:iee({instanceName:t}),queryFn:()=>lee({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function cee({evolutionBotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteEvolutionBot:l,updateEvolutionBot:c}=Xg(),{data:i,isLoading:d}=uee({instanceName:r==null?void 0:r.name,evolutionBotId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:i!=null&&i.timePerChar?i==null?void 0:i.timePerChar:0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar?g.timePerChar:0};await c({instanceName:r.name,evolutionBotId:e,data:y}),X.success(n("evolutionBot.toast.success.update")),t(),s(`/manager/instance/${r.id}/evolutionBot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,evolutionBotId:e}),X.success(n("evolutionBot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/evolutionBot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir evolutionBot:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(PI,{initialData:p,onSubmit:f,evolutionBotId:e,handleDelete:h,isModal:!1,openDeletionDialog:o,setOpenDeletionDialog:a})})}function rE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{evolutionBotId:r}=So(),{data:s,isLoading:o,refetch:a}=jI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/evolutionBot/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("evolutionBot.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(RI,{}),u.jsx(tee,{}),u.jsx(aee,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(q,{variant:"link",children:e("evolutionBot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(cee,{evolutionBotId:r,resetTable:i})})]})]})]})}const dee=e=>["flowise","findFlowise",JSON.stringify(e)],fee=async({instanceName:e,token:t})=>(await he.get(`/flowise/find/${e}`,{headers:{apiKey:t}})).data,MI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:dee({instanceName:t}),queryFn:()=>fee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},pee=e=>["flowise","fetchDefaultSettings",JSON.stringify(e)],hee=async({instanceName:e,token:t})=>{const n=await he.get(`/flowise/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},gee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:pee({instanceName:t}),queryFn:()=>hee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},mee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,vee=async({instanceName:e,flowiseId:t,data:n})=>(await he.put(`/flowise/update/${t}/${e}`,n)).data,yee=async({instanceName:e,flowiseId:t})=>(await he.delete(`/flowise/delete/${t}/${e}`)).data,bee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,xee=async({instanceName:e,token:t,data:n})=>(await he.post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data;function em(){const e=Ye(xee,{invalidateKeys:[["flowise","fetchDefaultSettings"]]}),t=Ye(bee,{invalidateKeys:[["flowise","getFlowise"],["flowise","fetchSessions"]]}),n=Ye(yee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),r=Ye(vee,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),s=Ye(mee,{invalidateKeys:[["flowise","findFlowise"]]});return{setDefaultSettingsFlowise:e,changeStatusFlowise:t,deleteFlowise:n,updateFlowise:r,createFlowise:s}}const wee=_.object({expire:_.string(),keywordFinish:_.string(),delayMessage:_.string(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.string(),ignoreJids:_.array(_.string()).default([]),flowiseIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean(),timePerChar:_.string()});function See(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsFlowise:n}=em(),[r,s]=v.useState(!1),{data:o,refetch:a}=gee({instanceName:t==null?void 0:t.name,enabled:r}),{data:l,refetch:c}=MI({instanceName:t==null?void 0:t.name,enabled:r}),i=sn({resolver:on(wee),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});v.useEffect(()=>{o&&i.reset({expire:o!=null&&o.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",ignoreJids:o.ignoreJids,flowiseIdFallback:o.flowiseIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar?o.timePerChar.toString():"0"})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids,splitMessages:f.splitMessages,timePerChar:parseInt(f.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),X.success(e("flowise.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("flowise.defaultSettings")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(l==null?void 0:l.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),u.jsx(G,{name:"expire",label:e("flowise.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("flowise.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const Cee=e=>["flowise","fetchSessions",JSON.stringify(e)],Eee=async({instanceName:e,flowiseId:t,token:n})=>(await he.get(`/flowise/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Tee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:Cee({instanceName:t}),queryFn:()=>Eee({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function OI({flowiseId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusFlowise:r}=em(),[s,o]=v.useState([]),[a,l]=v.useState(!1),[c,i]=v.useState(""),{data:d,refetch:p}=Tee({instanceName:n==null?void 0:n.name,flowiseId:e,enabled:a});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("flowise.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("flowise.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("flowise.sessions.search"),value:c,onChange:m=>i(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{})})]}),u.jsx(Nu,{columns:g,data:d??[],onSortingChange:o,state:{sorting:s,globalFilter:c},onGlobalFilterChange:i,enableGlobalFilter:!0,noResultsMessage:t("flowise.sessions.table.none")})]})]})]})}const kee=_.object({enabled:_.boolean(),description:_.string(),apiUrl:_.string(),apiKey:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function NI({initialData:e,onSubmit:t,handleDelete:n,flowiseId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(kee),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("flowise.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("flowise.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.flowiseSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"apiUrl",label:c("flowise.form.apiUrl.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:c("flowise.form.apiKey.label"),children:u.jsx(K,{type:"password"})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("flowise.form.triggerType.label"),options:[{label:c("flowise.form.triggerType.keyword"),value:"keyword"},{label:c("flowise.form.triggerType.all"),value:"all"},{label:c("flowise.form.triggerType.advanced"),value:"advanced"},{label:c("flowise.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("flowise.form.triggerOperator.label"),options:[{label:c("flowise.form.triggerOperator.contains"),value:"contains"},{label:c("flowise.form.triggerOperator.equals"),value:"equals"},{label:c("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("flowise.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("flowise.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("flowise.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("flowise.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("flowise.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("flowise.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("flowise.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("flowise.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("flowise.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("flowise.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("flowise.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("flowise.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:c("flowise.form.splitMessages.label"),reverse:!0}),i.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:c("flowise.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(OI,{flowiseId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"flowise.button.saving":"flowise.button.update")})]})]})]})})}function _ee({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createFlowise:r}=em(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,apiUrl:i.apiUrl,apiKey:i.apiKey,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("flowise.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("flowise.form.title")})}),u.jsx(NI,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const jee=e=>["flowise","getFlowise",JSON.stringify(e)],Ree=async({instanceName:e,token:t,flowiseId:n})=>{const r=await he.get(`/flowise/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Pee=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return lt({...s,queryKey:jee({instanceName:t}),queryFn:()=>Ree({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function Mee({flowiseId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteFlowise:l,updateFlowise:c}=em(),{data:i,isLoading:d}=Pee({instanceName:r==null?void 0:r.name,flowiseId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",apiUrl:(i==null?void 0:i.apiUrl)??"",apiKey:(i==null?void 0:i.apiKey)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)??0,splitMessages:(i==null?void 0:i.splitMessages)??!1,timePerChar:(i==null?void 0:i.timePerChar)??0}),[i==null?void 0:i.apiKey,i==null?void 0:i.apiUrl,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,flowiseId:e,data:y}),X.success(n("flowise.toast.success.update")),t(),s(`/manager/instance/${r.id}/flowise/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,flowiseId:e}),X.success(n("flowise.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/flowise`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(NI,{initialData:p,onSubmit:f,flowiseId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function sE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{flowiseId:r}=So(),{data:s,isLoading:o,refetch:a}=MI({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/flowise/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(OI,{}),u.jsx(See,{}),u.jsx(_ee,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:u.jsx("h4",{className:"text-base",children:d.description||d.id})},d.id)):u.jsx(q,{variant:"link",children:e("flowise.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(Mee,{flowiseId:r,resetTable:i})})]})]})]})}const Oee=e=>["openai","findOpenai",JSON.stringify(e)],Nee=async({instanceName:e,token:t})=>(await he.get(`/openai/find/${e}`,{headers:{apiKey:t}})).data,II=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Oee({instanceName:t}),queryFn:()=>Nee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Iee=e=>["openai","findOpenaiCreds",JSON.stringify(e)],Dee=async({instanceName:e,token:t})=>(await he.get(`/openai/creds/${e}`,{headers:{apiKey:t}})).data,Vw=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Iee({instanceName:t}),queryFn:()=>Dee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Aee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,Fee=async({openaiCredsId:e,instanceName:t})=>(await he.delete(`/openai/creds/${e}/${t}`)).data,Lee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,$ee=async({instanceName:e,token:t,openaiId:n,data:r})=>(await he.put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Bee=async({instanceName:e,token:t,openaiId:n})=>(await he.delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,zee=async({instanceName:e,token:t,data:n})=>(await he.post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,Uee=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function rf(){const e=Ye(zee,{invalidateKeys:[["openai","fetchDefaultSettings"]]}),t=Ye(Uee,{invalidateKeys:[["openai","getOpenai"],["openai","fetchSessions"]]}),n=Ye(Bee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),r=Ye($ee,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),s=Ye(Lee,{invalidateKeys:[["openai","findOpenai"]]}),o=Ye(Aee,{invalidateKeys:[["openai","findOpenaiCreds"]]}),a=Ye(Fee,{invalidateKeys:[["openai","findOpenaiCreds"]]});return{setDefaultSettingsOpenai:e,changeStatusOpenai:t,deleteOpenai:n,updateOpenai:r,createOpenai:s,createOpenaiCreds:o,deleteOpenaiCreds:a}}const Vee=_.object({name:_.string(),apiKey:_.string()});function Hee(){const{t:e}=ze(),{instance:t}=nt(),{createOpenaiCreds:n,deleteOpenaiCreds:r}=rf(),[s,o]=v.useState(!1),[a,l]=v.useState([]),{data:c,refetch:i}=Vw({instanceName:t==null?void 0:t.name,enabled:s}),d=sn({resolver:on(Vee),defaultValues:{name:"",apiKey:""}}),p=async m=>{var x,b,y;try{if(!t||!t.name)throw new Error("instance not found.");const w={name:m.name,apiKey:m.apiKey};await n({instanceName:t.name,token:t.token,data:w}),X.success(e("openai.toast.success.credentialsCreate")),f()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}};function f(){d.reset(),i()}const h=async m=>{var x,b,y;if(!(t!=null&&t.name)){X.error("Instance not found.");return}try{await r({openaiCredsId:m,instanceName:t==null?void 0:t.name}),X.success(e("openai.toast.success.credentialsDelete")),i()}catch(w){console.error("Error:",w),X.error(`Error: ${(y=(b=(x=w==null?void 0:w.response)==null?void 0:x.data)==null?void 0:b.response)==null?void 0:y.message}`)}},g=[{accessorKey:"name",header:({column:m})=>u.jsxs(q,{variant:"ghost",onClick:()=>m.toggleSorting(m.getIsSorted()==="asc"),children:[e("openai.credentials.table.name"),u.jsx(_3,{className:"ml-2 h-4 w-4"})]}),cell:({row:m})=>u.jsx("div",{children:m.getValue("name")})},{accessorKey:"apiKey",header:()=>u.jsx("div",{className:"text-right",children:e("openai.credentials.table.apiKey")}),cell:({row:m})=>u.jsxs("div",{children:[`${m.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:e("openai.credentials.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:e("openai.credentials.table.actions.title")}),u.jsx(Pa,{}),u.jsx(ft,{onClick:()=>h(x.id),children:e("openai.credentials.table.actions.delete")})]})]})}}];return u.jsxs(Tt,{open:s,onOpenChange:o,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(H3,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.credentials.title")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.credentials.title")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{onSubmit:d.handleSubmit(p),className:"w-full space-y-6",children:[u.jsx("div",{children:u.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[u.jsx(G,{name:"name",label:e("openai.credentials.table.name"),children:u.jsx(K,{})}),u.jsx(G,{name:"apiKey",label:e("openai.credentials.table.apiKey"),children:u.jsx(K,{type:"password"})})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("openai.button.save")})})]})}),u.jsx($t,{}),u.jsx("div",{children:u.jsx(Nu,{columns:g,data:c??[],onSortingChange:l,state:{sorting:a},noResultsMessage:e("openai.credentials.table.none")})})]})]})}const Kee=e=>["openai","fetchDefaultSettings",JSON.stringify(e)],qee=async({instanceName:e,token:t})=>{const n=await he.get(`/openai/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Wee=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Kee({instanceName:t}),queryFn:()=>qee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Gee=_.object({openaiCredsId:_.string(),expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number().default(0),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number(),speechToText:_.boolean(),ignoreJids:_.array(_.string()).default([]),openaiIdFallback:_.union([_.null(),_.string()]).optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function Jee(){const{t:e}=ze(),{instance:t}=nt(),{setDefaultSettingsOpenai:n}=rf(),[r,s]=v.useState(!1),{data:o,refetch:a}=Wee({instanceName:t==null?void 0:t.name,enabled:r}),{data:l,refetch:c}=II({instanceName:t==null?void 0:t.name,enabled:r}),{data:i}=Vw({instanceName:t==null?void 0:t.name,enabled:r}),d=sn({resolver:on(Gee),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0,splitMessages:!1,timePerChar:0}});v.useEffect(()=>{o&&d.reset({openaiCredsId:o.openaiCredsId,expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar??0})},[o]);const p=async h=>{var g,m,x;try{if(!t||!t.name)throw new Error("instance not found.");const b={openaiCredsId:h.openaiCredsId,expire:h.expire,keywordFinish:h.keywordFinish,delayMessage:h.delayMessage,unknownMessage:h.unknownMessage,listeningFromMe:h.listeningFromMe,stopBotFromMe:h.stopBotFromMe,keepOpen:h.keepOpen,debounceTime:h.debounceTime,speechToText:h.speechToText,openaiIdFallback:h.openaiIdFallback||void 0,ignoreJids:h.ignoreJids,splitMessages:h.splitMessages,timePerChar:h.timePerChar};await n({instanceName:t.name,token:t.token,data:b}),X.success(e("openai.toast.defaultSettings.success"))}catch(b){console.error("Error:",b),X.error(`Error: ${(x=(m=(g=b==null?void 0:b.response)==null?void 0:g.data)==null?void 0:m.response)==null?void 0:x.message}`)}};function f(){a(),c()}return u.jsxs(Tt,{open:r,onOpenChange:s,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("openai.defaultSettings")})}),u.jsx(Tr,{...d,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(p),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(i==null?void 0:i.filter(h=>!!h.id).map(h=>({label:h.name?h.name:h.apiKey.substring(0,15)+"...",value:h.id})))||[]}),u.jsx(Qt,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(l==null?void 0:l.filter(h=>!!h.id).map(h=>({label:h.description,value:h.id})))??[]}),u.jsx(G,{name:"expire",label:e("openai.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),u.jsx(ke,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:e("openai.form.splitMessages.label"),reverse:!0}),d.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:e("openai.form.timePerChar.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const Qee=e=>["openai","getModels",JSON.stringify(e)],Zee=async({instanceName:e,token:t})=>(await he.get(`/openai/getModels/${e}`,{headers:{apiKey:t}})).data,Yee=e=>{const{instanceName:t,token:n,...r}=e;return lt({staleTime:1e3*60*60*6,...r,queryKey:Qee({instanceName:t}),queryFn:()=>Zee({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Xee=e=>["openai","fetchSessions",JSON.stringify(e)],ete=async({instanceName:e,openaiId:t,token:n})=>(await he.get(`/openai/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,tte=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:Xee({instanceName:t}),queryFn:()=>ete({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function DI({openaiId:e}){const{t}=ze(),{instance:n}=nt(),{changeStatusOpenai:r}=rf(),[s,o]=v.useState([]),[a,l]=v.useState(!1),{data:c,refetch:i}=tte({instanceName:n==null?void 0:n.name,openaiId:e,enabled:a}),[d,p]=v.useState("");function f(){i()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("openai.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",size:"icon",children:[u.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:t("openai.sessions.table.actions.title")}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("openai.sessions.search"),value:d,onChange:m=>p(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Nu,{columns:g,data:c??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:p,enableGlobalFilter:!0,noResultsMessage:t("openai.sessions.table.none")})]})]})]})}const nte=_.object({enabled:_.boolean(),description:_.string(),openaiCredsId:_.string(),botType:_.string(),assistantId:_.string().optional(),functionUrl:_.string().optional(),model:_.string().optional(),systemMessages:_.string().optional(),assistantMessages:_.string().optional(),userMessages:_.string().optional(),maxTokens:_.coerce.number().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional(),splitMessages:_.boolean().optional(),timePerChar:_.coerce.number().optional()});function AI({initialData:e,onSubmit:t,handleDelete:n,openaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{},open:c}){const{t:i}=ze(),{instance:d}=nt(),{data:p}=Vw({instanceName:d==null?void 0:d.name,enabled:c}),{data:f}=Yee({instanceName:d==null?void 0:d.name,enabled:c}),h=sn({resolver:on(nte),defaultValues:e||{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:0,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),g=h.watch("botType"),m=h.watch("triggerType");return u.jsx(Tr,{...h,children:u.jsxs("form",{onSubmit:h.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:i("openai.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:i("openai.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsx(Qt,{name:"openaiCredsId",label:i("openai.form.openaiCredsId.label"),required:!0,options:(p==null?void 0:p.filter(x=>!!x.id).map(x=>({label:x.name?x.name:x.apiKey.substring(0,15)+"...",value:x.id})))??[]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.openaiSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"botType",label:i("openai.form.botType.label"),required:!0,options:[{label:i("openai.form.botType.assistant"),value:"assistant"},{label:i("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),g==="assistant"&&u.jsxs(u.Fragment,{children:[u.jsx(G,{name:"assistantId",label:i("openai.form.assistantId.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"functionUrl",label:i("openai.form.functionUrl.label"),required:!0,children:u.jsx(K,{})})]}),g==="chatCompletion"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"model",label:i("openai.form.model.label"),required:!0,options:(f==null?void 0:f.map(x=>({label:x.id,value:x.id})))??[]}),u.jsx(G,{name:"systemMessages",label:i("openai.form.systemMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"assistantMessages",label:i("openai.form.assistantMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"userMessages",label:i("openai.form.userMessages.label"),children:u.jsx(Ml,{})}),u.jsx(G,{name:"maxTokens",label:i("openai.form.maxTokens.label"),children:u.jsx(K,{type:"number"})})]}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:i("openai.form.triggerType.label"),required:!0,options:[{label:i("openai.form.triggerType.keyword"),value:"keyword"},{label:i("openai.form.triggerType.all"),value:"all"},{label:i("openai.form.triggerType.advanced"),value:"advanced"},{label:i("openai.form.triggerType.none"),value:"none"}]}),m==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:i("openai.form.triggerOperator.label"),required:!0,options:[{label:i("openai.form.triggerOperator.contains"),value:"contains"},{label:i("openai.form.triggerOperator.equals"),value:"equals"},{label:i("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:i("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:i("openai.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:i("openai.form.triggerValue.label"),required:!0,children:u.jsx(K,{})})]}),m==="advanced"&&u.jsx(G,{name:"triggerValue",label:i("openai.form.triggerConditions.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:i("openai.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:i("openai.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:i("openai.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:i("openai.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:i("openai.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:i("openai.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:i("openai.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:i("openai.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:i("openai.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(ke,{name:"splitMessages",label:i("openai.form.splitMessages.label"),reverse:!0}),h.watch("splitMessages")&&u.jsx(G,{name:"timePerChar",label:i("openai.form.timePerChar.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(DI,{openaiId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:i("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:i("modal.delete.title")}),u.jsx(Fi,{children:i("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:i("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:i("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:i(o?"openai.button.saving":"openai.button.update")})]})]})]})})}function rte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createOpenai:r}=rf(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,openaiCredsId:i.openaiCredsId,botType:i.botType,assistantId:i.assistantId||"",functionUrl:i.functionUrl||"",model:i.model||"",systemMessages:[i.systemMessages||""],assistantMessages:[i.assistantMessages||""],userMessages:[i.userMessages||""],maxTokens:i.maxTokens||0,triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0,splitMessages:i.splitMessages||!1,timePerChar:i.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("openai.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("openai.form.title")})}),u.jsx(AI,{onSubmit:c,isModal:!0,isLoading:s,open:a})]})]})}const ste=e=>["openai","getOpenai",JSON.stringify(e)],ote=async({instanceName:e,token:t,openaiId:n})=>{const r=await he.get(`/openai/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},ate=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return lt({...s,queryKey:ste({instanceName:t}),queryFn:()=>ote({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ite({openaiId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteOpenai:l,updateOpenai:c}=rf(),{data:i,isLoading:d}=ate({instanceName:r==null?void 0:r.name,openaiId:e}),p=v.useMemo(()=>({enabled:(i==null?void 0:i.enabled)??!0,description:(i==null?void 0:i.description)??"",openaiCredsId:(i==null?void 0:i.openaiCredsId)??"",botType:(i==null?void 0:i.botType)??"",assistantId:(i==null?void 0:i.assistantId)||"",functionUrl:(i==null?void 0:i.functionUrl)||"",model:(i==null?void 0:i.model)||"",systemMessages:Array.isArray(i==null?void 0:i.systemMessages)?i==null?void 0:i.systemMessages.join(", "):(i==null?void 0:i.systemMessages)||"",assistantMessages:Array.isArray(i==null?void 0:i.assistantMessages)?i==null?void 0:i.assistantMessages.join(", "):(i==null?void 0:i.assistantMessages)||"",userMessages:Array.isArray(i==null?void 0:i.userMessages)?i==null?void 0:i.userMessages.join(", "):(i==null?void 0:i.userMessages)||"",maxTokens:(i==null?void 0:i.maxTokens)||0,triggerType:(i==null?void 0:i.triggerType)||"",triggerOperator:(i==null?void 0:i.triggerOperator)||"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)||0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)||0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:i==null?void 0:i.listeningFromMe,stopBotFromMe:i==null?void 0:i.stopBotFromMe,keepOpen:i==null?void 0:i.keepOpen,debounceTime:(i==null?void 0:i.debounceTime)||0,splitMessages:(i==null?void 0:i.splitMessages)||!1,timePerChar:(i==null?void 0:i.timePerChar)||0}),[i==null?void 0:i.assistantId,i==null?void 0:i.assistantMessages,i==null?void 0:i.botType,i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.functionUrl,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.maxTokens,i==null?void 0:i.model,i==null?void 0:i.openaiCredsId,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.systemMessages,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.unknownMessage,i==null?void 0:i.userMessages,i==null?void 0:i.splitMessages,i==null?void 0:i.timePerChar]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,openaiCredsId:g.openaiCredsId,botType:g.botType,assistantId:g.assistantId||"",functionUrl:g.functionUrl||"",model:g.model||"",systemMessages:[g.systemMessages||""],assistantMessages:[g.assistantMessages||""],userMessages:[g.userMessages||""],maxTokens:g.maxTokens||0,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0,splitMessages:g.splitMessages||!1,timePerChar:g.timePerChar||0};await c({instanceName:r.name,openaiId:e,data:y}),X.success(n("openai.toast.success.update")),t(),s(`/manager/instance/${r.id}/openai/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,openaiId:e}),X.success(n("openai.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/openai`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx(AI,{initialData:p,onSubmit:f,openaiId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function oE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{botId:r}=So(),{data:s,isLoading:o,refetch:a}=II({instanceName:n==null?void 0:n.name}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/openai/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),u.jsxs("div",{className:"flex items-center justify-end gap-2",children:[u.jsx(DI,{}),u.jsx(Jee,{}),u.jsx(Hee,{}),u.jsx(rte,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsxs(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:[u.jsx("h4",{className:"text-base",children:d.description||d.id}),u.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:d.botType})]},d.id)):u.jsx(q,{variant:"link",children:e("openai.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-border"}),u.jsx(Ur,{children:u.jsx(ite,{openaiId:r,resetTable:i})})]})]})]})}const lte=e=>["proxy","fetchProxy",JSON.stringify(e)],ute=async({instanceName:e,token:t})=>(await he.get(`/proxy/find/${e}`,{headers:{apiKey:t}})).data,cte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lte({instanceName:t,token:n}),queryFn:()=>ute({instanceName:t,token:n}),enabled:!!t})},dte=async({instanceName:e,token:t,data:n})=>(await he.post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data;function fte(){return{createProxy:Ye(dte,{invalidateKeys:[["proxy","fetchProxy"]]})}}const pte=_.object({enabled:_.boolean(),host:_.string(),port:_.string(),protocol:_.string(),username:_.string(),password:_.string()});function hte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createProxy:s}=fte(),{data:o}=cte({instanceName:t==null?void 0:t.name}),a=sn({resolver:on(pte),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,host:o.host,port:o.port,protocol:o.protocol,username:o.username,password:o.password})},[o]);const l=async c=>{var i,d,p;if(t){r(!0);try{const f={enabled:c.enabled,host:c.host,port:c.port,protocol:c.protocol,username:c.username,password:c.password};await s({instanceName:t.name,token:t.token,data:f}),X.success(e("proxy.toast.success"))}catch(f){console.error(e("proxy.toast.error"),f),X.error(`Error : ${(p=(d=(i=f==null?void 0:f.response)==null?void 0:i.data)==null?void 0:d.response)==null?void 0:p.message}`)}finally{r(!1)}}};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[u.jsx(G,{name:"protocol",label:e("proxy.form.protocol.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"host",label:e("proxy.form.host.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"port",label:e("proxy.form.port.label"),children:u.jsx(K,{type:"number"})})]}),u.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[u.jsx(G,{name:"username",label:e("proxy.form.username.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"password",label:e("proxy.form.password.label"),children:u.jsx(K,{type:"password"})})]}),u.jsx("div",{className:"flex justify-end px-4 pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const gte=e=>["rabbitmq","fetchRabbitmq",JSON.stringify(e)],mte=async({instanceName:e,token:t})=>(await he.get(`/rabbitmq/find/${e}`,{headers:{apiKey:t}})).data,vte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:gte({instanceName:t,token:n}),queryFn:()=>mte({instanceName:t,token:n}),enabled:!!t})},yte=async({instanceName:e,token:t,data:n})=>(await he.post(`/rabbitmq/set/${e}`,{rabbitmq:n},{headers:{apikey:t}})).data;function bte(){return{createRabbitmq:Ye(yte,{invalidateKeys:[["rabbitmq","fetchRabbitmq"]]})}}const xte=_.object({enabled:_.boolean(),events:_.array(_.string())});function wte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createRabbitmq:s}=bte(),{data:o}=vte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(xte),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("rabbitmq.toast.success"))}catch(m){console.error(e("rabbitmq.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const Ste=e=>["instance","fetchSettings",JSON.stringify(e)],Cte=async({instanceName:e,token:t})=>(await he.get(`/settings/find/${e}`,{headers:{apikey:t}})).data,Ete=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ste({instanceName:t,token:n}),queryFn:()=>Cte({instanceName:t,token:n}),enabled:!!t})},Tte=_.object({rejectCall:_.boolean(),msgCall:_.string().optional(),groupsIgnore:_.boolean(),alwaysOnline:_.boolean(),readMessages:_.boolean(),syncFullHistory:_.boolean(),readStatus:_.boolean()});function kte(){const{t:e}=ze(),[t,n]=v.useState(!1),{instance:r}=nt(),{updateSettings:s}=_g(),{data:o,isLoading:a}=Ete({instanceName:r==null?void 0:r.name,token:r==null?void 0:r.token}),l=sn({resolver:on(Tte),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});v.useEffect(()=>{o&&l.reset({rejectCall:o.rejectCall,msgCall:o.msgCall||"",groupsIgnore:o.groupsIgnore,alwaysOnline:o.alwaysOnline,readMessages:o.readMessages,syncFullHistory:o.syncFullHistory,readStatus:o.readStatus})},[l,o]);const c=async p=>{try{if(!r||!r.name)throw new Error("instance not found");n(!0);const f={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await s({instanceName:r.name,token:r.token,data:f}),X.success(e("settings.toast.success"))}catch(f){console.error(e("settings.toast.success"),f),X.error(e("settings.toast.error"))}finally{n(!1)}},i=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],d=l.watch("rejectCall");return a?u.jsx(wr,{}):u.jsx(u.Fragment,{children:u.jsx(Na,{...l,children:u.jsx("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),u.jsx($t,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[u.jsxs("div",{className:"flex flex-col p-4",children:[u.jsx(ke,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),d&&u.jsx("div",{className:"mr-16 mt-2",children:u.jsx(G,{name:"msgCall",children:u.jsx(Ml,{placeholder:e("settings.form.msgCall.description")})})})]}),i.map(p=>u.jsx("div",{className:"flex p-4",children:u.jsx(ke,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),u.jsx("div",{className:"flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:t,children:e(t?"settings.button.saving":"settings.button.save")})})]})]})})})})}const _te=e=>["sqs","fetchSqs",JSON.stringify(e)],jte=async({instanceName:e,token:t})=>(await he.get(`/sqs/find/${e}`,{headers:{apiKey:t}})).data,Rte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:_te({instanceName:t,token:n}),queryFn:()=>jte({instanceName:t,token:n}),enabled:!!t})},Pte=async({instanceName:e,token:t,data:n})=>(await he.post(`/sqs/set/${e}`,{sqs:n},{headers:{apikey:t}})).data;function Mte(){return{createSqs:Ye(Pte,{invalidateKeys:[["sqs","fetchSqs"]]})}}const Ote=_.object({enabled:_.boolean(),events:_.array(_.string())});function Nte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createSqs:s}=Mte(),{data:o}=Rte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(Ote),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("sqs.toast.success"))}catch(m){console.error(e("sqs.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const Ite=e=>["typebot","findTypebot",JSON.stringify(e)],Dte=async({instanceName:e,token:t})=>(await he.get(`/typebot/find/${e}`,{headers:{apiKey:t}})).data,FI=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ite({instanceName:t}),queryFn:()=>Dte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ate=e=>["typebot","fetchDefaultSettings",JSON.stringify(e)],Fte=async({instanceName:e,token:t})=>{const n=await he.get(`/typebot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Lte=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:Ate({instanceName:t}),queryFn:()=>Fte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},$te=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,Bte=async({instanceName:e,token:t,typebotId:n,data:r})=>(await he.put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,zte=async({instanceName:e,typebotId:t})=>(await he.delete(`/typebot/delete/${t}/${e}`)).data,Ute=async({instanceName:e,token:t,data:n})=>(await he.post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,Vte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await he.post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function tm(){const e=Ye(Ute,{invalidateKeys:[["typebot","fetchDefaultSettings"]]}),t=Ye(Vte,{invalidateKeys:[["typebot","getTypebot"],["typebot","fetchSessions"]]}),n=Ye(zte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),r=Ye(Bte,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),s=Ye($te,{invalidateKeys:[["typebot","findTypebot"]]});return{setDefaultSettingsTypebot:e,changeStatusTypebot:t,deleteTypebot:n,updateTypebot:r,createTypebot:s}}const Hte=_.object({expire:_.coerce.number(),keywordFinish:_.string(),delayMessage:_.coerce.number(),unknownMessage:_.string(),listeningFromMe:_.boolean(),stopBotFromMe:_.boolean(),keepOpen:_.boolean(),debounceTime:_.coerce.number()});function Kte(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{setDefaultSettingsTypebot:s}=tm(),{data:o,refetch:a}=Lte({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),{data:l,refetch:c}=FI({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token,enabled:n}),i=sn({resolver:on(Hte),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});v.useEffect(()=>{o&&i.reset({expire:(o==null?void 0:o.expire)??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0})},[o]);const d=async f=>{var h,g,m;try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime};await s({instanceName:t.name,token:t.token,data:x}),X.success(e("typebot.toast.defaultSettings.success"))}catch(x){console.error(e("typebot.toast.defaultSettings.error"),x),X.error(`Error: ${(m=(g=(h=x==null?void 0:x.response)==null?void 0:h.data)==null?void 0:g.response)==null?void 0:m.message}`)}};function p(){a(),c()}return u.jsxs(Tt,{open:n,onOpenChange:r,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Oi,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[u.jsx(wt,{children:u.jsx(Ut,{children:e("typebot.modal.defaultSettings.title")})}),u.jsx(Tr,{...i,children:u.jsxs("form",{className:"w-full space-y-6",onSubmit:i.handleSubmit(d),children:[u.jsx("div",{children:u.jsxs("div",{className:"space-y-4",children:[u.jsx(Qt,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(l==null?void 0:l.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),u.jsx(G,{name:"expire",label:e("typebot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})}),u.jsx(Ru,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),u.jsx(rn,{children:u.jsx(q,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const qte=e=>["typebot","fetchSessions",JSON.stringify(e)],Wte=async({instanceName:e,typebotId:t,token:n})=>(await he.get(`/typebot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Gte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:qte({instanceName:t}),queryFn:()=>Wte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function LI({typebotId:e}){const{t}=ze(),{instance:n}=nt(),[r,s]=v.useState([]),[o,a]=v.useState(!1),[l,c]=v.useState(""),{changeStatusTypebot:i}=tm(),{data:d,refetch:p}=Gte({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token,typebotId:e});function f(){p()}const h=async(m,x)=>{var b,y,w;try{if(!n)return;await i({instanceName:n.name,token:n.token,remoteJid:m,status:x}),X.success(t("typebot.toast.success.status")),f()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(y=(b=S==null?void 0:S.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:w.message}`)}},g=[{accessorKey:"remoteJid",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("pushName")})},{accessorKey:"sessionId",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("sessionId")})},{accessorKey:"status",header:()=>u.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:m})=>u.jsx("div",{children:m.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:m})=>{const x=m.original;return u.jsxs(Eo,{children:[u.jsx(To,{asChild:!0,children:u.jsxs(q,{variant:"ghost",className:"h-8 w-8 p-0",children:[u.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),u.jsx(vu,{className:"h-4 w-4"})]})}),u.jsxs(ps,{align:"end",children:[u.jsx(Ai,{children:"Actions"}),u.jsx(Pa,{}),x.status!=="opened"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"opened"),children:[u.jsx(qd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),x.status!=="paused"&&x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"paused"),children:[u.jsx(Kd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),x.status!=="closed"&&u.jsxs(ft,{onClick:()=>h(x.remoteJid,"closed"),children:[u.jsx(Ud,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),u.jsxs(ft,{onClick:()=>h(x.remoteJid,"delete"),children:[u.jsx(Vd,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}];return u.jsxs(Tt,{open:o,onOpenChange:a,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{variant:"secondary",size:"sm",children:[u.jsx(Hd,{size:16,className:"mr-1"})," ",u.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:f,children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.sessions.label")})}),u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[u.jsx(K,{placeholder:t("typebot.sessions.search"),value:l,onChange:m=>c(m.target.value)}),u.jsx(q,{variant:"outline",onClick:f,size:"icon",children:u.jsx(Wd,{size:16})})]}),u.jsx(Nu,{columns:g,data:d??[],onSortingChange:s,state:{sorting:r,globalFilter:l},onGlobalFilterChange:c,enableGlobalFilter:!0,noResultsMessage:t("typebot.sessions.table.none")})]})]})]})}const Jte=_.object({enabled:_.boolean(),description:_.string(),url:_.string(),typebot:_.string().optional(),triggerType:_.string(),triggerOperator:_.string().optional(),triggerValue:_.string().optional(),expire:_.coerce.number().optional(),keywordFinish:_.string().optional(),delayMessage:_.coerce.number().optional(),unknownMessage:_.string().optional(),listeningFromMe:_.boolean().optional(),stopBotFromMe:_.boolean().optional(),keepOpen:_.boolean().optional(),debounceTime:_.coerce.number().optional()});function $I({initialData:e,onSubmit:t,handleDelete:n,typebotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:a=!1,setOpenDeletionDialog:l=()=>{}}){const{t:c}=ze(),i=sn({resolver:on(Jte),defaultValues:e||{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),d=i.watch("triggerType");return u.jsx(Tr,{...i,children:u.jsxs("form",{onSubmit:i.handleSubmit(t),className:"w-full space-y-6",children:[u.jsxs("div",{className:"space-y-4",children:[u.jsx(ke,{name:"enabled",label:c("typebot.form.enabled.label"),reverse:!0}),u.jsx(G,{name:"description",label:c("typebot.form.description.label"),required:!0,children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.typebotSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"url",label:c("typebot.form.url.label"),required:!0,children:u.jsx(K,{})}),u.jsx(G,{name:"typebot",label:c("typebot.form.typebot.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.triggerSettings.label")}),u.jsx($t,{})]}),u.jsx(Qt,{name:"triggerType",label:c("typebot.form.triggerType.label"),options:[{label:c("typebot.form.triggerType.keyword"),value:"keyword"},{label:c("typebot.form.triggerType.all"),value:"all"},{label:c("typebot.form.triggerType.advanced"),value:"advanced"},{label:c("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&u.jsxs(u.Fragment,{children:[u.jsx(Qt,{name:"triggerOperator",label:c("typebot.form.triggerOperator.label"),options:[{label:c("typebot.form.triggerOperator.contains"),value:"contains"},{label:c("typebot.form.triggerOperator.equals"),value:"equals"},{label:c("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:c("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:c("typebot.form.triggerOperator.regex"),value:"regex"}]}),u.jsx(G,{name:"triggerValue",label:c("typebot.form.triggerValue.label"),children:u.jsx(K,{})})]}),d==="advanced"&&u.jsx(G,{name:"triggerValue",label:c("typebot.form.triggerConditions.label"),children:u.jsx(K,{})}),u.jsxs("div",{className:"flex flex-col",children:[u.jsx("h3",{className:"my-4 text-lg font-medium",children:c("typebot.form.generalSettings.label")}),u.jsx($t,{})]}),u.jsx(G,{name:"expire",label:c("typebot.form.expire.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"keywordFinish",label:c("typebot.form.keywordFinish.label"),children:u.jsx(K,{})}),u.jsx(G,{name:"delayMessage",label:c("typebot.form.delayMessage.label"),children:u.jsx(K,{type:"number"})}),u.jsx(G,{name:"unknownMessage",label:c("typebot.form.unknownMessage.label"),children:u.jsx(K,{})}),u.jsx(ke,{name:"listeningFromMe",label:c("typebot.form.listeningFromMe.label"),reverse:!0}),u.jsx(ke,{name:"stopBotFromMe",label:c("typebot.form.stopBotFromMe.label"),reverse:!0}),u.jsx(ke,{name:"keepOpen",label:c("typebot.form.keepOpen.label"),reverse:!0}),u.jsx(G,{name:"debounceTime",label:c("typebot.form.debounceTime.label"),children:u.jsx(K,{type:"number"})})]}),s&&u.jsx(rn,{children:u.jsx(q,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.save")})}),!s&&u.jsxs("div",{children:[u.jsx(LI,{typebotId:r}),u.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsx(q,{variant:"destructive",size:"sm",children:c("dify.button.delete")})}),u.jsx(xt,{children:u.jsxs(wt,{children:[u.jsx(Ut,{children:c("modal.delete.title")}),u.jsx(Fi,{children:c("modal.delete.messageSingle")}),u.jsxs(rn,{children:[u.jsx(q,{size:"sm",variant:"outline",onClick:()=>l(!1),children:c("button.cancel")}),u.jsx(q,{variant:"destructive",onClick:n,children:c("button.delete")})]})]})})]}),u.jsx(q,{disabled:o,type:"submit",children:c(o?"typebot.button.saving":"typebot.button.update")})]})]})]})})}function Qte({resetTable:e}){const{t}=ze(),{instance:n}=nt(),{createTypebot:r}=tm(),[s,o]=v.useState(!1),[a,l]=v.useState(!1),c=async i=>{var d,p,f;try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:i.enabled,description:i.description,url:i.url,typebot:i.typebot||"",triggerType:i.triggerType,triggerOperator:i.triggerOperator||"",triggerValue:i.triggerValue||"",expire:i.expire||0,keywordFinish:i.keywordFinish||"",delayMessage:i.delayMessage||0,unknownMessage:i.unknownMessage||"",listeningFromMe:i.listeningFromMe||!1,stopBotFromMe:i.stopBotFromMe||!1,keepOpen:i.keepOpen||!1,debounceTime:i.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),X.success(t("typebot.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),X.error(`Error: ${(f=(p=(d=h==null?void 0:h.response)==null?void 0:d.data)==null?void 0:p.response)==null?void 0:f.message}`)}finally{o(!1)}};return u.jsxs(Tt,{open:a,onOpenChange:l,children:[u.jsx(Nt,{asChild:!0,children:u.jsxs(q,{size:"sm",children:[u.jsx(Ni,{size:16,className:"mr-1"}),u.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),u.jsxs(xt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[u.jsx(wt,{children:u.jsx(Ut,{children:t("typebot.form.title")})}),u.jsx($I,{onSubmit:c,isModal:!0,isLoading:s})]})]})}const Zte=e=>["typebot","getTypebot",JSON.stringify(e)],Yte=async({instanceName:e,token:t,typebotId:n})=>{const r=await he.get(`/typebot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Xte=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return lt({...s,queryKey:Zte({instanceName:t}),queryFn:()=>Yte({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function ene({typebotId:e,resetTable:t}){const{t:n}=ze(),{instance:r}=nt(),s=An(),[o,a]=v.useState(!1),{deleteTypebot:l,updateTypebot:c}=tm(),{data:i,isLoading:d}=Xte({instanceName:r==null?void 0:r.name,typebotId:e}),p=v.useMemo(()=>({enabled:!!(i!=null&&i.enabled),description:(i==null?void 0:i.description)??"",url:(i==null?void 0:i.url)??"",typebot:(i==null?void 0:i.typebot)??"",triggerType:(i==null?void 0:i.triggerType)??"",triggerOperator:(i==null?void 0:i.triggerOperator)??"",triggerValue:i==null?void 0:i.triggerValue,expire:(i==null?void 0:i.expire)??0,keywordFinish:i==null?void 0:i.keywordFinish,delayMessage:(i==null?void 0:i.delayMessage)??0,unknownMessage:i==null?void 0:i.unknownMessage,listeningFromMe:!!(i!=null&&i.listeningFromMe),stopBotFromMe:!!(i!=null&&i.stopBotFromMe),keepOpen:!!(i!=null&&i.keepOpen),debounceTime:(i==null?void 0:i.debounceTime)??0}),[i==null?void 0:i.debounceTime,i==null?void 0:i.delayMessage,i==null?void 0:i.description,i==null?void 0:i.enabled,i==null?void 0:i.expire,i==null?void 0:i.keepOpen,i==null?void 0:i.keywordFinish,i==null?void 0:i.listeningFromMe,i==null?void 0:i.stopBotFromMe,i==null?void 0:i.triggerOperator,i==null?void 0:i.triggerType,i==null?void 0:i.triggerValue,i==null?void 0:i.typebot,i==null?void 0:i.unknownMessage,i==null?void 0:i.url]),f=async g=>{var m,x,b;try{if(r&&r.name&&e){const y={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot||"",triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire||0,keywordFinish:g.keywordFinish||"",delayMessage:g.delayMessage||1e3,unknownMessage:g.unknownMessage||"",listeningFromMe:g.listeningFromMe||!1,stopBotFromMe:g.stopBotFromMe||!1,keepOpen:g.keepOpen||!1,debounceTime:g.debounceTime||0};await c({instanceName:r.name,typebotId:e,data:y}),X.success(n("typebot.toast.success.update")),t(),s(`/manager/instance/${r.id}/typebot/${e}`)}else console.error("Token not found")}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(x=(m=y==null?void 0:y.response)==null?void 0:m.data)==null?void 0:x.response)==null?void 0:b.message}`)}},h=async()=>{try{r&&r.name&&e?(await l({instanceName:r.name,typebotId:e}),X.success(n("typebot.toast.success.delete")),a(!1),t(),s(`/manager/instance/${r.id}/typebot`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}};return d?u.jsx(wr,{}):u.jsx("div",{className:"m-4",children:u.jsx($I,{initialData:p,onSubmit:f,typebotId:e,handleDelete:h,isModal:!1,isLoading:d,openDeletionDialog:o,setOpenDeletionDialog:a})})}function aE(){const{t:e}=ze(),t=Ou("(min-width: 768px)"),{instance:n}=nt(),{typebotId:r}=So(),{data:s,isLoading:o,refetch:a}=FI({instanceName:n==null?void 0:n.name,token:n==null?void 0:n.token}),l=An(),c=d=>{n&&l(`/manager/instance/${n.id}/typebot/${d}`)},i=()=>{a()};return u.jsxs("main",{className:"pt-5",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[u.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),u.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[u.jsx(LI,{}),u.jsx(Kte,{}),u.jsx(Qte,{resetTable:i})]})]}),u.jsx($t,{className:"my-4"}),u.jsxs(Pu,{direction:t?"horizontal":"vertical",children:[u.jsx(Ur,{defaultSize:35,className:"pr-4",children:u.jsx("div",{className:"flex flex-col gap-3",children:o?u.jsx(wr,{}):u.jsx(u.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(d=>u.jsx(q,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>c(`${d.id}`),variant:r===d.id?"secondary":"outline",children:d.description?u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.description}),u.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[d.url," - ",d.typebot]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h4",{className:"text-base",children:d.url}),u.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:d.typebot})]})},d.id)):u.jsx(q,{variant:"link",children:e("typebot.table.none")})})})}),r&&u.jsxs(u.Fragment,{children:[u.jsx(Mu,{withHandle:!0,className:"border border-black"}),u.jsx(Ur,{children:u.jsx(ene,{typebotId:r,resetTable:i})})]})]})]})}const tne=e=>["webhook","fetchWebhook",JSON.stringify(e)],nne=async({instanceName:e,token:t})=>(await he.get(`/webhook/find/${e}`,{headers:{apiKey:t}})).data,rne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:tne({instanceName:t,token:n}),queryFn:()=>nne({instanceName:t,token:n}),enabled:!!t})},sne=async({instanceName:e,token:t,data:n})=>(await he.post(`/webhook/set/${e}`,{webhook:n},{headers:{apikey:t}})).data;function one(){return{createWebhook:Ye(sne,{invalidateKeys:[["webhook","fetchWebhook"]]})}}const ane=_.object({enabled:_.boolean(),url:_.string().url("Invalid URL format"),events:_.array(_.string()),base64:_.boolean(),byEvents:_.boolean()});function ine(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebhook:s}=one(),{data:o}=rne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(ane),defaultValues:{enabled:!1,url:"",events:[],base64:!1,byEvents:!1}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,url:o.url,events:o.events,base64:o.webhookBase64,byEvents:o.webhookByEvents})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,url:p.url,events:p.events,base64:p.base64,byEvents:p.byEvents};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("webhook.toast.success"))}catch(m){console.error(e("webhook.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),u.jsx(G,{name:"url",label:"URL",children:u.jsx(K,{})}),u.jsx(ke,{name:"byEvents",label:e("webhook.form.byEvents.label"),className:"w-full justify-between",helper:e("webhook.form.byEvents.description")}),u.jsx(ke,{name:"base64",label:e("webhook.form.base64.label"),className:"w-full justify-between",helper:e("webhook.form.base64.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const lne=e=>["websocket","fetchWebsocket",JSON.stringify(e)],une=async({instanceName:e,token:t})=>(await he.get(`/websocket/find/${e}`,{headers:{apiKey:t}})).data,cne=e=>{const{instanceName:t,token:n,...r}=e;return lt({...r,queryKey:lne({instanceName:t,token:n}),queryFn:()=>une({instanceName:t,token:n}),enabled:!!t})},dne=async({instanceName:e,token:t,data:n})=>(await he.post(`/websocket/set/${e}`,{websocket:n},{headers:{apikey:t}})).data;function fne(){return{createWebsocket:Ye(dne,{invalidateKeys:[["websocket","fetchWebsocket"]]})}}const pne=_.object({enabled:_.boolean(),events:_.array(_.string())});function hne(){const{t:e}=ze(),{instance:t}=nt(),[n,r]=v.useState(!1),{createWebsocket:s}=fne(),{data:o}=cne({instanceName:t==null?void 0:t.name,token:t==null?void 0:t.token}),a=sn({resolver:on(pne),defaultValues:{enabled:!1,events:[]}});v.useEffect(()=>{o&&a.reset({enabled:o.enabled,events:o.events})},[o]);const l=async p=>{var f,h,g;if(t){r(!0);try{const m={enabled:p.enabled,events:p.events};await s({instanceName:t.name,token:t.token,data:m}),X.success(e("websocket.toast.success"))}catch(m){console.error(e("websocket.toast.error"),m),X.error(`Error: ${(g=(h=(f=m==null?void 0:m.response)==null?void 0:f.data)==null?void 0:h.response)==null?void 0:g.message}`)}finally{r(!1)}}},c=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],i=()=>{a.setValue("events",c)},d=()=>{a.setValue("events",[])};return u.jsx(u.Fragment,{children:u.jsx(Na,{...a,children:u.jsx("form",{onSubmit:a.handleSubmit(l),className:"w-full space-y-6",children:u.jsxs("div",{children:[u.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),u.jsx(Ra,{className:"my-4"}),u.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[u.jsx(ke,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),u.jsxs("div",{className:"mb-4 flex justify-between",children:[u.jsx(q,{variant:"outline",type:"button",onClick:i,children:e("button.markAll")}),u.jsx(q,{variant:"outline",type:"button",onClick:d,children:e("button.unMarkAll")})]}),u.jsx(Ia,{control:a.control,name:"events",render:({field:p})=>u.jsxs(_o,{className:"flex flex-col",children:[u.jsx(xr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),u.jsx(Vs,{children:u.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:c.sort((f,h)=>f.localeCompare(h)).map(f=>u.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[u.jsx(xr,{className:ge("break-all",p.value.includes(f)?"text-foreground":"text-muted-foreground"),children:f}),u.jsx(ju,{checked:p.value.includes(f),onCheckedChange:h=>{h?p.onChange([...p.value,f]):p.onChange(p.value.filter(g=>g!==f))}})]},f))})})]})})]}),u.jsx("div",{className:"mx-4 flex justify-end pt-6",children:u.jsx(q,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const gne=async({url:e,token:t})=>{try{const{data:n}=await zt.post(`${e}/verify-creds`,{},{headers:{apikey:t}});return P_({facebookAppId:n.facebookAppId,facebookConfigId:n.facebookConfigId,facebookUserToken:n.facebookUserToken}),n}catch{return null}},mne=_.object({serverUrl:_.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:_.string({required_error:"ApiKey is required"})});function vne(){const{t:e}=ze(),t=An(),n=sn({resolver:on(mne),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await nj({url:s.serverUrl});if(!o||!o.version){M_(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await gne({token:s.apiKey,url:s.serverUrl})){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}P_({version:o.version,clientName:o.clientName,url:s.serverUrl,token:s.apiKey}),t("/manager/")};return u.jsxs("div",{className:"flex min-h-screen flex-col",children:[u.jsx("div",{className:"flex items-center justify-center pt-2",children:u.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),u.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:u.jsxs(Ja,{className:"b-none w-[350px] shadow-none",children:[u.jsxs(Qa,{children:[u.jsx(jc,{className:"text-center",children:e("login.title")}),u.jsx(JP,{className:"text-center",children:e("login.description")})]}),u.jsx(Na,{...n,children:u.jsxs("form",{onSubmit:n.handleSubmit(r),children:[u.jsx(Za,{children:u.jsxs("div",{className:"grid w-full items-center gap-4",children:[u.jsx(G,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:u.jsx(K,{})}),u.jsx(G,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:u.jsx(K,{type:"password"})})]})}),u.jsx(kg,{className:"flex justify-center",children:u.jsx(q,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),u.jsx(Ax,{})]})}const yne=OL([{path:"/manager/login",element:u.jsx(l$,{children:u.jsx(vne,{})})},{path:"/manager/",element:u.jsx(Gt,{children:u.jsx(SV,{children:u.jsx(GQ,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(SY,{})})})},{path:"/manager/instance/:instanceId/chat",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Q1,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Q1,{})})})},{path:"/manager/instance/:instanceId/settings",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(kte,{})})})},{path:"/manager/instance/:instanceId/openai",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(oE,{})})})},{path:"/manager/instance/:instanceId/webhook",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(ine,{})})})},{path:"/manager/instance/:instanceId/websocket",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hne,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(wte,{})})})},{path:"/manager/instance/:instanceId/sqs",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(Nte,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(HZ,{})})})},{path:"/manager/instance/:instanceId/typebot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(aE,{})})})},{path:"/manager/instance/:instanceId/dify",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(nE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/evolutionBot/:evolutionBotId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(rE,{})})})},{path:"/manager/instance/:instanceId/flowise",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(sE,{})})})},{path:"/manager/instance/:instanceId/proxy",element:u.jsx(Gt,{children:u.jsx(Xt,{children:u.jsx(hte,{})})})}]),bne={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class jh{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||bne,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[l,c]=a;for(let i=0;i{let[l,c]=a;for(let i=0;i{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},iE=e=>e==null?"":""+e,xne=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},wne=/###/g,lE=e=>e&&e.indexOf("###")>-1?e.replace(wne,"."):e,uE=e=>!e||typeof e=="string",Ic=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=Ic(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),l=Ic(e,a,Object);for(;l.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),l=Ic(e,a,Object),l&&l.obj&&typeof l.obj[`${l.k}.${o}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${o}`]=n},Sne=(e,t,n,r)=>{const{obj:s,k:o}=Ic(e,t,Object);s[o]=s[o]||[],s[o].push(n)},Rh=(e,t)=>{const{obj:n,k:r}=Ic(e,t);if(n)return n[r]},Cne=(e,t,n)=>{const r=Rh(e,n);return r!==void 0?r:Rh(t,n)},BI=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):BI(e[r],t[r],n):e[r]=t[r]);return e},Xi=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ene={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const Tne=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>Ene[t]):e;class kne{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const _ne=[" ",",","?","!",";"],jne=new kne(20),Rne=(e,t,n)=>{t=t||"",n=n||"";const r=_ne.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=jne.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},_b=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ce&&e.indexOf("_")>0?e.replace("_","-"):e;class dE extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;t.indexOf(".")>-1?l=t.split("."):(l=[t,n],r&&(Array.isArray(r)?l.push(...r):typeof r=="string"&&o?l.push(...r.split(o)):l.push(r)));const c=Rh(this.data,l);return!c&&!n&&!r&&t.indexOf(".")>-1&&(t=l[0],n=l[1],r=l.slice(2).join(".")),c||!a||typeof r!="string"?c:_b(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let l=[t,n];r&&(l=l.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(l=t.split("."),s=n,n=l[1]),this.addNamespaces(n),cE(this.data,l,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},l=[t,n];t.indexOf(".")>-1&&(l=t.split("."),s=r,r=n,n=l[1]),this.addNamespaces(n);let c=Rh(this.data,l)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?BI(c,r,o):c={...c,...r},cE(this.data,l,c),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var zI={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const fE={};class Mh extends nm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),xne(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Is.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Rne(t,r,s);if(a&&!l){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:o};const i=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(i[0])>-1)&&(o=i.shift()),t=i.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(t[t.length-1],n),c=l[l.length-1],i=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(i&&i.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${c}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:`${c}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:i,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:a}const p=this.resolve(t,n);let f=p&&p.res;const h=p&&p.usedKey||a,g=p&&p.exactUsedKey||a,m=Object.prototype.toString.apply(f),x=["[object Number]","[object Function]","[object RegExp]"],b=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&f&&(typeof f!="string"&&typeof f!="boolean"&&typeof f!="number")&&x.indexOf(m)<0&&!(typeof b=="string"&&Array.isArray(f))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,f,{...n,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(p.res=S,p.usedParams=this.getUsedParamsDetails(n),p):S}if(o){const S=Array.isArray(f),E=S?[]:{},C=S?g:h;for(const k in f)if(Object.prototype.hasOwnProperty.call(f,k)){const T=`${C}${o}${k}`;E[k]=this.translate(T,{...n,joinArrays:!1,ns:l}),E[k]===T&&(E[k]=f[k])}f=E}}else if(y&&typeof b=="string"&&Array.isArray(f))f=f.join(b),f&&(f=this.extendTranslation(f,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",k=Mh.hasDefaultValue(n),T=C?this.pluralResolver.getSuffix(i,n.count,n):"",P=n.ordinal&&C?this.pluralResolver.getSuffix(i,n.count,{ordinal:!1}):"",N=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),U=N&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${T}`]||n[`defaultValue${P}`]||n.defaultValue;!this.isValidLookup(f)&&k&&(S=!0,f=U),this.isValidLookup(f)||(E=!0,f=a);const Z=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:f,V=k&&U!==f&&this.options.updateMissing;if(E||S||V){if(this.logger.log(V?"updateKey":"missingKey",i,c,a,V?U:f),o){const F=this.resolve(a,{...n,keySeparator:!1});F&&F.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Q=[];const ee=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ee&&ee[0])for(let F=0;F{const de=k&&Y!==f?Y:Z;this.options.missingKeyHandler?this.options.missingKeyHandler(F,c,A,de,V,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(F,c,A,de,V,n),this.emit("missingKey",F,c,A,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?Q.forEach(F=>{const A=this.pluralResolver.getSuffixes(F,n);N&&n[`defaultValue${this.options.pluralSeparator}zero`]&&A.indexOf(`${this.options.pluralSeparator}zero`)<0&&A.push(`${this.options.pluralSeparator}zero`),A.forEach(Y=>{W([F],a+Y,n[`defaultValue${Y}`]||U)})}):W(Q,a,U))}f=this.extendTranslation(f,t,n,p,r),E&&f===a&&this.options.appendNamespaceToMissingKey&&(f=`${c}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}:${a}`:a,S?f:void 0):f=this.options.parseMissingKeyHandler(f))}return s?(p.res=f,p.usedParams=this.getUsedParamsDetails(n),p):f}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const i=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(i){const f=t.match(this.interpolator.nestingRegexp);d=f&&f.length}let p=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(p={...this.options.interpolation.defaultVariables,...p}),t=this.interpolator.interpolate(t,p,r.lng||this.language||s.usedLng,r),i){const f=t.match(this.interpolator.nestingRegexp),h=f&&f.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,l;return typeof t=="string"&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(r))return;const i=this.extractFromKey(c,n),d=i.key;s=d;let p=i.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const f=n.count!==void 0&&typeof n.count!="string",h=f&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),g=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);p.forEach(x=>{this.isValidLookup(r)||(l=x,!fE[`${m[0]}-${x}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(l)&&(fE[`${m[0]}-${x}`]=!0,this.logger.warn(`key "${s}" for languages "${m.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(b=>{if(this.isValidLookup(r))return;a=b;const y=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,d,b,x,n);else{let S;f&&(S=this.pluralResolver.getSuffix(b,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(y.push(d+S),n.ordinal&&S.indexOf(C)===0&&y.push(d+S.replace(C,this.options.pluralSeparator)),h&&y.push(d+E)),g){const k=`${d}${this.options.contextSeparator}${n.context}`;y.push(k),f&&(y.push(k+S),n.ordinal&&S.indexOf(C)===0&&y.push(k+S.replace(C,this.options.pluralSeparator)),h&&y.push(k+E))}}let w;for(;w=y.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(b,x,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:l}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const Cv=e=>e.charAt(0).toUpperCase()+e.slice(1);class pE{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Is.create("languageUtils")}getScriptPartFromCode(t){if(t=Ph(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ph(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=Cv(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=Cv(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let Pne=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Mne={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const One=["v1","v2","v3"],Nne=["v4"],hE={zero:0,one:1,two:2,few:3,many:4,other:5},Ine=()=>{const e={};return Pne.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:Mne[t.fc]}})}),e};class Dne{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=Is.create("pluralResolver"),(!this.options.compatibilityJSON||Nne.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=Ine(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Ph(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>hE[s]-hE[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!One.includes(this.options.compatibilityJSON)}}const gE=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=Cne(e,t,n);return!o&&s&&typeof n=="string"&&(o=_b(e,n,r),o===void 0&&(o=_b(t,n,r))),o},Ev=e=>e.replace(/\$/g,"$$$$");class Ane{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:l,suffixEscaped:c,formatSeparator:i,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:f,nestingPrefixEscaped:h,nestingSuffix:g,nestingSuffixEscaped:m,nestingOptionsSeparator:x,maxReplaces:b,alwaysFormat:y}=t.interpolation;this.escape=n!==void 0?n:Tne,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?Xi(o):a||"{{",this.suffix=l?Xi(l):c||"}}",this.formatSeparator=i||",",this.unescapePrefix=d?"":p||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?Xi(f):h||Xi("$t("),this.nestingSuffix=g?Xi(g):m||Xi(")"),this.nestingOptionsSeparator=x||",",this.maxReplaces=b||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},i=h=>{if(h.indexOf(this.formatSeparator)<0){const b=gE(n,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(b,void 0,r,{...s,...n,interpolationkey:h}):b}const g=h.split(this.formatSeparator),m=g.shift().trim(),x=g.join(this.formatSeparator).trim();return this.format(gE(n,c,m,this.options.keySeparator,this.options.ignoreJSONStructure),x,r,{...s,...n,interpolationkey:m})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,p=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>Ev(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?Ev(this.escape(h)):Ev(h)}].forEach(h=>{for(l=0;o=h.regex.exec(t);){const g=o[1].trim();if(a=i(g),a===void 0)if(typeof d=="function"){const x=d(t,o,s);a=typeof x=="string"?x:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))a="";else if(p){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=iE(a));const m=h.safeValue(a);if(t=t.replace(o[0],m),p?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=o[0].length):h.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const l=(c,i)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const p=c.split(new RegExp(`${d}[ ]*{`));let f=`{${p[1]}`;c=p[0],f=this.interpolate(f,a);const h=f.match(/'/g),g=f.match(/"/g);(h&&h.length%2===0&&!g||g.length%2!==0)&&(f=f.replace(/'/g,'"'));try{a=JSON.parse(f),i&&(a={...i,...a})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,m),`${c}${d}${f}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,c};for(;s=this.nestingRegexp.exec(t);){let c=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let i=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(p=>p.trim());s[1]=d.shift(),c=d,i=!0}if(o=n(l.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=iE(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),i&&(o=c.reduce((d,p)=>this.format(d,p,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const Fne=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[l,...c]=a.split(":"),i=c.join(":").trim().replace(/^'+|'+$/g,""),d=l.trim();n[d]||(n[d]=i),i==="false"&&(n[d]=!1),i==="true"&&(n[d]=!0),isNaN(i)||(n[d]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},el=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let l=t[a];return l||(l=e(Ph(r),s),t[a]=l),l(n)}};class Lne{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Is.create("formatter"),this.options=t,this.formats={number:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:el((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:el((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:el((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:el((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=el(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(l=>l.indexOf(")")>-1)){const l=o.findIndex(c=>c.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,l)].join(this.formatSeparator)}return o.reduce((l,c)=>{const{formatName:i,formatOptions:d}=Fne(c);if(this.formats[i]){let p=l;try{const f=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},h=f.locale||f.lng||s.locale||s.lng||r;p=this.formats[i](l,h,{...d,...s,...f})}catch(f){this.logger.warn(f)}return p}else this.logger.warn(`there was no format function for ${i}`);return l},t)}}const $ne=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Bne extends nm{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=Is.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},l={},c={};return t.forEach(i=>{let d=!0;n.forEach(p=>{const f=`${i}|${p}`;!r.reload&&this.store.hasResourceBundle(i,p)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?a[f]===void 0&&(a[f]=!0):(this.state[f]=1,d=!1,a[f]===void 0&&(a[f]=!0),o[f]===void 0&&(o[f]=!0),c[p]===void 0&&(c[p]=!0)))}),d||(l[i]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const l={};this.queue.forEach(c=>{Sne(c.loaded,[o],a),$ne(c,t),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(i=>{l[i]||(l[i]={});const d=c.loaded[i];d.length&&d.forEach(p=>{l[i][p]===void 0&&(l[i][p]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const l=(i,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(i&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(i,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const i=c(t,n);i&&typeof i.then=="function"?i.then(d=>l(null,d)).catch(l):l(null,i)}catch(i){l(i)}return}return c(t,n,l)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,l)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&l&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,l),this.loaded(t,a,l)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const c={...a,isUpdate:o},i=this.backend.create.bind(this.backend);if(i.length<6)try{let d;i.length===5?d=i(t,n,r,s,c):d=i(t,n,r,s),d&&typeof d.then=="function"?d.then(p=>l(null,p)).catch(l):l(null,d)}catch(d){l(d)}else i(t,n,r,s,l,c)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const mE=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),vE=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),Qf=()=>{},zne=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Pd extends nm{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=vE(t),this.services={},this.logger=Is,this.modules={external:[]},zne(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=mE();this.options={...s,...this.options,...vE(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Is.init(o(this.modules.logger),this.options):Is.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=Lne);const p=new pE(this.options);this.store=new dE(this.options.resources,this.options);const f=this.services;f.logger=Is,f.resourceStore=this.store,f.languageUtils=p,f.pluralResolver=new Dne(p,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(f.formatter=o(d),f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new Ane(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Bne(o(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",function(h){for(var g=arguments.length,m=new Array(g>1?g-1:0),x=1;x1?g-1:0),x=1;x{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Qf),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const c=sc(),i=()=>{const d=(p,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),r(p,f)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?i():setTimeout(i,0),c}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(i=>{i!=="cimode"&&o.indexOf(i)<0&&o.push(i)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>a(c)),this.options.preload&&this.options.preload.forEach(l=>a(l)),this.services.backendConnector.load(o,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(t,n,r){const s=sc();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=Qf),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&zI.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=sc();this.emit("languageChanging",t);const o=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},a=(c,i)=>{i?(o(i),this.translator.changeLanguage(i),this.isLanguageChangingTo=void 0,this.emit("languageChanged",i),this.logger.log("languageChanged",i)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(c,function(){return r.t(...arguments)})},l=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const i=typeof c=="string"?c:this.services.languageUtils.getBestMatchFromCodes(c);i&&(this.language||o(i),this.translator.language||this.translator.changeLanguage(i),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(i)),this.loadResources(i,d=>{a(d,i)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?l(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(l):this.services.languageDetector.detect(l):l(t),s}getFixedT(t,n,r){var s=this;const o=function(a,l){let c;if(typeof l!="object"){for(var i=arguments.length,d=new Array(i>2?i-2:0),p=2;p`${c.keyPrefix}${f}${g}`):h=c.keyPrefix?`${c.keyPrefix}${f}${a}`:a,s.t(h,c)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(l,c)=>{const i=this.services.backendConnector.state[`${l}|${c}`];return i===-1||i===0||i===2};if(n.precheck){const l=n.precheck(this,a);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=sc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=sc();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new pE(mE());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Pd(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qf;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Pd(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(l=>{o[l]=this[l]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new dE(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Mh(o.services,s),o.translator.on("*",function(l){for(var c=arguments.length,i=new Array(c>1?c-1:0),d=1;d()=>(t||e((t={exports:{}}).exports,t),t.exports);var tie=TD((ko,jo)=>{function Bk(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function fd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var av={exports:{}},Xc={},iv={exports:{}},Et={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var A0;function ND(){if(A0)return Et;A0=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),m=Symbol.iterator;function g(A){return A===null||typeof A!="object"?null:(A=m&&A[m]||A["@@iterator"],typeof A=="function"?A:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b=Object.assign,w={};function C(A,F,fe){this.props=A,this.context=F,this.refs=w,this.updater=fe||x}C.prototype.isReactComponent={},C.prototype.setState=function(A,F){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,F,"setState")},C.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function k(){}k.prototype=C.prototype;function j(A,F,fe){this.props=A,this.context=F,this.refs=w,this.updater=fe||x}var M=j.prototype=new k;M.constructor=j,b(M,C.prototype),M.isPureReactComponent=!0;var _=Array.isArray,R=Object.prototype.hasOwnProperty,N={current:null},O={key:!0,ref:!0,__self:!0,__source:!0};function D(A,F,fe){var te,de={},ge=null,Z=null;if(F!=null)for(te in F.ref!==void 0&&(Z=F.ref),F.key!==void 0&&(ge=""+F.key),F)R.call(F,te)&&!O.hasOwnProperty(te)&&(de[te]=F[te]);var ye=arguments.length-2;if(ye===1)de.children=fe;else if(1{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Fl=typeof window>"u"||"Deno"in globalThis;function ss(){}function RD(e,t){return typeof e=="function"?e(t):e}function Sy(e){return typeof e=="number"&&e>=0&&e!==1/0}function zk(e,t){return Math.max(e+(t||0)-Date.now(),0)}function _l(e,t){return typeof e=="function"?e(t):e}function ws(e,t){return typeof e=="function"?e(t):e}function $0(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:o,queryKey:l,stale:u}=e;if(l){if(r){if(t.queryHash!==_b(l,t.options))return!1}else if(!Ou(t.queryKey,l))return!1}if(n!=="all"){const d=t.isActive();if(n==="active"&&!d||n==="inactive"&&d)return!1}return!(typeof u=="boolean"&&t.isStale()!==u||s&&s!==t.state.fetchStatus||o&&!o(t))}function B0(e,t){const{exact:n,status:r,predicate:s,mutationKey:o}=e;if(o){if(!t.options.mutationKey)return!1;if(n){if(xi(t.options.mutationKey)!==xi(o))return!1}else if(!Ou(t.options.mutationKey,o))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function _b(e,t){return(t?.queryKeyHashFn||xi)(e)}function xi(e){return JSON.stringify(e,(t,n)=>Cy(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Ou(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Ou(e[n],t[n])):!1}function Uk(e,t){if(e===t)return e;const n=z0(e)&&z0(t);if(n||Cy(e)&&Cy(t)){const r=n?e:Object.keys(e),s=r.length,o=n?t:Object.keys(t),l=o.length,u=n?[]:{};let d=0;for(let f=0;f{setTimeout(t,e)})}function Ey(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Uk(e,t):t}function OD(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function ID(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Vk=Symbol();function Hk(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Vk?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var AD=class extends Zl{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!Fl&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},Rb=new AD,DD=class extends Zl{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!Fl&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},_p=new DD;function FD(e){return Math.min(1e3*2**e,3e4)}function qk(e){return(e??"online")==="online"?_p.isOnline():!0}var Kk=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function lv(e){return e instanceof Kk}function Wk(e){let t=!1,n=0,r=!1,s,o,l;const u=new Promise((k,j)=>{o=k,l=j}),d=k=>{r||(b(new Kk(k)),e.abort?.())},f=()=>{t=!0},h=()=>{t=!1},m=()=>Rb.isFocused()&&(e.networkMode==="always"||_p.isOnline())&&e.canRun(),g=()=>qk(e.networkMode)&&e.canRun(),x=k=>{r||(r=!0,e.onSuccess?.(k),s?.(),o(k))},b=k=>{r||(r=!0,e.onError?.(k),s?.(),l(k))},w=()=>new Promise(k=>{s=j=>{(r||m())&&k(j)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),C=()=>{if(r)return;let k;const j=n===0?e.initialPromise:void 0;try{k=j??e.fn()}catch(M){k=Promise.reject(M)}Promise.resolve(k).then(x).catch(M=>{if(r)return;const _=e.retry??(Fl?0:3),R=e.retryDelay??FD,N=typeof R=="function"?R(n,M):R,O=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,M);if(t||!O){b(M);return}n++,e.onFail?.(n,M),PD(N).then(()=>m()?void 0:w()).then(()=>{t?b(M):C()})})};return{promise:u,cancel:d,continue:()=>(s?.(),u),cancelRetry:f,continueRetry:h,canStart:g,start:()=>(g()?C():w().then(C),u)}}function LD(){let e=[],t=0,n=g=>{g()},r=g=>{g()},s=g=>setTimeout(g,0);const o=g=>{s=g},l=g=>{let x;t++;try{x=g()}finally{t--,t||f()}return x},u=g=>{t?e.push(g):s(()=>{n(g)})},d=g=>(...x)=>{u(()=>{g(...x)})},f=()=>{const g=e;e=[],g.length&&s(()=>{r(()=>{g.forEach(x=>{n(x)})})})};return{batch:l,batchCalls:d,schedule:u,setNotifyFunction:g=>{n=g},setBatchNotifyFunction:g=>{r=g},setScheduler:o}}var Fn=LD(),Gk=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Sy(this.gcTime)&&(this.#e=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Fl?1/0:300*1e3))}clearGcTimeout(){this.#e&&(clearTimeout(this.#e),this.#e=void 0)}},$D=class extends Gk{#e;#t;#r;#n;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.cache,this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=BD(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){const n=Ey(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(ss).catch(ss):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>ws(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!zk(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#n&&(this.#o?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){const u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}const n=new AbortController,r=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},s=()=>{const u=Hk(this.options,t),d={queryKey:this.queryKey,meta:this.meta};return r(d),this.#o=!1,this.options.persister?this.options.persister(u,d,this):u(d)},o={fetchOptions:t,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};r(o),this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#s({type:"fetch",meta:o.fetchOptions?.meta});const l=u=>{lv(u)&&u.silent||this.#s({type:"error",error:u}),lv(u)||(this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return this.#n=Wk({initialPromise:t?.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:u=>{if(u===void 0){l(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(u)}catch(d){l(d);return}this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:l,onFail:(u,d)=>{this.#s({type:"failed",failureCount:u,error:d})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}),this.#n.start()}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Jk(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const r=e.error;return lv(r)&&r.revert&&this.#t?{...this.#t,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Fn.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Jk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:qk(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function BD(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var zD=class extends Zl{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,s=t.queryHash??_b(r,t);let o=this.get(s);return o||(o=new $D({cache:this,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Fn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>$0(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>$0(e,n)):t}notify(e){Fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Fn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Fn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},UD=class extends Gk{#e;#t;#r;constructor(e){super(),this.mutationId=e.mutationId,this.#t=e.mutationCache,this.#e=[],this.state=e.state||Qk(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#t.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#t.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#t.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){this.#r=Wk({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#n({type:"failed",failureCount:r,error:s})},onPause:()=>{this.#n({type:"pause"})},onContinue:()=>{this.#n({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#t.canRun(this)});const t=this.state.status==="pending",n=!this.#r.canStart();try{if(!t){this.#n({type:"pending",variables:e,isPaused:n}),await this.#t.config.onMutate?.(e,this);const s=await this.options.onMutate?.(e);s!==this.state.context&&this.#n({type:"pending",context:s,variables:e,isPaused:n})}const r=await this.#r.start();return await this.#t.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#t.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#n({type:"success",data:r}),r}catch(r){try{throw await this.#t.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#t.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#n({type:"error",error:r})}}finally{this.#t.runNext(this)}}#n(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Fn.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(e)}),this.#t.notify({mutation:this,type:"updated",action:e})})}};function Qk(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var VD=class extends Zl{constructor(e={}){super(),this.config=e,this.#e=new Map,this.#t=Date.now()}#e;#t;build(e,t,n){const r=new UD({mutationCache:this,mutationId:++this.#t,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){const t=Df(e),n=this.#e.get(t)??[];n.push(e),this.#e.set(t,n),this.notify({type:"added",mutation:e})}remove(e){const t=Df(e);if(this.#e.has(t)){const n=this.#e.get(t)?.filter(r=>r!==e);n&&(n.length===0?this.#e.delete(t):this.#e.set(t,n))}this.notify({type:"removed",mutation:e})}canRun(e){const t=this.#e.get(Df(e))?.find(n=>n.state.status==="pending");return!t||t===e}runNext(e){return this.#e.get(Df(e))?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve()}clear(){Fn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}getAll(){return[...this.#e.values()].flat()}find(e){const t={exact:!0,...e};return this.getAll().find(n=>B0(t,n))}findAll(e={}){return this.getAll().filter(t=>B0(e,t))}notify(e){Fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Fn.batch(()=>Promise.all(e.map(t=>t.continue().catch(ss))))}};function Df(e){return e.options.scope?.id??String(e.mutationId)}function HD(e){return{onFetch:(t,n)=>{const r=async()=>{const s=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,l=t.state.data?.pages||[],u=t.state.data?.pageParams||[],d={pages:[],pageParams:[]};let f=!1;const h=b=>{Object.defineProperty(b,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},m=Hk(t.options,t.fetchOptions),g=async(b,w,C)=>{if(f)return Promise.reject();if(w==null&&b.pages.length)return Promise.resolve(b);const k={queryKey:t.queryKey,pageParam:w,direction:C?"backward":"forward",meta:t.options.meta};h(k);const j=await m(k),{maxPages:M}=t.options,_=C?ID:OD;return{pages:_(b.pages,j,M),pageParams:_(b.pageParams,w,M)}};let x;if(o&&l.length){const b=o==="backward",w=b?qD:V0,C={pages:l,pageParams:u},k=w(s,C);x=await g(C,k,b)}else{x=await g(d,u[0]??s.initialPageParam);const b=e??l.length;for(let w=1;wt.options.persister?.(r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=r}}}function V0(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function qD(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var KD=class{#e;#t;#r;#n;#a;#o;#s;#i;constructor(e={}){this.#e=e.queryCache||new zD,this.#t=e.mutationCache||new VD,this.#r=e.defaultOptions||{},this.#n=new Map,this.#a=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#s=Rb.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=_p.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#s?.(),this.#s=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);if(t===void 0)return this.fetchQuery(e);{const n=this.defaultQueryOptions(e),r=this.#e.build(this,n);return e.revalidateIfStale&&r.isStaleByTime(_l(n.staleTime,r))&&this.prefetchQuery(n),Promise.resolve(t)}}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(r.queryHash)?.state.data,l=RD(t,o);if(l!==void 0)return this.#e.build(this,r).setData(l,{...n,manual:!0})}setQueriesData(e,t,n){return Fn.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Fn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e,r={type:"active",...e};return Fn.batch(()=>(n.findAll(e).forEach(s=>{s.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=Fn.batch(()=>this.#e.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(ss).catch(ss)}invalidateQueries(e={},t={}){return Fn.batch(()=>{if(this.#e.findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:t?.cancelRefetch??!0},r=Fn.batch(()=>this.#e.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let o=s.fetch(void 0,n);return n.throwOnError||(o=o.catch(ss)),s.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(ss)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(_l(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ss).catch(ss)}fetchInfiniteQuery(e){return e.behavior=HD(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ss).catch(ss)}resumePausedMutations(){return _p.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#n.set(xi(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()];let n={};return t.forEach(r=>{Ou(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){this.#a.set(xi(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#a.values()];let n={};return t.forEach(r=>{Ou(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=_b(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.enabled!==!0&&t.queryFn===Vk&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},WD=class extends Zl{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#r=void 0;#n=void 0;#a;#o;#s;#i;#f;#p;#c;#u;#l;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),H0(this.#t,this.options)?this.#d():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ky(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ky(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e,t){const n=this.options,r=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ws(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#w(),this.#t.setOptions(this.options),n._defaulted&&!Mp(this.options,n)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const s=this.hasListeners();s&&q0(this.#t,r,this.options,n)&&this.#d(),this.updateResult(t),s&&(this.#t!==r||ws(this.options.enabled,this.#t)!==ws(n.enabled,this.#t)||_l(this.options.staleTime,this.#t)!==_l(n.staleTime,this.#t))&&this.#g();const o=this.#m();s&&(this.#t!==r||ws(this.options.enabled,this.#t)!==ws(n.enabled,this.#t)||o!==this.#l)&&this.#v(o)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return JD(this,n)&&(this.#n=n,this.#o=this.options,this.#a=this.#t.state),n}getCurrentResult(){return this.#n}trackResult(e,t){const n={};return Object.keys(e).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.isFetchingOptimistic=!0,n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#w();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(ss)),t}#g(){this.#b();const e=_l(this.options.staleTime,this.#t);if(Fl||this.#n.isStale||!Sy(e))return;const n=zk(this.#n.dataUpdatedAt,e)+1;this.#c=setTimeout(()=>{this.#n.isStale||this.updateResult()},n)}#m(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#l=e,!(Fl||ws(this.options.enabled,this.#t)===!1||!Sy(this.#l)||this.#l===0)&&(this.#u=setInterval(()=>{(this.options.refetchIntervalInBackground||Rb.isFocused())&&this.#d()},this.#l))}#y(){this.#g(),this.#v(this.#m())}#b(){this.#c&&(clearTimeout(this.#c),this.#c=void 0)}#x(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,r=this.options,s=this.#n,o=this.#a,l=this.#o,d=e!==n?e.state:this.#r,{state:f}=e;let h={...f},m=!1,g;if(t._optimisticResults){const N=this.hasListeners(),O=!N&&H0(e,t),D=N&&q0(e,n,t,r);(O||D)&&(h={...h,...Jk(f.data,e.options)}),t._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:x,errorUpdatedAt:b,status:w}=h;if(t.select&&h.data!==void 0)if(s&&h.data===o?.data&&t.select===this.#i)g=this.#f;else try{this.#i=t.select,g=t.select(h.data),g=Ey(s?.data,g,t),this.#f=g,this.#s=null}catch(N){this.#s=N}else g=h.data;if(t.placeholderData!==void 0&&g===void 0&&w==="pending"){let N;if(s?.isPlaceholderData&&t.placeholderData===l?.placeholderData)N=s.data;else if(N=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,t.select&&N!==void 0)try{N=t.select(N),this.#s=null}catch(O){this.#s=O}N!==void 0&&(w="success",g=Ey(s?.data,N,t),m=!0)}this.#s&&(x=this.#s,g=this.#f,b=Date.now(),w="error");const C=h.fetchStatus==="fetching",k=w==="pending",j=w==="error",M=k&&C,_=g!==void 0;return{status:w,fetchStatus:h.fetchStatus,isPending:k,isSuccess:w==="success",isError:j,isInitialLoading:M,isLoading:M,data:g,dataUpdatedAt:h.dataUpdatedAt,error:x,errorUpdatedAt:b,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:C,isRefetching:C&&!k,isLoadingError:j&&!_,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:j&&_,isStale:Pb(e,t),refetch:this.refetch}}updateResult(e){const t=this.#n,n=this.createResult(this.#t,this.options);if(this.#a=this.#t.state,this.#o=this.options,this.#a.data!==void 0&&(this.#p=this.#t),Mp(n,t))return;this.#n=n;const r={},s=()=>{if(!t)return!0;const{notifyOnChangeProps:o}=this.options,l=typeof o=="function"?o():o;if(l==="all"||!l&&!this.#h.size)return!0;const u=new Set(l??this.#h);return this.options.throwOnError&&u.add("error"),Object.keys(this.#n).some(d=>{const f=d;return this.#n[f]!==t[f]&&u.has(f)})};e?.listeners!==!1&&s()&&(r.listeners=!0),this.#S({...r,...e})}#w(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#r=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#S(e){Fn.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function GD(e,t){return ws(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function H0(e,t){return GD(e,t)||e.state.data!==void 0&&ky(e,t,t.refetchOnMount)}function ky(e,t,n){if(ws(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Pb(e,t)}return!1}function q0(e,t,n,r){return(e!==t||ws(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Pb(e,n)}function Pb(e,t){return ws(t.enabled,e)!==!1&&e.isStaleByTime(_l(t.staleTime,e))}function JD(e,t){return!Mp(e.getCurrentResult(),t)}var QD=class extends Zl{#e;#t=void 0;#r;#n;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#a()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),Mp(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),n?.mutationKey&&this.options.mutationKey&&xi(n.mutationKey)!==xi(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(t){this.#a(),this.#o(t)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#a(),this.#o()}mutate(t,n){return this.#n=n,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(t)}#a(){const t=this.#r?.state??Qk();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#o(t){Fn.batch(()=>{if(this.#n&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context;t?.type==="success"?(this.#n.onSuccess?.(t.data,n,r),this.#n.onSettled?.(t.data,null,n,r)):t?.type==="error"&&(this.#n.onError?.(t.error,n,r),this.#n.onSettled?.(void 0,t.error,n,r))}this.listeners.forEach(n=>{n(this.#t)})})}},y=pd();const qe=fd(y),Yl=Bk({__proto__:null,default:qe},[y]);var Zk=y.createContext(void 0),Ob=e=>{const t=y.useContext(Zk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Yk=({client:e,children:t})=>(y.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),i.jsx(Zk.Provider,{value:e,children:t})),Xk=y.createContext(!1),ZD=()=>y.useContext(Xk);Xk.Provider;function YD(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var XD=y.createContext(YD()),eF=()=>y.useContext(XD);function ej(e,t){return typeof e=="function"?e(...t):!!e}function tF(){}var nF=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},rF=e=>{y.useEffect(()=>{e.clearReset()},[e])},sF=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&ej(n,[e.error,r]),oF=e=>{e.suspense&&(typeof e.staleTime!="number"&&(e.staleTime=1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},aF=(e,t)=>e?.suspense&&t.isPending,iF=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function lF(e,t,n){const r=Ob(),s=ZD(),o=eF(),l=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(l),l._optimisticResults=s?"isRestoring":"optimistic",oF(l),nF(l,o),rF(o);const[u]=y.useState(()=>new t(r,l)),d=u.getOptimisticResult(l);if(y.useSyncExternalStore(y.useCallback(f=>{const h=s?()=>{}:u.subscribe(Fn.batchCalls(f));return u.updateResult(),h},[u,s]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),y.useEffect(()=>{u.setOptions(l,{listeners:!1})},[l,u]),aF(l,d))throw iF(l,u,o);if(sF({result:d,errorResetBoundary:o,throwOnError:l.throwOnError,query:r.getQueryCache().get(l.queryHash)}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(l,d),l.notifyOnChangeProps?d:u.trackResult(d)}function mt(e,t){return lF(e,WD)}function cF(e,t){const n=Ob(),[r]=y.useState(()=>new QD(n,e));y.useEffect(()=>{r.setOptions(e)},[r,e]);const s=y.useSyncExternalStore(y.useCallback(l=>r.subscribe(Fn.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=y.useCallback((l,u)=>{r.mutate(l,u).catch(tF)},[r]);if(s.error&&ej(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:o,mutateAsync:s.mutate}}var Ff={},cv={exports:{}},Cr={},uv={exports:{}},dv={};/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var K0;function uF(){return K0||(K0=1,(function(e){function t(H,q){var he=H.length;H.push(q);e:for(;0>>1,F=H[A];if(0>>1;As(de,he))ges(Z,de)?(H[A]=Z,H[ge]=he,A=ge):(H[A]=de,H[te]=he,A=te);else if(ges(Z,he))H[A]=Z,H[ge]=he,A=ge;else break e}}return q}function s(H,q){var he=H.sortIndex-q.sortIndex;return he!==0?he:H.id-q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,u=l.now();e.unstable_now=function(){return l.now()-u}}var d=[],f=[],h=1,m=null,g=3,x=!1,b=!1,w=!1,C=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,j=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function M(H){for(var q=n(f);q!==null;){if(q.callback===null)r(f);else if(q.startTime<=H)r(f),q.sortIndex=q.expirationTime,t(d,q);else break;q=n(f)}}function _(H){if(w=!1,M(H),!b)if(n(d)!==null)b=!0,re(R);else{var q=n(f);q!==null&&Y(_,q.startTime-H)}}function R(H,q){b=!1,w&&(w=!1,k(D),D=-1),x=!0;var he=g;try{for(M(q),m=n(d);m!==null&&(!(m.expirationTime>q)||H&&!pe());){var A=m.callback;if(typeof A=="function"){m.callback=null,g=m.priorityLevel;var F=A(m.expirationTime<=q);q=e.unstable_now(),typeof F=="function"?m.callback=F:m===n(d)&&r(d),M(q)}else r(d);m=n(d)}if(m!==null)var fe=!0;else{var te=n(f);te!==null&&Y(_,te.startTime-q),fe=!1}return fe}finally{m=null,g=he,x=!1}}var N=!1,O=null,D=-1,z=5,Q=-1;function pe(){return!(e.unstable_now()-QH||125A?(H.sortIndex=he,t(f,H),n(d)===null&&H===n(f)&&(w?(k(D),D=-1):w=!0,Y(_,he-A))):(H.sortIndex=F,t(d,H),b||x||(b=!0,re(R))),H},e.unstable_shouldYield=pe,e.unstable_wrapCallback=function(H){var q=g;return function(){var he=g;g=q;try{return H.apply(this,arguments)}finally{g=he}}}})(dv)),dv}var W0;function dF(){return W0||(W0=1,uv.exports=uF()),uv.exports}/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var G0;function fF(){if(G0)return Cr;G0=1;var e=pd(),t=dF();function n(a){for(var c="https://reactjs.org/docs/error-decoder.html?invariant="+a,p=1;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d=Object.prototype.hasOwnProperty,f=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,h={},m={};function g(a){return d.call(m,a)?!0:d.call(h,a)?!1:f.test(a)?m[a]=!0:(h[a]=!0,!1)}function x(a,c,p,v){if(p!==null&&p.type===0)return!1;switch(typeof c){case"function":case"symbol":return!0;case"boolean":return v?!1:p!==null?!p.acceptsBooleans:(a=a.toLowerCase().slice(0,5),a!=="data-"&&a!=="aria-");default:return!1}}function b(a,c,p,v){if(c===null||typeof c>"u"||x(a,c,p,v))return!0;if(v)return!1;if(p!==null)switch(p.type){case 3:return!c;case 4:return c===!1;case 5:return isNaN(c);case 6:return isNaN(c)||1>c}return!1}function w(a,c,p,v,S,E,T){this.acceptsBooleans=c===2||c===3||c===4,this.attributeName=v,this.attributeNamespace=S,this.mustUseProperty=p,this.propertyName=a,this.type=c,this.sanitizeURL=E,this.removeEmptyString=T}var C={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new w(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var c=a[0];C[c]=new w(c,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new w(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new w(a,2,!1,a,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new w(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){C[a]=new w(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){C[a]=new w(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){C[a]=new w(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){C[a]=new w(a,5,!1,a.toLowerCase(),null,!1,!1)});var k=/[\-:]([a-z])/g;function j(a){return a[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var c=a.replace(k,j);C[c]=new w(c,1,!1,a,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var c=a.replace(k,j);C[c]=new w(c,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var c=a.replace(k,j);C[c]=new w(c,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(a){C[a]=new w(a,1,!1,a.toLowerCase(),null,!1,!1)}),C.xlinkHref=new w("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(a){C[a]=new w(a,1,!1,a.toLowerCase(),null,!0,!0)});function M(a,c,p,v){var S=C.hasOwnProperty(c)?C[c]:null;(S!==null?S.type!==0:v||!(2I||S[T]!==E[I]){var $=` +`+S[T].replace(" at new "," at ");return a.displayName&&$.includes("")&&($=$.replace("",a.displayName)),$}while(1<=T&&0<=I);break}}}finally{fe=!1,Error.prepareStackTrace=p}return(a=a?a.displayName||a.name:"")?F(a):""}function de(a){switch(a.tag){case 5:return F(a.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return a=te(a.type,!1),a;case 11:return a=te(a.type.render,!1),a;case 1:return a=te(a.type,!0),a;default:return""}}function ge(a){if(a==null)return null;if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case O:return"Fragment";case N:return"Portal";case z:return"Profiler";case D:return"StrictMode";case G:return"Suspense";case W:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case pe:return(a.displayName||"Context")+".Consumer";case Q:return(a._context.displayName||"Context")+".Provider";case V:var c=a.render;return a=a.displayName,a||(a=c.displayName||c.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case ie:return c=a.displayName||null,c!==null?c:ge(a.type)||"Memo";case re:c=a._payload,a=a._init;try{return ge(a(c))}catch{}}return null}function Z(a){var c=a.type;switch(a.tag){case 24:return"Cache";case 9:return(c.displayName||"Context")+".Consumer";case 10:return(c._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=c.render,a=a.displayName||a.name||"",c.displayName||(a!==""?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return c;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ge(c);case 8:return c===D?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof c=="function")return c.displayName||c.name||null;if(typeof c=="string")return c}return null}function ye(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return""}}function Re(a){var c=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(c==="checkbox"||c==="radio")}function $e(a){var c=Re(a)?"checked":"value",p=Object.getOwnPropertyDescriptor(a.constructor.prototype,c),v=""+a[c];if(!a.hasOwnProperty(c)&&typeof p<"u"&&typeof p.get=="function"&&typeof p.set=="function"){var S=p.get,E=p.set;return Object.defineProperty(a,c,{configurable:!0,get:function(){return S.call(this)},set:function(T){v=""+T,E.call(this,T)}}),Object.defineProperty(a,c,{enumerable:p.enumerable}),{getValue:function(){return v},setValue:function(T){v=""+T},stopTracking:function(){a._valueTracker=null,delete a[c]}}}}function Ye(a){a._valueTracker||(a._valueTracker=$e(a))}function Fe(a){if(!a)return!1;var c=a._valueTracker;if(!c)return!0;var p=c.getValue(),v="";return a&&(v=Re(a)?a.checked?"true":"false":a.value),a=v,a!==p?(c.setValue(a),!0):!1}function ft(a){if(a=a||(typeof document<"u"?document:void 0),typeof a>"u")return null;try{return a.activeElement||a.body}catch{return a.body}}function ln(a,c){var p=c.checked;return he({},c,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:p??a._wrapperState.initialChecked})}function Sn(a,c){var p=c.defaultValue==null?"":c.defaultValue,v=c.checked!=null?c.checked:c.defaultChecked;p=ye(c.value!=null?c.value:p),a._wrapperState={initialChecked:v,initialValue:p,controlled:c.type==="checkbox"||c.type==="radio"?c.checked!=null:c.value!=null}}function vn(a,c){c=c.checked,c!=null&&M(a,"checked",c,!1)}function Cn(a,c){vn(a,c);var p=ye(c.value),v=c.type;if(p!=null)v==="number"?(p===0&&a.value===""||a.value!=p)&&(a.value=""+p):a.value!==""+p&&(a.value=""+p);else if(v==="submit"||v==="reset"){a.removeAttribute("value");return}c.hasOwnProperty("value")?X(a,c.type,p):c.hasOwnProperty("defaultValue")&&X(a,c.type,ye(c.defaultValue)),c.checked==null&&c.defaultChecked!=null&&(a.defaultChecked=!!c.defaultChecked)}function L(a,c,p){if(c.hasOwnProperty("value")||c.hasOwnProperty("defaultValue")){var v=c.type;if(!(v!=="submit"&&v!=="reset"||c.value!==void 0&&c.value!==null))return;c=""+a._wrapperState.initialValue,p||c===a.value||(a.value=c),a.defaultValue=c}p=a.name,p!==""&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,p!==""&&(a.name=p)}function X(a,c,p){(c!=="number"||ft(a.ownerDocument)!==a)&&(p==null?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+p&&(a.defaultValue=""+p))}var ue=Array.isArray;function Ne(a,c,p,v){if(a=a.options,c){c={};for(var S=0;S"+c.valueOf().toString()+"",c=bn.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;c.firstChild;)a.appendChild(c.firstChild)}});function gr(a,c){if(c){var p=a.firstChild;if(p&&p===a.lastChild&&p.nodeType===3){p.nodeValue=c;return}}a.textContent=c}var Qn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ro=["Webkit","ms","Moz","O"];Object.keys(Qn).forEach(function(a){ro.forEach(function(c){c=c+a.charAt(0).toUpperCase()+a.substring(1),Qn[c]=Qn[a]})});function Bn(a,c,p){return c==null||typeof c=="boolean"||c===""?"":p||typeof c!="number"||c===0||Qn.hasOwnProperty(a)&&Qn[a]?(""+c).trim():c+"px"}function Te(a,c){a=a.style;for(var p in c)if(c.hasOwnProperty(p)){var v=p.indexOf("--")===0,S=Bn(p,c[p],v);p==="float"&&(p="cssFloat"),v?a.setProperty(p,S):a[p]=S}}var ut=he({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function It(a,c){if(c){if(ut[a]&&(c.children!=null||c.dangerouslySetInnerHTML!=null))throw Error(n(137,a));if(c.dangerouslySetInnerHTML!=null){if(c.children!=null)throw Error(n(60));if(typeof c.dangerouslySetInnerHTML!="object"||!("__html"in c.dangerouslySetInnerHTML))throw Error(n(61))}if(c.style!=null&&typeof c.style!="object")throw Error(n(62))}}function Tn(a,c){if(a.indexOf("-")===-1)return typeof c.is=="string";switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var mr=null;function vr(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var Gr=null,Jr=null,_r=null;function Rr(a){if(a=Lc(a)){if(typeof Gr!="function")throw Error(n(280));var c=a.stateNode;c&&(c=Qd(c),Gr(a.stateNode,a.type,c))}}function Uo(a){Jr?_r?_r.push(a):_r=[a]:Jr=a}function vc(){if(Jr){var a=Jr,c=_r;if(_r=Jr=null,Rr(a),c)for(a=0;a>>=0,a===0?32:31-(fs(a)/Rd|0)|0}var Pd=64,Od=4194304;function xc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function Id(a,c){var p=a.pendingLanes;if(p===0)return 0;var v=0,S=a.suspendedLanes,E=a.pingedLanes,T=p&268435455;if(T!==0){var I=T&~S;I!==0?v=xc(I):(E&=T,E!==0&&(v=xc(E)))}else T=p&~S,T!==0?v=xc(T):E!==0&&(v=xc(E));if(v===0)return 0;if(c!==0&&c!==v&&(c&S)===0&&(S=v&-v,E=c&-c,S>=E||S===16&&(E&4194240)!==0))return c;if((v&4)!==0&&(v|=p&16),c=a.entangledLanes,c!==0)for(a=a.entanglements,c&=v;0p;p++)c.push(a);return c}function wc(a,c,p){a.pendingLanes|=c,c!==536870912&&(a.suspendedLanes=0,a.pingedLanes=0),a=a.eventTimes,c=31-Tt(c),a[c]=p}function GI(a,c){var p=a.pendingLanes&~c;a.pendingLanes=c,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=c,a.mutableReadLanes&=c,a.entangledLanes&=c,c=a.entanglements;var v=a.eventTimes;for(a=a.expirationTimes;0=Mc),Nw=" ",Mw=!1;function _w(a,c){switch(a){case"keyup":return SA.indexOf(c.keyCode)!==-1;case"keydown":return c.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Rw(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var Ki=!1;function EA(a,c){switch(a){case"compositionend":return Rw(c);case"keypress":return c.which!==32?null:(Mw=!0,Nw);case"textInput":return a=c.data,a===Nw&&Mw?null:a;default:return null}}function kA(a,c){if(Ki)return a==="compositionend"||!Bg&&_w(a,c)?(a=Sw(),$d=Ig=Go=null,Ki=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(c.ctrlKey||c.altKey||c.metaKey)||c.ctrlKey&&c.altKey){if(c.char&&1=c)return{node:p,offset:c-a};a=v}e:{for(;p;){if(p.nextSibling){p=p.nextSibling;break e}p=p.parentNode}p=void 0}p=Lw(p)}}function Bw(a,c){return a&&c?a===c?!0:a&&a.nodeType===3?!1:c&&c.nodeType===3?Bw(a,c.parentNode):"contains"in a?a.contains(c):a.compareDocumentPosition?!!(a.compareDocumentPosition(c)&16):!1:!1}function zw(){for(var a=window,c=ft();c instanceof a.HTMLIFrameElement;){try{var p=typeof c.contentWindow.location.href=="string"}catch{p=!1}if(p)a=c.contentWindow;else break;c=ft(a.document)}return c}function Vg(a){var c=a&&a.nodeName&&a.nodeName.toLowerCase();return c&&(c==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||c==="textarea"||a.contentEditable==="true")}function IA(a){var c=zw(),p=a.focusedElem,v=a.selectionRange;if(c!==p&&p&&p.ownerDocument&&Bw(p.ownerDocument.documentElement,p)){if(v!==null&&Vg(p)){if(c=v.start,a=v.end,a===void 0&&(a=c),"selectionStart"in p)p.selectionStart=c,p.selectionEnd=Math.min(a,p.value.length);else if(a=(c=p.ownerDocument||document)&&c.defaultView||window,a.getSelection){a=a.getSelection();var S=p.textContent.length,E=Math.min(v.start,S);v=v.end===void 0?E:Math.min(v.end,S),!a.extend&&E>v&&(S=v,v=E,E=S),S=$w(p,E);var T=$w(p,v);S&&T&&(a.rangeCount!==1||a.anchorNode!==S.node||a.anchorOffset!==S.offset||a.focusNode!==T.node||a.focusOffset!==T.offset)&&(c=c.createRange(),c.setStart(S.node,S.offset),a.removeAllRanges(),E>v?(a.addRange(c),a.extend(T.node,T.offset)):(c.setEnd(T.node,T.offset),a.addRange(c)))}}for(c=[],a=p;a=a.parentNode;)a.nodeType===1&&c.push({element:a,left:a.scrollLeft,top:a.scrollTop});for(typeof p.focus=="function"&&p.focus(),p=0;p=document.documentMode,Wi=null,Hg=null,Oc=null,qg=!1;function Uw(a,c,p){var v=p.window===p?p.document:p.nodeType===9?p:p.ownerDocument;qg||Wi==null||Wi!==ft(v)||(v=Wi,"selectionStart"in v&&Vg(v)?v={start:v.selectionStart,end:v.selectionEnd}:(v=(v.ownerDocument&&v.ownerDocument.defaultView||window).getSelection(),v={anchorNode:v.anchorNode,anchorOffset:v.anchorOffset,focusNode:v.focusNode,focusOffset:v.focusOffset}),Oc&&Pc(Oc,v)||(Oc=v,v=Wd(Hg,"onSelect"),0Yi||(a.current=rm[Yi],rm[Yi]=null,Yi--)}function Qt(a,c){Yi++,rm[Yi]=a.current,a.current=c}var Yo={},Zn=Zo(Yo),yr=Zo(!1),Ka=Yo;function Xi(a,c){var p=a.type.contextTypes;if(!p)return Yo;var v=a.stateNode;if(v&&v.__reactInternalMemoizedUnmaskedChildContext===c)return v.__reactInternalMemoizedMaskedChildContext;var S={},E;for(E in p)S[E]=c[E];return v&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=c,a.__reactInternalMemoizedMaskedChildContext=S),S}function br(a){return a=a.childContextTypes,a!=null}function Zd(){en(yr),en(Zn)}function rS(a,c,p){if(Zn.current!==Yo)throw Error(n(168));Qt(Zn,c),Qt(yr,p)}function sS(a,c,p){var v=a.stateNode;if(c=c.childContextTypes,typeof v.getChildContext!="function")return p;v=v.getChildContext();for(var S in v)if(!(S in c))throw Error(n(108,Z(a)||"Unknown",S));return he({},p,v)}function Yd(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Yo,Ka=Zn.current,Qt(Zn,a),Qt(yr,yr.current),!0}function oS(a,c,p){var v=a.stateNode;if(!v)throw Error(n(169));p?(a=sS(a,c,Ka),v.__reactInternalMemoizedMergedChildContext=a,en(yr),en(Zn),Qt(Zn,a)):en(yr),Qt(yr,p)}var ao=null,Xd=!1,sm=!1;function aS(a){ao===null?ao=[a]:ao.push(a)}function KA(a){Xd=!0,aS(a)}function Xo(){if(!sm&&ao!==null){sm=!0;var a=0,c=Kt;try{var p=ao;for(Kt=1;a>=T,S-=T,io=1<<32-Tt(c)+S|p<dt?(Vn=tt,tt=null):Vn=tt.sibling;var Lt=be(J,tt,ee[dt],ke);if(Lt===null){tt===null&&(tt=Vn);break}a&&tt&&Lt.alternate===null&&c(J,tt),U=E(Lt,U,dt),et===null?Je=Lt:et.sibling=Lt,et=Lt,tt=Vn}if(dt===ee.length)return p(J,tt),cn&&Ga(J,dt),Je;if(tt===null){for(;dtdt?(Vn=tt,tt=null):Vn=tt.sibling;var la=be(J,tt,Lt.value,ke);if(la===null){tt===null&&(tt=Vn);break}a&&tt&&la.alternate===null&&c(J,tt),U=E(la,U,dt),et===null?Je=la:et.sibling=la,et=la,tt=Vn}if(Lt.done)return p(J,tt),cn&&Ga(J,dt),Je;if(tt===null){for(;!Lt.done;dt++,Lt=ee.next())Lt=we(J,Lt.value,ke),Lt!==null&&(U=E(Lt,U,dt),et===null?Je=Lt:et.sibling=Lt,et=Lt);return cn&&Ga(J,dt),Je}for(tt=v(J,tt);!Lt.done;dt++,Lt=ee.next())Lt=De(tt,J,dt,Lt.value,ke),Lt!==null&&(a&&Lt.alternate!==null&&tt.delete(Lt.key===null?dt:Lt.key),U=E(Lt,U,dt),et===null?Je=Lt:et.sibling=Lt,et=Lt);return a&&tt.forEach(function(jD){return c(J,jD)}),cn&&Ga(J,dt),Je}function kn(J,U,ee,ke){if(typeof ee=="object"&&ee!==null&&ee.type===O&&ee.key===null&&(ee=ee.props.children),typeof ee=="object"&&ee!==null){switch(ee.$$typeof){case R:e:{for(var Je=ee.key,et=U;et!==null;){if(et.key===Je){if(Je=ee.type,Je===O){if(et.tag===7){p(J,et.sibling),U=S(et,ee.props.children),U.return=J,J=U;break e}}else if(et.elementType===Je||typeof Je=="object"&&Je!==null&&Je.$$typeof===re&&fS(Je)===et.type){p(J,et.sibling),U=S(et,ee.props),U.ref=$c(J,et,ee),U.return=J,J=U;break e}p(J,et);break}else c(J,et);et=et.sibling}ee.type===O?(U=ni(ee.props.children,J.mode,ke,ee.key),U.return=J,J=U):(ke=Nf(ee.type,ee.key,ee.props,null,J.mode,ke),ke.ref=$c(J,U,ee),ke.return=J,J=ke)}return T(J);case N:e:{for(et=ee.key;U!==null;){if(U.key===et)if(U.tag===4&&U.stateNode.containerInfo===ee.containerInfo&&U.stateNode.implementation===ee.implementation){p(J,U.sibling),U=S(U,ee.children||[]),U.return=J,J=U;break e}else{p(J,U);break}else c(J,U);U=U.sibling}U=tv(ee,J.mode,ke),U.return=J,J=U}return T(J);case re:return et=ee._init,kn(J,U,et(ee._payload),ke)}if(ue(ee))return He(J,U,ee,ke);if(q(ee))return Ke(J,U,ee,ke);rf(J,ee)}return typeof ee=="string"&&ee!==""||typeof ee=="number"?(ee=""+ee,U!==null&&U.tag===6?(p(J,U.sibling),U=S(U,ee),U.return=J,J=U):(p(J,U),U=ev(ee,J.mode,ke),U.return=J,J=U),T(J)):p(J,U)}return kn}var rl=pS(!0),hS=pS(!1),sf=Zo(null),of=null,sl=null,um=null;function dm(){um=sl=of=null}function fm(a){var c=sf.current;en(sf),a._currentValue=c}function pm(a,c,p){for(;a!==null;){var v=a.alternate;if((a.childLanes&c)!==c?(a.childLanes|=c,v!==null&&(v.childLanes|=c)):v!==null&&(v.childLanes&c)!==c&&(v.childLanes|=c),a===p)break;a=a.return}}function ol(a,c){of=a,um=sl=null,a=a.dependencies,a!==null&&a.firstContext!==null&&((a.lanes&c)!==0&&(xr=!0),a.firstContext=null)}function Yr(a){var c=a._currentValue;if(um!==a)if(a={context:a,memoizedValue:c,next:null},sl===null){if(of===null)throw Error(n(308));sl=a,of.dependencies={lanes:0,firstContext:a}}else sl=sl.next=a;return c}var Ja=null;function hm(a){Ja===null?Ja=[a]:Ja.push(a)}function gS(a,c,p,v){var S=c.interleaved;return S===null?(p.next=p,hm(c)):(p.next=S.next,S.next=p),c.interleaved=p,co(a,v)}function co(a,c){a.lanes|=c;var p=a.alternate;for(p!==null&&(p.lanes|=c),p=a,a=a.return;a!==null;)a.childLanes|=c,p=a.alternate,p!==null&&(p.childLanes|=c),p=a,a=a.return;return p.tag===3?p.stateNode:null}var ea=!1;function gm(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function mS(a,c){a=a.updateQueue,c.updateQueue===a&&(c.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function uo(a,c){return{eventTime:a,lane:c,tag:0,payload:null,callback:null,next:null}}function ta(a,c,p){var v=a.updateQueue;if(v===null)return null;if(v=v.shared,(Ft&2)!==0){var S=v.pending;return S===null?c.next=c:(c.next=S.next,S.next=c),v.pending=c,co(a,p)}return S=v.interleaved,S===null?(c.next=c,hm(v)):(c.next=S.next,S.next=c),v.interleaved=c,co(a,p)}function af(a,c,p){if(c=c.updateQueue,c!==null&&(c=c.shared,(p&4194240)!==0)){var v=c.lanes;v&=a.pendingLanes,p|=v,c.lanes=p,Mg(a,p)}}function vS(a,c){var p=a.updateQueue,v=a.alternate;if(v!==null&&(v=v.updateQueue,p===v)){var S=null,E=null;if(p=p.firstBaseUpdate,p!==null){do{var T={eventTime:p.eventTime,lane:p.lane,tag:p.tag,payload:p.payload,callback:p.callback,next:null};E===null?S=E=T:E=E.next=T,p=p.next}while(p!==null);E===null?S=E=c:E=E.next=c}else S=E=c;p={baseState:v.baseState,firstBaseUpdate:S,lastBaseUpdate:E,shared:v.shared,effects:v.effects},a.updateQueue=p;return}a=p.lastBaseUpdate,a===null?p.firstBaseUpdate=c:a.next=c,p.lastBaseUpdate=c}function lf(a,c,p,v){var S=a.updateQueue;ea=!1;var E=S.firstBaseUpdate,T=S.lastBaseUpdate,I=S.shared.pending;if(I!==null){S.shared.pending=null;var $=I,ae=$.next;$.next=null,T===null?E=ae:T.next=ae,T=$;var xe=a.alternate;xe!==null&&(xe=xe.updateQueue,I=xe.lastBaseUpdate,I!==T&&(I===null?xe.firstBaseUpdate=ae:I.next=ae,xe.lastBaseUpdate=$))}if(E!==null){var we=S.baseState;T=0,xe=ae=$=null,I=E;do{var be=I.lane,De=I.eventTime;if((v&be)===be){xe!==null&&(xe=xe.next={eventTime:De,lane:0,tag:I.tag,payload:I.payload,callback:I.callback,next:null});e:{var He=a,Ke=I;switch(be=c,De=p,Ke.tag){case 1:if(He=Ke.payload,typeof He=="function"){we=He.call(De,we,be);break e}we=He;break e;case 3:He.flags=He.flags&-65537|128;case 0:if(He=Ke.payload,be=typeof He=="function"?He.call(De,we,be):He,be==null)break e;we=he({},we,be);break e;case 2:ea=!0}}I.callback!==null&&I.lane!==0&&(a.flags|=64,be=S.effects,be===null?S.effects=[I]:be.push(I))}else De={eventTime:De,lane:be,tag:I.tag,payload:I.payload,callback:I.callback,next:null},xe===null?(ae=xe=De,$=we):xe=xe.next=De,T|=be;if(I=I.next,I===null){if(I=S.shared.pending,I===null)break;be=I,I=be.next,be.next=null,S.lastBaseUpdate=be,S.shared.pending=null}}while(!0);if(xe===null&&($=we),S.baseState=$,S.firstBaseUpdate=ae,S.lastBaseUpdate=xe,c=S.shared.interleaved,c!==null){S=c;do T|=S.lane,S=S.next;while(S!==c)}else E===null&&(S.shared.lanes=0);Ya|=T,a.lanes=T,a.memoizedState=we}}function yS(a,c,p){if(a=c.effects,c.effects=null,a!==null)for(c=0;cp?p:4,a(!0);var v=xm.transition;xm.transition={};try{a(!1),c()}finally{Kt=p,xm.transition=v}}function FS(){return Xr().memoizedState}function QA(a,c,p){var v=oa(a);if(p={lane:v,action:p,hasEagerState:!1,eagerState:null,next:null},LS(a))$S(c,p);else if(p=gS(a,c,p,v),p!==null){var S=ir();ys(p,a,v,S),BS(p,c,v)}}function ZA(a,c,p){var v=oa(a),S={lane:v,action:p,hasEagerState:!1,eagerState:null,next:null};if(LS(a))$S(c,S);else{var E=a.alternate;if(a.lanes===0&&(E===null||E.lanes===0)&&(E=c.lastRenderedReducer,E!==null))try{var T=c.lastRenderedState,I=E(T,p);if(S.hasEagerState=!0,S.eagerState=I,ps(I,T)){var $=c.interleaved;$===null?(S.next=S,hm(c)):(S.next=$.next,$.next=S),c.interleaved=S;return}}catch{}finally{}p=gS(a,c,S,v),p!==null&&(S=ir(),ys(p,a,v,S),BS(p,c,v))}}function LS(a){var c=a.alternate;return a===hn||c!==null&&c===hn}function $S(a,c){Vc=df=!0;var p=a.pending;p===null?c.next=c:(c.next=p.next,p.next=c),a.pending=c}function BS(a,c,p){if((p&4194240)!==0){var v=c.lanes;v&=a.pendingLanes,p|=v,c.lanes=p,Mg(a,p)}}var hf={readContext:Yr,useCallback:Yn,useContext:Yn,useEffect:Yn,useImperativeHandle:Yn,useInsertionEffect:Yn,useLayoutEffect:Yn,useMemo:Yn,useReducer:Yn,useRef:Yn,useState:Yn,useDebugValue:Yn,useDeferredValue:Yn,useTransition:Yn,useMutableSource:Yn,useSyncExternalStore:Yn,useId:Yn,unstable_isNewReconciler:!1},YA={readContext:Yr,useCallback:function(a,c){return Fs().memoizedState=[a,c===void 0?null:c],a},useContext:Yr,useEffect:MS,useImperativeHandle:function(a,c,p){return p=p!=null?p.concat([a]):null,ff(4194308,4,PS.bind(null,c,a),p)},useLayoutEffect:function(a,c){return ff(4194308,4,a,c)},useInsertionEffect:function(a,c){return ff(4,2,a,c)},useMemo:function(a,c){var p=Fs();return c=c===void 0?null:c,a=a(),p.memoizedState=[a,c],a},useReducer:function(a,c,p){var v=Fs();return c=p!==void 0?p(c):c,v.memoizedState=v.baseState=c,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:c},v.queue=a,a=a.dispatch=QA.bind(null,hn,a),[v.memoizedState,a]},useRef:function(a){var c=Fs();return a={current:a},c.memoizedState=a},useState:TS,useDebugValue:Tm,useDeferredValue:function(a){return Fs().memoizedState=a},useTransition:function(){var a=TS(!1),c=a[0];return a=JA.bind(null,a[1]),Fs().memoizedState=a,[c,a]},useMutableSource:function(){},useSyncExternalStore:function(a,c,p){var v=hn,S=Fs();if(cn){if(p===void 0)throw Error(n(407));p=p()}else{if(p=c(),Un===null)throw Error(n(349));(Za&30)!==0||SS(v,c,p)}S.memoizedState=p;var E={value:p,getSnapshot:c};return S.queue=E,MS(ES.bind(null,v,E,a),[a]),v.flags|=2048,Kc(9,CS.bind(null,v,E,p,c),void 0,null),p},useId:function(){var a=Fs(),c=Un.identifierPrefix;if(cn){var p=lo,v=io;p=(v&~(1<<32-Tt(v)-1)).toString(32)+p,c=":"+c+"R"+p,p=Hc++,0<\/script>",a=a.removeChild(a.firstChild)):typeof v.is=="string"?a=T.createElement(p,{is:v.is}):(a=T.createElement(p),p==="select"&&(T=a,v.multiple?T.multiple=!0:v.size&&(T.size=v.size))):a=T.createElementNS(a,p),a[As]=c,a[Fc]=v,a0(a,c,!1,!1),c.stateNode=a;e:{switch(T=Tn(p,v),p){case"dialog":Xt("cancel",a),Xt("close",a),S=v;break;case"iframe":case"object":case"embed":Xt("load",a),S=v;break;case"video":case"audio":for(S=0;Sul&&(c.flags|=128,v=!0,Wc(E,!1),c.lanes=4194304)}else{if(!v)if(a=cf(T),a!==null){if(c.flags|=128,v=!0,p=a.updateQueue,p!==null&&(c.updateQueue=p,c.flags|=4),Wc(E,!0),E.tail===null&&E.tailMode==="hidden"&&!T.alternate&&!cn)return Xn(c),null}else 2*Gt()-E.renderingStartTime>ul&&p!==1073741824&&(c.flags|=128,v=!0,Wc(E,!1),c.lanes=4194304);E.isBackwards?(T.sibling=c.child,c.child=T):(p=E.last,p!==null?p.sibling=T:c.child=T,E.last=T)}return E.tail!==null?(c=E.tail,E.rendering=c,E.tail=c.sibling,E.renderingStartTime=Gt(),c.sibling=null,p=pn.current,Qt(pn,v?p&1|2:p&1),c):(Xn(c),null);case 22:case 23:return Zm(),v=c.memoizedState!==null,a!==null&&a.memoizedState!==null!==v&&(c.flags|=8192),v&&(c.mode&1)!==0?(Dr&1073741824)!==0&&(Xn(c),c.subtreeFlags&6&&(c.flags|=8192)):Xn(c),null;case 24:return null;case 25:return null}throw Error(n(156,c.tag))}function aD(a,c){switch(am(c),c.tag){case 1:return br(c.type)&&Zd(),a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 3:return al(),en(yr),en(Zn),bm(),a=c.flags,(a&65536)!==0&&(a&128)===0?(c.flags=a&-65537|128,c):null;case 5:return vm(c),null;case 13:if(en(pn),a=c.memoizedState,a!==null&&a.dehydrated!==null){if(c.alternate===null)throw Error(n(340));nl()}return a=c.flags,a&65536?(c.flags=a&-65537|128,c):null;case 19:return en(pn),null;case 4:return al(),null;case 10:return fm(c.type._context),null;case 22:case 23:return Zm(),null;case 24:return null;default:return null}}var yf=!1,er=!1,iD=typeof WeakSet=="function"?WeakSet:Set,ze=null;function ll(a,c){var p=a.ref;if(p!==null)if(typeof p=="function")try{p(null)}catch(v){xn(a,c,v)}else p.current=null}function $m(a,c,p){try{p()}catch(v){xn(a,c,v)}}var c0=!1;function lD(a,c){if(Zg=Fd,a=zw(),Vg(a)){if("selectionStart"in a)var p={start:a.selectionStart,end:a.selectionEnd};else e:{p=(p=a.ownerDocument)&&p.defaultView||window;var v=p.getSelection&&p.getSelection();if(v&&v.rangeCount!==0){p=v.anchorNode;var S=v.anchorOffset,E=v.focusNode;v=v.focusOffset;try{p.nodeType,E.nodeType}catch{p=null;break e}var T=0,I=-1,$=-1,ae=0,xe=0,we=a,be=null;t:for(;;){for(var De;we!==p||S!==0&&we.nodeType!==3||(I=T+S),we!==E||v!==0&&we.nodeType!==3||($=T+v),we.nodeType===3&&(T+=we.nodeValue.length),(De=we.firstChild)!==null;)be=we,we=De;for(;;){if(we===a)break t;if(be===p&&++ae===S&&(I=T),be===E&&++xe===v&&($=T),(De=we.nextSibling)!==null)break;we=be,be=we.parentNode}we=De}p=I===-1||$===-1?null:{start:I,end:$}}else p=null}p=p||{start:0,end:0}}else p=null;for(Yg={focusedElem:a,selectionRange:p},Fd=!1,ze=c;ze!==null;)if(c=ze,a=c.child,(c.subtreeFlags&1028)!==0&&a!==null)a.return=c,ze=a;else for(;ze!==null;){c=ze;try{var He=c.alternate;if((c.flags&1024)!==0)switch(c.tag){case 0:case 11:case 15:break;case 1:if(He!==null){var Ke=He.memoizedProps,kn=He.memoizedState,J=c.stateNode,U=J.getSnapshotBeforeUpdate(c.elementType===c.type?Ke:gs(c.type,Ke),kn);J.__reactInternalSnapshotBeforeUpdate=U}break;case 3:var ee=c.stateNode.containerInfo;ee.nodeType===1?ee.textContent="":ee.nodeType===9&&ee.documentElement&&ee.removeChild(ee.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(ke){xn(c,c.return,ke)}if(a=c.sibling,a!==null){a.return=c.return,ze=a;break}ze=c.return}return He=c0,c0=!1,He}function Gc(a,c,p){var v=c.updateQueue;if(v=v!==null?v.lastEffect:null,v!==null){var S=v=v.next;do{if((S.tag&a)===a){var E=S.destroy;S.destroy=void 0,E!==void 0&&$m(c,p,E)}S=S.next}while(S!==v)}}function bf(a,c){if(c=c.updateQueue,c=c!==null?c.lastEffect:null,c!==null){var p=c=c.next;do{if((p.tag&a)===a){var v=p.create;p.destroy=v()}p=p.next}while(p!==c)}}function Bm(a){var c=a.ref;if(c!==null){var p=a.stateNode;switch(a.tag){case 5:a=p;break;default:a=p}typeof c=="function"?c(a):c.current=a}}function u0(a){var c=a.alternate;c!==null&&(a.alternate=null,u0(c)),a.child=null,a.deletions=null,a.sibling=null,a.tag===5&&(c=a.stateNode,c!==null&&(delete c[As],delete c[Fc],delete c[nm],delete c[HA],delete c[qA])),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}function d0(a){return a.tag===5||a.tag===3||a.tag===4}function f0(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||d0(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function zm(a,c,p){var v=a.tag;if(v===5||v===6)a=a.stateNode,c?p.nodeType===8?p.parentNode.insertBefore(a,c):p.insertBefore(a,c):(p.nodeType===8?(c=p.parentNode,c.insertBefore(a,p)):(c=p,c.appendChild(a)),p=p._reactRootContainer,p!=null||c.onclick!==null||(c.onclick=Jd));else if(v!==4&&(a=a.child,a!==null))for(zm(a,c,p),a=a.sibling;a!==null;)zm(a,c,p),a=a.sibling}function Um(a,c,p){var v=a.tag;if(v===5||v===6)a=a.stateNode,c?p.insertBefore(a,c):p.appendChild(a);else if(v!==4&&(a=a.child,a!==null))for(Um(a,c,p),a=a.sibling;a!==null;)Um(a,c,p),a=a.sibling}var qn=null,ms=!1;function na(a,c,p){for(p=p.child;p!==null;)p0(a,c,p),p=p.sibling}function p0(a,c,p){if(Dt&&typeof Dt.onCommitFiberUnmount=="function")try{Dt.onCommitFiberUnmount(pt,p)}catch{}switch(p.tag){case 5:er||ll(p,c);case 6:var v=qn,S=ms;qn=null,na(a,c,p),qn=v,ms=S,qn!==null&&(ms?(a=qn,p=p.stateNode,a.nodeType===8?a.parentNode.removeChild(p):a.removeChild(p)):qn.removeChild(p.stateNode));break;case 18:qn!==null&&(ms?(a=qn,p=p.stateNode,a.nodeType===8?tm(a.parentNode,p):a.nodeType===1&&tm(a,p),jc(a)):tm(qn,p.stateNode));break;case 4:v=qn,S=ms,qn=p.stateNode.containerInfo,ms=!0,na(a,c,p),qn=v,ms=S;break;case 0:case 11:case 14:case 15:if(!er&&(v=p.updateQueue,v!==null&&(v=v.lastEffect,v!==null))){S=v=v.next;do{var E=S,T=E.destroy;E=E.tag,T!==void 0&&((E&2)!==0||(E&4)!==0)&&$m(p,c,T),S=S.next}while(S!==v)}na(a,c,p);break;case 1:if(!er&&(ll(p,c),v=p.stateNode,typeof v.componentWillUnmount=="function"))try{v.props=p.memoizedProps,v.state=p.memoizedState,v.componentWillUnmount()}catch(I){xn(p,c,I)}na(a,c,p);break;case 21:na(a,c,p);break;case 22:p.mode&1?(er=(v=er)||p.memoizedState!==null,na(a,c,p),er=v):na(a,c,p);break;default:na(a,c,p)}}function h0(a){var c=a.updateQueue;if(c!==null){a.updateQueue=null;var p=a.stateNode;p===null&&(p=a.stateNode=new iD),c.forEach(function(v){var S=vD.bind(null,a,v);p.has(v)||(p.add(v),v.then(S,S))})}}function vs(a,c){var p=c.deletions;if(p!==null)for(var v=0;vS&&(S=T),v&=~E}if(v=S,v=Gt()-v,v=(120>v?120:480>v?480:1080>v?1080:1920>v?1920:3e3>v?3e3:4320>v?4320:1960*uD(v/1960))-v,10a?16:a,sa===null)var v=!1;else{if(a=sa,sa=null,Ef=0,(Ft&6)!==0)throw Error(n(331));var S=Ft;for(Ft|=4,ze=a.current;ze!==null;){var E=ze,T=E.child;if((ze.flags&16)!==0){var I=E.deletions;if(I!==null){for(var $=0;$Gt()-qm?ei(a,0):Hm|=p),Sr(a,c)}function T0(a,c){c===0&&((a.mode&1)===0?c=1:(c=Od,Od<<=1,(Od&130023424)===0&&(Od=4194304)));var p=ir();a=co(a,c),a!==null&&(wc(a,c,p),Sr(a,p))}function mD(a){var c=a.memoizedState,p=0;c!==null&&(p=c.retryLane),T0(a,p)}function vD(a,c){var p=0;switch(a.tag){case 13:var v=a.stateNode,S=a.memoizedState;S!==null&&(p=S.retryLane);break;case 19:v=a.stateNode;break;default:throw Error(n(314))}v!==null&&v.delete(c),T0(a,p)}var N0;N0=function(a,c,p){if(a!==null)if(a.memoizedProps!==c.pendingProps||yr.current)xr=!0;else{if((a.lanes&p)===0&&(c.flags&128)===0)return xr=!1,sD(a,c,p);xr=(a.flags&131072)!==0}else xr=!1,cn&&(c.flags&1048576)!==0&&iS(c,tf,c.index);switch(c.lanes=0,c.tag){case 2:var v=c.type;vf(a,c),a=c.pendingProps;var S=Xi(c,Zn.current);ol(c,p),S=Sm(null,c,v,a,S,p);var E=Cm();return c.flags|=1,typeof S=="object"&&S!==null&&typeof S.render=="function"&&S.$$typeof===void 0?(c.tag=1,c.memoizedState=null,c.updateQueue=null,br(v)?(E=!0,Yd(c)):E=!1,c.memoizedState=S.state!==null&&S.state!==void 0?S.state:null,gm(c),S.updater=gf,c.stateNode=S,S._reactInternals=c,Mm(c,v,a,p),c=Om(null,c,v,!0,E,p)):(c.tag=0,cn&&E&&om(c),ar(null,c,S,p),c=c.child),c;case 16:v=c.elementType;e:{switch(vf(a,c),a=c.pendingProps,S=v._init,v=S(v._payload),c.type=v,S=c.tag=bD(v),a=gs(v,a),S){case 0:c=Pm(null,c,v,a,p);break e;case 1:c=e0(null,c,v,a,p);break e;case 11:c=JS(null,c,v,a,p);break e;case 14:c=QS(null,c,v,gs(v.type,a),p);break e}throw Error(n(306,v,""))}return c;case 0:return v=c.type,S=c.pendingProps,S=c.elementType===v?S:gs(v,S),Pm(a,c,v,S,p);case 1:return v=c.type,S=c.pendingProps,S=c.elementType===v?S:gs(v,S),e0(a,c,v,S,p);case 3:e:{if(t0(c),a===null)throw Error(n(387));v=c.pendingProps,E=c.memoizedState,S=E.element,mS(a,c),lf(c,v,null,p);var T=c.memoizedState;if(v=T.element,E.isDehydrated)if(E={element:v,isDehydrated:!1,cache:T.cache,pendingSuspenseBoundaries:T.pendingSuspenseBoundaries,transitions:T.transitions},c.updateQueue.baseState=E,c.memoizedState=E,c.flags&256){S=il(Error(n(423)),c),c=n0(a,c,v,p,S);break e}else if(v!==S){S=il(Error(n(424)),c),c=n0(a,c,v,p,S);break e}else for(Ar=Qo(c.stateNode.containerInfo.firstChild),Ir=c,cn=!0,hs=null,p=hS(c,null,v,p),c.child=p;p;)p.flags=p.flags&-3|4096,p=p.sibling;else{if(nl(),v===S){c=fo(a,c,p);break e}ar(a,c,v,p)}c=c.child}return c;case 5:return bS(c),a===null&&lm(c),v=c.type,S=c.pendingProps,E=a!==null?a.memoizedProps:null,T=S.children,Xg(v,S)?T=null:E!==null&&Xg(v,E)&&(c.flags|=32),XS(a,c),ar(a,c,T,p),c.child;case 6:return a===null&&lm(c),null;case 13:return r0(a,c,p);case 4:return mm(c,c.stateNode.containerInfo),v=c.pendingProps,a===null?c.child=rl(c,null,v,p):ar(a,c,v,p),c.child;case 11:return v=c.type,S=c.pendingProps,S=c.elementType===v?S:gs(v,S),JS(a,c,v,S,p);case 7:return ar(a,c,c.pendingProps,p),c.child;case 8:return ar(a,c,c.pendingProps.children,p),c.child;case 12:return ar(a,c,c.pendingProps.children,p),c.child;case 10:e:{if(v=c.type._context,S=c.pendingProps,E=c.memoizedProps,T=S.value,Qt(sf,v._currentValue),v._currentValue=T,E!==null)if(ps(E.value,T)){if(E.children===S.children&&!yr.current){c=fo(a,c,p);break e}}else for(E=c.child,E!==null&&(E.return=c);E!==null;){var I=E.dependencies;if(I!==null){T=E.child;for(var $=I.firstContext;$!==null;){if($.context===v){if(E.tag===1){$=uo(-1,p&-p),$.tag=2;var ae=E.updateQueue;if(ae!==null){ae=ae.shared;var xe=ae.pending;xe===null?$.next=$:($.next=xe.next,xe.next=$),ae.pending=$}}E.lanes|=p,$=E.alternate,$!==null&&($.lanes|=p),pm(E.return,p,c),I.lanes|=p;break}$=$.next}}else if(E.tag===10)T=E.type===c.type?null:E.child;else if(E.tag===18){if(T=E.return,T===null)throw Error(n(341));T.lanes|=p,I=T.alternate,I!==null&&(I.lanes|=p),pm(T,p,c),T=E.sibling}else T=E.child;if(T!==null)T.return=E;else for(T=E;T!==null;){if(T===c){T=null;break}if(E=T.sibling,E!==null){E.return=T.return,T=E;break}T=T.return}E=T}ar(a,c,S.children,p),c=c.child}return c;case 9:return S=c.type,v=c.pendingProps.children,ol(c,p),S=Yr(S),v=v(S),c.flags|=1,ar(a,c,v,p),c.child;case 14:return v=c.type,S=gs(v,c.pendingProps),S=gs(v.type,S),QS(a,c,v,S,p);case 15:return ZS(a,c,c.type,c.pendingProps,p);case 17:return v=c.type,S=c.pendingProps,S=c.elementType===v?S:gs(v,S),vf(a,c),c.tag=1,br(v)?(a=!0,Yd(c)):a=!1,ol(c,p),US(c,v,S),Mm(c,v,S,p),Om(null,c,v,!0,a,p);case 19:return o0(a,c,p);case 22:return YS(a,c,p)}throw Error(n(156,c.tag))};function M0(a,c){return Nn(a,c)}function yD(a,c,p,v){this.tag=a,this.key=p,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=c,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=v,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ts(a,c,p,v){return new yD(a,c,p,v)}function Xm(a){return a=a.prototype,!(!a||!a.isReactComponent)}function bD(a){if(typeof a=="function")return Xm(a)?1:0;if(a!=null){if(a=a.$$typeof,a===V)return 11;if(a===ie)return 14}return 2}function ia(a,c){var p=a.alternate;return p===null?(p=ts(a.tag,c,a.key,a.mode),p.elementType=a.elementType,p.type=a.type,p.stateNode=a.stateNode,p.alternate=a,a.alternate=p):(p.pendingProps=c,p.type=a.type,p.flags=0,p.subtreeFlags=0,p.deletions=null),p.flags=a.flags&14680064,p.childLanes=a.childLanes,p.lanes=a.lanes,p.child=a.child,p.memoizedProps=a.memoizedProps,p.memoizedState=a.memoizedState,p.updateQueue=a.updateQueue,c=a.dependencies,p.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext},p.sibling=a.sibling,p.index=a.index,p.ref=a.ref,p}function Nf(a,c,p,v,S,E){var T=2;if(v=a,typeof a=="function")Xm(a)&&(T=1);else if(typeof a=="string")T=5;else e:switch(a){case O:return ni(p.children,S,E,c);case D:T=8,S|=8;break;case z:return a=ts(12,p,c,S|2),a.elementType=z,a.lanes=E,a;case G:return a=ts(13,p,c,S),a.elementType=G,a.lanes=E,a;case W:return a=ts(19,p,c,S),a.elementType=W,a.lanes=E,a;case Y:return Mf(p,S,E,c);default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case Q:T=10;break e;case pe:T=9;break e;case V:T=11;break e;case ie:T=14;break e;case re:T=16,v=null;break e}throw Error(n(130,a==null?a:typeof a,""))}return c=ts(T,p,c,S),c.elementType=a,c.type=v,c.lanes=E,c}function ni(a,c,p,v){return a=ts(7,a,v,c),a.lanes=p,a}function Mf(a,c,p,v){return a=ts(22,a,v,c),a.elementType=Y,a.lanes=p,a.stateNode={isHidden:!1},a}function ev(a,c,p){return a=ts(6,a,null,c),a.lanes=p,a}function tv(a,c,p){return c=ts(4,a.children!==null?a.children:[],a.key,c),c.lanes=p,c.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},c}function xD(a,c,p,v,S){this.tag=c,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ng(0),this.expirationTimes=Ng(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ng(0),this.identifierPrefix=v,this.onRecoverableError=S,this.mutableSourceEagerHydrationData=null}function nv(a,c,p,v,S,E,T,I,$){return a=new xD(a,c,p,I,$),c===1?(c=1,E===!0&&(c|=8)):c=0,E=ts(3,null,null,c),a.current=E,E.stateNode=a,E.memoizedState={element:v,isDehydrated:p,cache:null,transitions:null,pendingSuspenseBoundaries:null},gm(E),a}function wD(a,c,p){var v=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),cv.exports=fF(),cv.exports}var Q0;function pF(){if(Q0)return Ff;Q0=1;var e=tj();return Ff.createRoot=e.createRoot,Ff.hydrateRoot=e.hydrateRoot,Ff}var hF=pF();const gF=fd(hF),mF=(...e)=>{console?.warn&&(fi(e[0])&&(e[0]=`react-i18next:: ${e[0]}`),console.warn(...e))},Z0={},jy=(...e)=>{fi(e[0])&&Z0[e[0]]||(fi(e[0])&&(Z0[e[0]]=new Date),mF(...e))},nj=(e,t)=>()=>{if(e.isInitialized)t();else{const n=()=>{setTimeout(()=>{e.off("initialized",n)},0),t()};e.on("initialized",n)}},Y0=(e,t,n)=>{e.loadNamespaces(t,nj(e,n))},X0=(e,t,n,r)=>{fi(n)&&(n=[n]),n.forEach(s=>{e.options.ns.indexOf(s)<0&&e.options.ns.push(s)}),e.loadLanguages(t,nj(e,r))},vF=(e,t,n={})=>!t.languages||!t.languages.length?(jy("i18n.languages were undefined or empty",t.languages),!0):t.hasLoadedNamespace(e,{lng:n.lng,precheck:(r,s)=>{if(n.bindI18n?.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,e))return!1}}),fi=e=>typeof e=="string",yF=e=>typeof e=="object"&&e!==null,bF=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,xF={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},wF=e=>xF[e],SF=e=>e.replace(bF,wF);let Ty={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:SF};const CF=(e={})=>{Ty={...Ty,...e}},EF=()=>Ty;let rj;const kF=e=>{rj=e},jF=()=>rj,TF={type:"3rdParty",init(e){CF(e.options.react),kF(e)}},sj=y.createContext();class NF{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(n=>{this.usedNamespaces[n]??=!0})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const MF=(e,t)=>{const n=y.useRef();return y.useEffect(()=>{n.current=e},[e,t]),n.current},oj=(e,t,n,r)=>e.getFixedT(t,n,r),_F=(e,t,n,r)=>y.useCallback(oj(e,t,n,r),[e,t,n,r]),Ve=(e,t={})=>{const{i18n:n}=t,{i18n:r,defaultNS:s}=y.useContext(sj)||{},o=n||r||jF();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new NF),!o){jy("You will need to pass in an i18next instance by using initReactI18next");const _=(N,O)=>fi(O)?O:yF(O)&&fi(O.defaultValue)?O.defaultValue:Array.isArray(N)?N[N.length-1]:N,R=[_,{},!1];return R.t=_,R.i18n={},R.ready=!1,R}o.options.react?.wait&&jy("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const l={...EF(),...o.options.react,...t},{useSuspense:u,keyPrefix:d}=l;let f=s||o.options?.defaultNS;f=fi(f)?[f]:f||["translation"],o.reportNamespaces.addUsedNamespaces?.(f);const h=(o.isInitialized||o.initializedStoreOnce)&&f.every(_=>vF(_,o,l)),m=_F(o,t.lng||null,l.nsMode==="fallback"?f:f[0],d),g=()=>m,x=()=>oj(o,t.lng||null,l.nsMode==="fallback"?f:f[0],d),[b,w]=y.useState(g);let C=f.join();t.lng&&(C=`${t.lng}${C}`);const k=MF(C),j=y.useRef(!0);y.useEffect(()=>{const{bindI18n:_,bindI18nStore:R}=l;j.current=!0,!h&&!u&&(t.lng?X0(o,t.lng,f,()=>{j.current&&w(x)}):Y0(o,f,()=>{j.current&&w(x)})),h&&k&&k!==C&&j.current&&w(x);const N=()=>{j.current&&w(x)};return _&&o?.on(_,N),R&&o?.store.on(R,N),()=>{j.current=!1,o&&_?.split(" ").forEach(O=>o.off(O,N)),R&&o&&R.split(" ").forEach(O=>o.store.off(O,N))}},[o,C]),y.useEffect(()=>{j.current&&h&&w(g)},[o,d,h]);const M=[b,o,h];if(M.t=b,M.i18n=o,M.ready=h,h||!h&&!u)return M;throw new Promise(_=>{t.lng?X0(o,t.lng,f,()=>_()):Y0(o,f,()=>_())})};function RF({i18n:e,defaultNS:t,children:n}){const r=y.useMemo(()=>({i18n:e,defaultNS:t}),[e,t]);return y.createElement(sj.Provider,{value:r},n)}var Ma=tj();const Ib=fd(Ma),PF=Bk({__proto__:null,default:Ib},[Ma]);/** + * @remix-run/router v1.18.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function mn(){return mn=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Ll(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function IF(){return Math.random().toString(36).substr(2,8)}function tC(e,t){return{usr:e.state,key:e.key,idx:t}}function Iu(e,t,n,r){return n===void 0&&(n=null),mn({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?_a(t):t,{state:n,key:t&&t.key||r||IF()})}function wi(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function _a(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function AF(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:o=!1}=r,l=s.history,u=_n.Pop,d=null,f=h();f==null&&(f=0,l.replaceState(mn({},l.state,{idx:f}),""));function h(){return(l.state||{idx:null}).idx}function m(){u=_n.Pop;let C=h(),k=C==null?null:C-f;f=C,d&&d({action:u,location:w.location,delta:k})}function g(C,k){u=_n.Push;let j=Iu(w.location,C,k);f=h()+1;let M=tC(j,f),_=w.createHref(j);try{l.pushState(M,"",_)}catch(R){if(R instanceof DOMException&&R.name==="DataCloneError")throw R;s.location.assign(_)}o&&d&&d({action:u,location:w.location,delta:1})}function x(C,k){u=_n.Replace;let j=Iu(w.location,C,k);f=h();let M=tC(j,f),_=w.createHref(j);l.replaceState(M,"",_),o&&d&&d({action:u,location:w.location,delta:0})}function b(C){let k=s.location.origin!=="null"?s.location.origin:s.location.href,j=typeof C=="string"?C:wi(C);return j=j.replace(/ $/,"%20"),Ct(k,"No window.location.(origin|href) available to create URL for href: "+j),new URL(j,k)}let w={get action(){return u},get location(){return e(s,l)},listen(C){if(d)throw new Error("A history only accepts one active listener");return s.addEventListener(eC,m),d=C,()=>{s.removeEventListener(eC,m),d=null}},createHref(C){return t(s,C)},createURL:b,encodeLocation(C){let k=b(C);return{pathname:k.pathname,search:k.search,hash:k.hash}},push:g,replace:x,go(C){return l.go(C)}};return w}var Zt;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Zt||(Zt={}));const DF=new Set(["lazy","caseSensitive","path","id","index","children"]);function FF(e){return e.index===!0}function Au(e,t,n,r){return n===void 0&&(n=[]),r===void 0&&(r={}),e.map((s,o)=>{let l=[...n,String(o)],u=typeof s.id=="string"?s.id:l.join("-");if(Ct(s.index!==!0||!s.children,"Cannot specify children on an index route"),Ct(!r[u],'Found a route id collision on id "'+u+`". Route id's must be globally unique within Data Router usages`),FF(s)){let d=mn({},s,t(s),{id:u});return r[u]=d,d}else{let d=mn({},s,t(s),{id:u,children:void 0});return r[u]=d,s.children&&(d.children=Au(s.children,t,l,r)),d}})}function oi(e,t,n){return n===void 0&&(n="/"),cp(e,t,n,!1)}function cp(e,t,n,r){let s=typeof t=="string"?_a(t):t,o=Xl(s.pathname||"/",n);if(o==null)return null;let l=aj(e);$F(l);let u=null;for(let d=0;u==null&&d{let d={relativePath:u===void 0?o.path||"":u,caseSensitive:o.caseSensitive===!0,childrenIndex:l,route:o};d.relativePath.startsWith("/")&&(Ct(d.relativePath.startsWith(r),'Absolute route path "'+d.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),d.relativePath=d.relativePath.slice(r.length));let f=To([r,d.relativePath]),h=n.concat(d);o.children&&o.children.length>0&&(Ct(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+f+'".')),aj(o.children,t,h,f)),!(o.path==null&&!o.index)&&t.push({path:f,score:KF(f,o.index),routesMeta:h})};return e.forEach((o,l)=>{var u;if(o.path===""||!((u=o.path)!=null&&u.includes("?")))s(o,l);else for(let d of ij(o.path))s(o,l,d)}),t}function ij(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return s?[o,""]:[o];let l=ij(r.join("/")),u=[];return u.push(...l.map(d=>d===""?o:[o,d].join("/"))),s&&u.push(...l),u.map(d=>e.startsWith("/")&&d===""?"/":d)}function $F(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:WF(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const BF=/^:[\w-]+$/,zF=3,UF=2,VF=1,HF=10,qF=-2,nC=e=>e==="*";function KF(e,t){let n=e.split("/"),r=n.length;return n.some(nC)&&(r+=qF),t&&(r+=UF),n.filter(s=>!nC(s)).reduce((s,o)=>s+(BF.test(o)?zF:o===""?VF:HF),r)}function WF(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function GF(e,t,n){n===void 0&&(n=!1);let{routesMeta:r}=e,s={},o="/",l=[];for(let u=0;u{let{paramName:g,isOptional:x}=h;if(g==="*"){let w=u[m]||"";l=o.slice(0,o.length-w.length).replace(/(.)\/+$/,"$1")}const b=u[m];return x&&!b?f[g]=void 0:f[g]=(b||"").replace(/%2F/g,"/"),f},{}),pathname:o,pathnameBase:l,pattern:e}}function JF(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Ll(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,d)=>(r.push({paramName:u,isOptional:d!=null}),d?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function QF(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ll(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Xl(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function ZF(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?_a(e):e;return{pathname:n?n.startsWith("/")?n:YF(n,t):t,search:e2(r),hash:t2(s)}}function YF(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function fv(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function lj(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function hh(e,t){let n=lj(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function gh(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=_a(e):(s=mn({},e),Ct(!s.pathname||!s.pathname.includes("?"),fv("?","pathname","search",s)),Ct(!s.pathname||!s.pathname.includes("#"),fv("#","pathname","hash",s)),Ct(!s.search||!s.search.includes("#"),fv("#","search","hash",s)));let o=e===""||s.pathname==="",l=o?"/":s.pathname,u;if(l==null)u=n;else{let m=t.length-1;if(!r&&l.startsWith("..")){let g=l.split("/");for(;g[0]==="..";)g.shift(),m-=1;s.pathname=g.join("/")}u=m>=0?t[m]:"/"}let d=ZF(s,u),f=l&&l!=="/"&&l.endsWith("/"),h=(o||l===".")&&n.endsWith("/");return!d.pathname.endsWith("/")&&(f||h)&&(d.pathname+="/"),d}const To=e=>e.join("/").replace(/\/\/+/g,"/"),XF=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),e2=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,t2=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;class Ab{constructor(t,n,r,s){s===void 0&&(s=!1),this.status=t,this.statusText=n||"",this.internal=s,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function mh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const cj=["post","put","patch","delete"],n2=new Set(cj),r2=["get",...cj],s2=new Set(r2),o2=new Set([301,302,303,307,308]),a2=new Set([307,308]),pv={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},i2={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},eu={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},Db=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,l2=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),uj="remix-router-transitions";function c2(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u",r=!n;Ct(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let s;if(e.mapRouteProperties)s=e.mapRouteProperties;else if(e.detectErrorBoundary){let B=e.detectErrorBoundary;s=K=>({hasErrorBoundary:B(K)})}else s=l2;let o={},l=Au(e.routes,s,void 0,o),u,d=e.basename||"/",f=e.unstable_dataStrategy||h2,h=e.unstable_patchRoutesOnMiss,m=mn({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1,v7_skipActionErrorRevalidation:!1},e.future),g=null,x=new Set,b=null,w=null,C=null,k=e.hydrationData!=null,j=oi(l,e.history.location,d),M=null;if(j==null&&!h){let B=lr(404,{pathname:e.history.location.pathname}),{matches:K,route:oe}=pC(l);j=K,M={[oe.id]:B}}j&&h&&!e.hydrationData&&Ba(j,l,e.history.location.pathname).active&&(j=null);let _;if(!j)_=!1,j=[];else if(j.some(B=>B.route.lazy))_=!1;else if(!j.some(B=>B.route.loader))_=!0;else if(m.v7_partialHydration){let B=e.hydrationData?e.hydrationData.loaderData:null,K=e.hydrationData?e.hydrationData.errors:null,oe=ve=>ve.route.loader?typeof ve.route.loader=="function"&&ve.route.loader.hydrate===!0?!1:B&&B[ve.route.id]!==void 0||K&&K[ve.route.id]!==void 0:!0;if(K){let ve=j.findIndex(Oe=>K[Oe.route.id]!==void 0);_=j.slice(0,ve+1).every(oe)}else _=j.every(oe)}else _=e.hydrationData!=null;let R,N={historyAction:e.history.action,location:e.history.location,matches:j,initialized:_,navigation:pv,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||M,fetchers:new Map,blockers:new Map},O=_n.Pop,D=!1,z,Q=!1,pe=new Map,V=null,G=!1,W=!1,ie=[],re=[],Y=new Map,H=0,q=-1,he=new Map,A=new Set,F=new Map,fe=new Map,te=new Set,de=new Map,ge=new Map,Z=new Map,ye=!1;function Re(){if(g=e.history.listen(B=>{let{action:K,location:oe,delta:ve}=B;if(ye){ye=!1;return}Ll(ge.size===0||ve!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let Oe=Gr({currentLocation:N.location,nextLocation:oe,historyAction:K});if(Oe&&ve!=null){ye=!0,e.history.go(ve*-1),vr(Oe,{state:"blocked",location:oe,proceed(){vr(Oe,{state:"proceeding",proceed:void 0,reset:void 0,location:oe}),e.history.go(ve)},reset(){let We=new Map(N.blockers);We.set(Oe,eu),Fe({blockers:We})}});return}return vn(K,oe)}),n){T2(t,pe);let B=()=>N2(t,pe);t.addEventListener("pagehide",B),V=()=>t.removeEventListener("pagehide",B)}return N.initialized||vn(_n.Pop,N.location,{initialHydration:!0}),R}function $e(){g&&g(),V&&V(),x.clear(),z&&z.abort(),N.fetchers.forEach((B,K)=>Qn(K)),N.blockers.forEach((B,K)=>mr(K))}function Ye(B){return x.add(B),()=>x.delete(B)}function Fe(B,K){K===void 0&&(K={}),N=mn({},N,B);let oe=[],ve=[];m.v7_fetcherPersist&&N.fetchers.forEach((Oe,We)=>{Oe.state==="idle"&&(te.has(We)?ve.push(We):oe.push(We))}),[...x].forEach(Oe=>Oe(N,{deletedFetchers:ve,unstable_viewTransitionOpts:K.viewTransitionOpts,unstable_flushSync:K.flushSync===!0})),m.v7_fetcherPersist&&(oe.forEach(Oe=>N.fetchers.delete(Oe)),ve.forEach(Oe=>Qn(Oe)))}function ft(B,K,oe){var ve,Oe;let{flushSync:We}=oe===void 0?{}:oe,st=N.actionData!=null&&N.navigation.formMethod!=null&&bs(N.navigation.formMethod)&&N.navigation.state==="loading"&&((ve=B.state)==null?void 0:ve._isRedirect)!==!0,Me;K.actionData?Object.keys(K.actionData).length>0?Me=K.actionData:Me=null:st?Me=N.actionData:Me=null;let ht=K.loaderData?dC(N.loaderData,K.loaderData,K.matches||[],K.errors):N.loaderData,Ge=N.blockers;Ge.size>0&&(Ge=new Map(Ge),Ge.forEach((Vt,Ht)=>Ge.set(Ht,eu)));let Xe=D===!0||N.navigation.formMethod!=null&&bs(N.navigation.formMethod)&&((Oe=B.state)==null?void 0:Oe._isRedirect)!==!0;u&&(l=u,u=void 0),G||O===_n.Pop||(O===_n.Push?e.history.push(B,B.state):O===_n.Replace&&e.history.replace(B,B.state));let Ut;if(O===_n.Pop){let Vt=pe.get(N.location.pathname);Vt&&Vt.has(B.pathname)?Ut={currentLocation:N.location,nextLocation:B}:pe.has(B.pathname)&&(Ut={currentLocation:B,nextLocation:N.location})}else if(Q){let Vt=pe.get(N.location.pathname);Vt?Vt.add(B.pathname):(Vt=new Set([B.pathname]),pe.set(N.location.pathname,Vt)),Ut={currentLocation:N.location,nextLocation:B}}Fe(mn({},K,{actionData:Me,loaderData:ht,historyAction:O,location:B,initialized:!0,navigation:pv,revalidation:"idle",restoreScrollPosition:yc(B,K.matches||N.matches),preventScrollReset:Xe,blockers:Ge}),{viewTransitionOpts:Ut,flushSync:We===!0}),O=_n.Pop,D=!1,Q=!1,G=!1,W=!1,ie=[],re=[]}async function ln(B,K){if(typeof B=="number"){e.history.go(B);return}let oe=Ny(N.location,N.matches,d,m.v7_prependBasename,B,m.v7_relativeSplatPath,K?.fromRouteId,K?.relative),{path:ve,submission:Oe,error:We}=sC(m.v7_normalizeFormMethod,!1,oe,K),st=N.location,Me=Iu(N.location,ve,K&&K.state);Me=mn({},Me,e.history.encodeLocation(Me));let ht=K&&K.replace!=null?K.replace:void 0,Ge=_n.Push;ht===!0?Ge=_n.Replace:ht===!1||Oe!=null&&bs(Oe.formMethod)&&Oe.formAction===N.location.pathname+N.location.search&&(Ge=_n.Replace);let Xe=K&&"preventScrollReset"in K?K.preventScrollReset===!0:void 0,Ut=(K&&K.unstable_flushSync)===!0,Vt=Gr({currentLocation:st,nextLocation:Me,historyAction:Ge});if(Vt){vr(Vt,{state:"blocked",location:Me,proceed(){vr(Vt,{state:"proceeding",proceed:void 0,reset:void 0,location:Me}),ln(B,K)},reset(){let Ht=new Map(N.blockers);Ht.set(Vt,eu),Fe({blockers:Ht})}});return}return await vn(Ge,Me,{submission:Oe,pendingError:We,preventScrollReset:Xe,replace:K&&K.replace,enableViewTransition:K&&K.unstable_viewTransition,flushSync:Ut})}function Sn(){if(yn(),Fe({revalidation:"loading"}),N.navigation.state!=="submitting"){if(N.navigation.state==="idle"){vn(N.historyAction,N.location,{startUninterruptedRevalidation:!0});return}vn(O||N.historyAction,N.navigation.location,{overrideNavigation:N.navigation})}}async function vn(B,K,oe){z&&z.abort(),z=null,O=B,G=(oe&&oe.startUninterruptedRevalidation)===!0,_d(N.location,N.matches),D=(oe&&oe.preventScrollReset)===!0,Q=(oe&&oe.enableViewTransition)===!0;let ve=u||l,Oe=oe&&oe.overrideNavigation,We=oi(ve,K,d),st=(oe&&oe.flushSync)===!0,Me=Ba(We,ve,K.pathname);if(Me.active&&Me.matches&&(We=Me.matches),!We){let{error:At,notFoundMatches:Nn,route:fn}=Jr(K.pathname);ft(K,{matches:Nn,loaderData:{},errors:{[fn.id]:At}},{flushSync:st});return}if(N.initialized&&!W&&x2(N.location,K)&&!(oe&&oe.submission&&bs(oe.submission.formMethod))){ft(K,{matches:We},{flushSync:st});return}z=new AbortController;let ht=fl(e.history,K,z.signal,oe&&oe.submission),Ge;if(oe&&oe.pendingError)Ge=[jl(We).route.id,{type:Zt.error,error:oe.pendingError}];else if(oe&&oe.submission&&bs(oe.submission.formMethod)){let At=await Cn(ht,K,oe.submission,We,Me.active,{replace:oe.replace,flushSync:st});if(At.shortCircuited)return;if(At.pendingActionResult){let[Nn,fn]=At.pendingActionResult;if(Br(fn)&&mh(fn.error)&&fn.error.status===404){z=null,ft(K,{matches:At.matches,loaderData:{},errors:{[Nn]:fn.error}});return}}We=At.matches||We,Ge=At.pendingActionResult,Oe=hv(K,oe.submission),st=!1,Me.active=!1,ht=fl(e.history,ht.url,ht.signal)}let{shortCircuited:Xe,matches:Ut,loaderData:Vt,errors:Ht}=await L(ht,K,We,Me.active,Oe,oe&&oe.submission,oe&&oe.fetcherSubmission,oe&&oe.replace,oe&&oe.initialHydration===!0,st,Ge);Xe||(z=null,ft(K,mn({matches:Ut||We},fC(Ge),{loaderData:Vt,errors:Ht})))}async function Cn(B,K,oe,ve,Oe,We){We===void 0&&(We={}),yn();let st=k2(K,oe);if(Fe({navigation:st},{flushSync:We.flushSync===!0}),Oe){let Ge=await za(ve,K.pathname,B.signal);if(Ge.type==="aborted")return{shortCircuited:!0};if(Ge.type==="error"){let{boundaryId:Xe,error:Ut}=_r(K.pathname,Ge);return{matches:Ge.partialMatches,pendingActionResult:[Xe,{type:Zt.error,error:Ut}]}}else if(Ge.matches)ve=Ge.matches;else{let{notFoundMatches:Xe,error:Ut,route:Vt}=Jr(K.pathname);return{matches:Xe,pendingActionResult:[Vt.id,{type:Zt.error,error:Ut}]}}}let Me,ht=gu(ve,K);if(!ht.route.action&&!ht.route.lazy)Me={type:Zt.error,error:lr(405,{method:B.method,pathname:K.pathname,routeId:ht.route.id})};else if(Me=(await bt("action",B,[ht],ve))[0],B.signal.aborted)return{shortCircuited:!0};if(ii(Me)){let Ge;return We&&We.replace!=null?Ge=We.replace:Ge=lC(Me.response.headers.get("Location"),new URL(B.url),d)===N.location.pathname+N.location.search,await Be(B,Me,{submission:oe,replace:Ge}),{shortCircuited:!0}}if(ai(Me))throw lr(400,{type:"defer-action"});if(Br(Me)){let Ge=jl(ve,ht.route.id);return(We&&We.replace)!==!0&&(O=_n.Push),{matches:ve,pendingActionResult:[Ge.route.id,Me]}}return{matches:ve,pendingActionResult:[ht.route.id,Me]}}async function L(B,K,oe,ve,Oe,We,st,Me,ht,Ge,Xe){let Ut=Oe||hv(K,We),Vt=We||st||mC(Ut),Ht=!G&&(!m.v7_partialHydration||!ht);if(ve){if(Ht){let Dt=X(Xe);Fe(mn({navigation:Ut},Dt!==void 0?{actionData:Dt}:{}),{flushSync:Ge})}let pt=await za(oe,K.pathname,B.signal);if(pt.type==="aborted")return{shortCircuited:!0};if(pt.type==="error"){let{boundaryId:Dt,error:or}=_r(K.pathname,pt);return{matches:pt.partialMatches,loaderData:{},errors:{[Dt]:or}}}else if(pt.matches)oe=pt.matches;else{let{error:Dt,notFoundMatches:or,route:Tt}=Jr(K.pathname);return{matches:or,loaderData:{},errors:{[Tt.id]:Dt}}}}let At=u||l,[Nn,fn]=oC(e.history,N,oe,Vt,K,m.v7_partialHydration&&ht===!0,m.v7_skipActionErrorRevalidation,W,ie,re,te,F,A,At,d,Xe);if(Rr(pt=>!(oe&&oe.some(Dt=>Dt.route.id===pt))||Nn&&Nn.some(Dt=>Dt.route.id===pt)),q=++H,Nn.length===0&&fn.length===0){let pt=ut();return ft(K,mn({matches:oe,loaderData:{},errors:Xe&&Br(Xe[1])?{[Xe[0]]:Xe[1].error}:null},fC(Xe),pt?{fetchers:new Map(N.fetchers)}:{}),{flushSync:Ge}),{shortCircuited:!0}}if(Ht){let pt={};if(!ve){pt.navigation=Ut;let Dt=X(Xe);Dt!==void 0&&(pt.actionData=Dt)}fn.length>0&&(pt.fetchers=ue(fn)),Fe(pt,{flushSync:Ge})}fn.forEach(pt=>{Y.has(pt.key)&&Bn(pt.key),pt.controller&&Y.set(pt.key,pt.controller)});let Va=()=>fn.forEach(pt=>Bn(pt.key));z&&z.signal.addEventListener("abort",Va);let{loaderResults:Os,fetcherResults:Gt}=await Wt(N.matches,oe,Nn,fn,B);if(B.signal.aborted)return{shortCircuited:!0};z&&z.signal.removeEventListener("abort",Va),fn.forEach(pt=>Y.delete(pt.key));let Vo=hC([...Os,...Gt]);if(Vo){if(Vo.idx>=Nn.length){let pt=fn[Vo.idx-Nn.length].key;A.add(pt)}return await Be(B,Vo.result,{replace:Me}),{shortCircuited:!0}}let{loaderData:Is,errors:Pr}=uC(N,oe,Nn,Os,Xe,fn,Gt,de);de.forEach((pt,Dt)=>{pt.subscribe(or=>{(or||pt.done)&&de.delete(Dt)})}),m.v7_partialHydration&&ht&&N.errors&&Object.entries(N.errors).filter(pt=>{let[Dt]=pt;return!Nn.some(or=>or.route.id===Dt)}).forEach(pt=>{let[Dt,or]=pt;Pr=Object.assign(Pr||{},{[Dt]:or})});let so=ut(),Vi=It(q),Ha=so||Vi||fn.length>0;return mn({matches:oe,loaderData:Is,errors:Pr},Ha?{fetchers:new Map(N.fetchers)}:{})}function X(B){if(B&&!Br(B[1]))return{[B[0]]:B[1].data};if(N.actionData)return Object.keys(N.actionData).length===0?null:N.actionData}function ue(B){return B.forEach(K=>{let oe=N.fetchers.get(K.key),ve=tu(void 0,oe?oe.data:void 0);N.fetchers.set(K.key,ve)}),new Map(N.fetchers)}function Ne(B,K,oe,ve){if(r)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");Y.has(B)&&Bn(B);let Oe=(ve&&ve.unstable_flushSync)===!0,We=u||l,st=Ny(N.location,N.matches,d,m.v7_prependBasename,oe,m.v7_relativeSplatPath,K,ve?.relative),Me=oi(We,st,d),ht=Ba(Me,We,st);if(ht.active&&ht.matches&&(Me=ht.matches),!Me){En(B,K,lr(404,{pathname:st}),{flushSync:Oe});return}let{path:Ge,submission:Xe,error:Ut}=sC(m.v7_normalizeFormMethod,!0,st,ve);if(Ut){En(B,K,Ut,{flushSync:Oe});return}let Vt=gu(Me,Ge);if(D=(ve&&ve.preventScrollReset)===!0,Xe&&bs(Xe.formMethod)){je(B,K,Ge,Vt,Me,ht.active,Oe,Xe);return}F.set(B,{routeId:K,path:Ge}),Se(B,K,Ge,Vt,Me,ht.active,Oe,Xe)}async function je(B,K,oe,ve,Oe,We,st,Me){yn(),F.delete(B);function ht(Tt){if(!Tt.route.action&&!Tt.route.lazy){let fs=lr(405,{method:Me.formMethod,pathname:oe,routeId:K});return En(B,K,fs,{flushSync:st}),!0}return!1}if(!We&&ht(ve))return;let Ge=N.fetchers.get(B);bn(B,j2(Me,Ge),{flushSync:st});let Xe=new AbortController,Ut=fl(e.history,oe,Xe.signal,Me);if(We){let Tt=await za(Oe,oe,Ut.signal);if(Tt.type==="aborted")return;if(Tt.type==="error"){let{error:fs}=_r(oe,Tt);En(B,K,fs,{flushSync:st});return}else if(Tt.matches){if(Oe=Tt.matches,ve=gu(Oe,oe),ht(ve))return}else{En(B,K,lr(404,{pathname:oe}),{flushSync:st});return}}Y.set(B,Xe);let Vt=H,At=(await bt("action",Ut,[ve],Oe))[0];if(Ut.signal.aborted){Y.get(B)===Xe&&Y.delete(B);return}if(m.v7_fetcherPersist&&te.has(B)){if(ii(At)||Br(At)){bn(B,da(void 0));return}}else{if(ii(At))if(Y.delete(B),q>Vt){bn(B,da(void 0));return}else return A.add(B),bn(B,tu(Me)),Be(Ut,At,{fetcherSubmission:Me});if(Br(At)){En(B,K,At.error);return}}if(ai(At))throw lr(400,{type:"defer-action"});let Nn=N.navigation.location||N.location,fn=fl(e.history,Nn,Xe.signal),Va=u||l,Os=N.navigation.state!=="idle"?oi(Va,N.navigation.location,d):N.matches;Ct(Os,"Didn't find any matches after fetcher action");let Gt=++H;he.set(B,Gt);let Vo=tu(Me,At.data);N.fetchers.set(B,Vo);let[Is,Pr]=oC(e.history,N,Os,Me,Nn,!1,m.v7_skipActionErrorRevalidation,W,ie,re,te,F,A,Va,d,[ve.route.id,At]);Pr.filter(Tt=>Tt.key!==B).forEach(Tt=>{let fs=Tt.key,Rd=N.fetchers.get(fs),jg=tu(void 0,Rd?Rd.data:void 0);N.fetchers.set(fs,jg),Y.has(fs)&&Bn(fs),Tt.controller&&Y.set(fs,Tt.controller)}),Fe({fetchers:new Map(N.fetchers)});let so=()=>Pr.forEach(Tt=>Bn(Tt.key));Xe.signal.addEventListener("abort",so);let{loaderResults:Vi,fetcherResults:Ha}=await Wt(N.matches,Os,Is,Pr,fn);if(Xe.signal.aborted)return;Xe.signal.removeEventListener("abort",so),he.delete(B),Y.delete(B),Pr.forEach(Tt=>Y.delete(Tt.key));let pt=hC([...Vi,...Ha]);if(pt){if(pt.idx>=Is.length){let Tt=Pr[pt.idx-Is.length].key;A.add(Tt)}return Be(fn,pt.result)}let{loaderData:Dt,errors:or}=uC(N,N.matches,Is,Vi,void 0,Pr,Ha,de);if(N.fetchers.has(B)){let Tt=da(At.data);N.fetchers.set(B,Tt)}It(Gt),N.navigation.state==="loading"&&Gt>q?(Ct(O,"Expected pending action"),z&&z.abort(),ft(N.navigation.location,{matches:Os,loaderData:Dt,errors:or,fetchers:new Map(N.fetchers)})):(Fe({errors:or,loaderData:dC(N.loaderData,Dt,Os,or),fetchers:new Map(N.fetchers)}),W=!1)}async function Se(B,K,oe,ve,Oe,We,st,Me){let ht=N.fetchers.get(B);bn(B,tu(Me,ht?ht.data:void 0),{flushSync:st});let Ge=new AbortController,Xe=fl(e.history,oe,Ge.signal);if(We){let At=await za(Oe,oe,Xe.signal);if(At.type==="aborted")return;if(At.type==="error"){let{error:Nn}=_r(oe,At);En(B,K,Nn,{flushSync:st});return}else if(At.matches)Oe=At.matches,ve=gu(Oe,oe);else{En(B,K,lr(404,{pathname:oe}),{flushSync:st});return}}Y.set(B,Ge);let Ut=H,Ht=(await bt("loader",Xe,[ve],Oe))[0];if(ai(Ht)&&(Ht=await gj(Ht,Xe.signal,!0)||Ht),Y.get(B)===Ge&&Y.delete(B),!Xe.signal.aborted){if(te.has(B)){bn(B,da(void 0));return}if(ii(Ht))if(q>Ut){bn(B,da(void 0));return}else{A.add(B),await Be(Xe,Ht);return}if(Br(Ht)){En(B,K,Ht.error);return}Ct(!ai(Ht),"Unhandled fetcher deferred data"),bn(B,da(Ht.data))}}async function Be(B,K,oe){let{submission:ve,fetcherSubmission:Oe,replace:We}=oe===void 0?{}:oe;K.response.headers.has("X-Remix-Revalidate")&&(W=!0);let st=K.response.headers.get("Location");Ct(st,"Expected a Location header on the redirect Response"),st=lC(st,new URL(B.url),d);let Me=Iu(N.location,st,{_isRedirect:!0});if(n){let Ht=!1;if(K.response.headers.has("X-Remix-Reload-Document"))Ht=!0;else if(Db.test(st)){const At=e.history.createURL(st);Ht=At.origin!==t.location.origin||Xl(At.pathname,d)==null}if(Ht){We?t.location.replace(st):t.location.assign(st);return}}z=null;let ht=We===!0?_n.Replace:_n.Push,{formMethod:Ge,formAction:Xe,formEncType:Ut}=N.navigation;!ve&&!Oe&&Ge&&Xe&&Ut&&(ve=mC(N.navigation));let Vt=ve||Oe;if(a2.has(K.response.status)&&Vt&&bs(Vt.formMethod))await vn(ht,Me,{submission:mn({},Vt,{formAction:st}),preventScrollReset:D});else{let Ht=hv(Me,ve);await vn(ht,Me,{overrideNavigation:Ht,fetcherSubmission:Oe,preventScrollReset:D})}}async function bt(B,K,oe,ve){try{let Oe=await g2(f,B,K,oe,ve,o,s);return await Promise.all(Oe.map((We,st)=>{if(S2(We)){let Me=We.result;return{type:Zt.redirect,response:y2(Me,K,oe[st].route.id,ve,d,m.v7_relativeSplatPath)}}return v2(We)}))}catch(Oe){return oe.map(()=>({type:Zt.error,error:Oe}))}}async function Wt(B,K,oe,ve,Oe){let[We,...st]=await Promise.all([oe.length?bt("loader",Oe,oe,K):[],...ve.map(Me=>{if(Me.matches&&Me.match&&Me.controller){let ht=fl(e.history,Me.path,Me.controller.signal);return bt("loader",ht,[Me.match],Me.matches).then(Ge=>Ge[0])}else return Promise.resolve({type:Zt.error,error:lr(404,{pathname:Me.path})})})]);return await Promise.all([gC(B,oe,We,We.map(()=>Oe.signal),!1,N.loaderData),gC(B,ve.map(Me=>Me.match),st,ve.map(Me=>Me.controller?Me.controller.signal:null),!0)]),{loaderResults:We,fetcherResults:st}}function yn(){W=!0,ie.push(...Rr()),F.forEach((B,K)=>{Y.has(K)&&(re.push(K),Bn(K))})}function bn(B,K,oe){oe===void 0&&(oe={}),N.fetchers.set(B,K),Fe({fetchers:new Map(N.fetchers)},{flushSync:(oe&&oe.flushSync)===!0})}function En(B,K,oe,ve){ve===void 0&&(ve={});let Oe=jl(N.matches,K);Qn(B),Fe({errors:{[Oe.route.id]:oe},fetchers:new Map(N.fetchers)},{flushSync:(ve&&ve.flushSync)===!0})}function gr(B){return m.v7_fetcherPersist&&(fe.set(B,(fe.get(B)||0)+1),te.has(B)&&te.delete(B)),N.fetchers.get(B)||i2}function Qn(B){let K=N.fetchers.get(B);Y.has(B)&&!(K&&K.state==="loading"&&he.has(B))&&Bn(B),F.delete(B),he.delete(B),A.delete(B),te.delete(B),N.fetchers.delete(B)}function ro(B){if(m.v7_fetcherPersist){let K=(fe.get(B)||0)-1;K<=0?(fe.delete(B),te.add(B)):fe.set(B,K)}else Qn(B);Fe({fetchers:new Map(N.fetchers)})}function Bn(B){let K=Y.get(B);Ct(K,"Expected fetch controller: "+B),K.abort(),Y.delete(B)}function Te(B){for(let K of B){let oe=gr(K),ve=da(oe.data);N.fetchers.set(K,ve)}}function ut(){let B=[],K=!1;for(let oe of A){let ve=N.fetchers.get(oe);Ct(ve,"Expected fetcher: "+oe),ve.state==="loading"&&(A.delete(oe),B.push(oe),K=!0)}return Te(B),K}function It(B){let K=[];for(let[oe,ve]of he)if(ve0}function Tn(B,K){let oe=N.blockers.get(B)||eu;return ge.get(B)!==K&&ge.set(B,K),oe}function mr(B){N.blockers.delete(B),ge.delete(B)}function vr(B,K){let oe=N.blockers.get(B)||eu;Ct(oe.state==="unblocked"&&K.state==="blocked"||oe.state==="blocked"&&K.state==="blocked"||oe.state==="blocked"&&K.state==="proceeding"||oe.state==="blocked"&&K.state==="unblocked"||oe.state==="proceeding"&&K.state==="unblocked","Invalid blocker state transition: "+oe.state+" -> "+K.state);let ve=new Map(N.blockers);ve.set(B,K),Fe({blockers:ve})}function Gr(B){let{currentLocation:K,nextLocation:oe,historyAction:ve}=B;if(ge.size===0)return;ge.size>1&&Ll(!1,"A router only supports one blocker at a time");let Oe=Array.from(ge.entries()),[We,st]=Oe[Oe.length-1],Me=N.blockers.get(We);if(!(Me&&Me.state==="proceeding")&&st({currentLocation:K,nextLocation:oe,historyAction:ve}))return We}function Jr(B){let K=lr(404,{pathname:B}),oe=u||l,{matches:ve,route:Oe}=pC(oe);return Rr(),{notFoundMatches:ve,route:Oe,error:K}}function _r(B,K){return{boundaryId:jl(K.partialMatches).route.id,error:lr(400,{type:"route-discovery",pathname:B,message:K.error!=null&&"message"in K.error?K.error:String(K.error)})}}function Rr(B){let K=[];return de.forEach((oe,ve)=>{(!B||B(ve))&&(oe.cancel(),K.push(ve),de.delete(ve))}),K}function Uo(B,K,oe){if(b=B,C=K,w=oe||null,!k&&N.navigation===pv){k=!0;let ve=yc(N.location,N.matches);ve!=null&&Fe({restoreScrollPosition:ve})}return()=>{b=null,C=null,w=null}}function vc(B,K){return w&&w(B,K.map(ve=>LF(ve,N.loaderData)))||B.key}function _d(B,K){if(b&&C){let oe=vc(B,K);b[oe]=C()}}function yc(B,K){if(b){let oe=vc(B,K),ve=b[oe];if(typeof ve=="number")return ve}return null}function Ba(B,K,oe){if(h)if(B){let ve=B[B.length-1].route;if(ve.path&&(ve.path==="*"||ve.path.endsWith("/*")))return{active:!0,matches:cp(K,oe,d,!0)}}else return{active:!0,matches:cp(K,oe,d,!0)||[]};return{active:!1,matches:null}}async function za(B,K,oe){let ve=B,Oe=ve.length>0?ve[ve.length-1].route:null;for(;;){let We=u==null,st=u||l;try{await p2(h,K,ve,st,o,s,Z,oe)}catch(Xe){return{type:"error",error:Xe,partialMatches:ve}}finally{We&&(l=[...l])}if(oe.aborted)return{type:"aborted"};let Me=oi(st,K,d),ht=!1;if(Me){let Xe=Me[Me.length-1].route;if(Xe.index)return{type:"success",matches:Me};if(Xe.path&&Xe.path.length>0)if(Xe.path==="*")ht=!0;else return{type:"success",matches:Me}}let Ge=cp(st,K,d,!0);if(!Ge||ve.map(Xe=>Xe.route.id).join("-")===Ge.map(Xe=>Xe.route.id).join("-"))return{type:"success",matches:ht?Me:null};if(ve=Ge,Oe=ve[ve.length-1].route,Oe.path==="*")return{type:"success",matches:ve}}}function Ua(B){o={},u=Au(B,s,void 0,o)}function bc(B,K){let oe=u==null;fj(B,K,u||l,o,s),oe&&(l=[...l],Fe({}))}return R={get basename(){return d},get future(){return m},get state(){return N},get routes(){return l},get window(){return t},initialize:Re,subscribe:Ye,enableScrollRestoration:Uo,navigate:ln,fetch:Ne,revalidate:Sn,createHref:B=>e.history.createHref(B),encodeLocation:B=>e.history.encodeLocation(B),getFetcher:gr,deleteFetcher:ro,dispose:$e,getBlocker:Tn,deleteBlocker:mr,patchRoutes:bc,_internalFetchControllers:Y,_internalActiveDeferreds:de,_internalSetRoutes:Ua},R}function u2(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Ny(e,t,n,r,s,o,l,u){let d,f;if(l){d=[];for(let m of t)if(d.push(m),m.route.id===l){f=m;break}}else d=t,f=t[t.length-1];let h=gh(s||".",hh(d,o),Xl(e.pathname,n)||e.pathname,u==="path");return s==null&&(h.search=e.search,h.hash=e.hash),(s==null||s===""||s===".")&&f&&f.route.index&&!Fb(h.search)&&(h.search=h.search?h.search.replace(/^\?/,"?index&"):"?index"),r&&n!=="/"&&(h.pathname=h.pathname==="/"?n:To([n,h.pathname])),wi(h)}function sC(e,t,n,r){if(!r||!u2(r))return{path:n};if(r.formMethod&&!E2(r.formMethod))return{path:n,error:lr(405,{method:r.formMethod})};let s=()=>({path:n,error:lr(400,{type:"invalid-body"})}),o=r.formMethod||"get",l=e?o.toUpperCase():o.toLowerCase(),u=pj(n);if(r.body!==void 0){if(r.formEncType==="text/plain"){if(!bs(l))return s();let g=typeof r.body=="string"?r.body:r.body instanceof FormData||r.body instanceof URLSearchParams?Array.from(r.body.entries()).reduce((x,b)=>{let[w,C]=b;return""+x+w+"="+C+` +`},""):String(r.body);return{path:n,submission:{formMethod:l,formAction:u,formEncType:r.formEncType,formData:void 0,json:void 0,text:g}}}else if(r.formEncType==="application/json"){if(!bs(l))return s();try{let g=typeof r.body=="string"?JSON.parse(r.body):r.body;return{path:n,submission:{formMethod:l,formAction:u,formEncType:r.formEncType,formData:void 0,json:g,text:void 0}}}catch{return s()}}}Ct(typeof FormData=="function","FormData is not available in this environment");let d,f;if(r.formData)d=My(r.formData),f=r.formData;else if(r.body instanceof FormData)d=My(r.body),f=r.body;else if(r.body instanceof URLSearchParams)d=r.body,f=cC(d);else if(r.body==null)d=new URLSearchParams,f=new FormData;else try{d=new URLSearchParams(r.body),f=cC(d)}catch{return s()}let h={formMethod:l,formAction:u,formEncType:r&&r.formEncType||"application/x-www-form-urlencoded",formData:f,json:void 0,text:void 0};if(bs(h.formMethod))return{path:n,submission:h};let m=_a(n);return t&&m.search&&Fb(m.search)&&d.append("index",""),m.search="?"+d,{path:wi(m),submission:h}}function d2(e,t){let n=e;if(t){let r=e.findIndex(s=>s.route.id===t);r>=0&&(n=e.slice(0,r))}return n}function oC(e,t,n,r,s,o,l,u,d,f,h,m,g,x,b,w){let C=w?Br(w[1])?w[1].error:w[1].data:void 0,k=e.createURL(t.location),j=e.createURL(s),M=w&&Br(w[1])?w[0]:void 0,_=M?d2(n,M):n,R=w?w[1].statusCode:void 0,N=l&&R&&R>=400,O=_.filter((z,Q)=>{let{route:pe}=z;if(pe.lazy)return!0;if(pe.loader==null)return!1;if(o)return typeof pe.loader!="function"||pe.loader.hydrate?!0:t.loaderData[pe.id]===void 0&&(!t.errors||t.errors[pe.id]===void 0);if(f2(t.loaderData,t.matches[Q],z)||d.some(W=>W===z.route.id))return!0;let V=t.matches[Q],G=z;return aC(z,mn({currentUrl:k,currentParams:V.params,nextUrl:j,nextParams:G.params},r,{actionResult:C,actionStatus:R,defaultShouldRevalidate:N?!1:u||k.pathname+k.search===j.pathname+j.search||k.search!==j.search||dj(V,G)}))}),D=[];return m.forEach((z,Q)=>{if(o||!n.some(ie=>ie.route.id===z.routeId)||h.has(Q))return;let pe=oi(x,z.path,b);if(!pe){D.push({key:Q,routeId:z.routeId,path:z.path,matches:null,match:null,controller:null});return}let V=t.fetchers.get(Q),G=gu(pe,z.path),W=!1;g.has(Q)?W=!1:f.includes(Q)?W=!0:V&&V.state!=="idle"&&V.data===void 0?W=u:W=aC(G,mn({currentUrl:k,currentParams:t.matches[t.matches.length-1].params,nextUrl:j,nextParams:n[n.length-1].params},r,{actionResult:C,actionStatus:R,defaultShouldRevalidate:N?!1:u})),W&&D.push({key:Q,routeId:z.routeId,path:z.path,matches:pe,match:G,controller:new AbortController})}),[O,D]}function f2(e,t,n){let r=!t||n.route.id!==t.route.id,s=e[n.route.id]===void 0;return r||s}function dj(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function aC(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}async function p2(e,t,n,r,s,o,l,u){let d=[t,...n.map(f=>f.route.id)].join("-");try{let f=l.get(d);f||(f=e({path:t,matches:n,patch:(h,m)=>{u.aborted||fj(h,m,r,s,o)}}),l.set(d,f)),f&&w2(f)&&await f}finally{l.delete(d)}}function fj(e,t,n,r,s){if(e){var o;let l=r[e];Ct(l,"No route found to patch children into: routeId = "+e);let u=Au(t,s,[e,"patch",String(((o=l.children)==null?void 0:o.length)||"0")],r);l.children?l.children.push(...u):l.children=u}else{let l=Au(t,s,["patch",String(n.length||"0")],r);n.push(...l)}}async function iC(e,t,n){if(!e.lazy)return;let r=await e.lazy();if(!e.lazy)return;let s=n[e.id];Ct(s,"No route found in manifest");let o={};for(let l in r){let d=s[l]!==void 0&&l!=="hasErrorBoundary";Ll(!d,'Route "'+s.id+'" has a static property "'+l+'" defined but its lazy function is also returning a value for this property. '+('The lazy route property "'+l+'" will be ignored.')),!d&&!DF.has(l)&&(o[l]=r[l])}Object.assign(s,o),Object.assign(s,mn({},t(s),{lazy:void 0}))}function h2(e){return Promise.all(e.matches.map(t=>t.resolve()))}async function g2(e,t,n,r,s,o,l,u){let d=r.reduce((m,g)=>m.add(g.route.id),new Set),f=new Set,h=await e({matches:s.map(m=>{let g=d.has(m.route.id);return mn({},m,{shouldLoad:g,resolve:b=>(f.add(m.route.id),g?m2(t,n,m,o,l,b,u):Promise.resolve({type:Zt.data,result:void 0}))})}),request:n,params:s[0].params,context:u});return s.forEach(m=>Ct(f.has(m.route.id),'`match.resolve()` was not called for route id "'+m.route.id+'". You must call `match.resolve()` on every match passed to `dataStrategy` to ensure all routes are properly loaded.')),h.filter((m,g)=>d.has(s[g].route.id))}async function m2(e,t,n,r,s,o,l){let u,d,f=h=>{let m,g=new Promise((w,C)=>m=C);d=()=>m(),t.signal.addEventListener("abort",d);let x=w=>typeof h!="function"?Promise.reject(new Error("You cannot call the handler for a route which defines a boolean "+('"'+e+'" [routeId: '+n.route.id+"]"))):h({request:t,params:n.params,context:l},...w!==void 0?[w]:[]),b;return o?b=o(w=>x(w)):b=(async()=>{try{return{type:"data",result:await x()}}catch(w){return{type:"error",result:w}}})(),Promise.race([b,g])};try{let h=n.route[e];if(n.route.lazy)if(h){let m,[g]=await Promise.all([f(h).catch(x=>{m=x}),iC(n.route,s,r)]);if(m!==void 0)throw m;u=g}else if(await iC(n.route,s,r),h=n.route[e],h)u=await f(h);else if(e==="action"){let m=new URL(t.url),g=m.pathname+m.search;throw lr(405,{method:t.method,pathname:g,routeId:n.route.id})}else return{type:Zt.data,result:void 0};else if(h)u=await f(h);else{let m=new URL(t.url),g=m.pathname+m.search;throw lr(404,{pathname:g})}Ct(u.result!==void 0,"You defined "+(e==="action"?"an action":"a loader")+" for route "+('"'+n.route.id+"\" but didn't return anything from your `"+e+"` ")+"function. Please return a value or `null`.")}catch(h){return{type:Zt.error,result:h}}finally{d&&t.signal.removeEventListener("abort",d)}return u}async function v2(e){let{result:t,type:n,status:r}=e;if(hj(t)){let l;try{let u=t.headers.get("Content-Type");u&&/\bapplication\/json\b/.test(u)?t.body==null?l=null:l=await t.json():l=await t.text()}catch(u){return{type:Zt.error,error:u}}return n===Zt.error?{type:Zt.error,error:new Ab(t.status,t.statusText,l),statusCode:t.status,headers:t.headers}:{type:Zt.data,data:l,statusCode:t.status,headers:t.headers}}if(n===Zt.error)return{type:Zt.error,error:t,statusCode:mh(t)?t.status:r};if(C2(t)){var s,o;return{type:Zt.deferred,deferredData:t,statusCode:(s=t.init)==null?void 0:s.status,headers:((o=t.init)==null?void 0:o.headers)&&new Headers(t.init.headers)}}return{type:Zt.data,data:t,statusCode:r}}function y2(e,t,n,r,s,o){let l=e.headers.get("Location");if(Ct(l,"Redirects returned/thrown from loaders/actions must have a Location header"),!Db.test(l)){let u=r.slice(0,r.findIndex(d=>d.route.id===n)+1);l=Ny(new URL(t.url),u,s,!0,l,o),e.headers.set("Location",l)}return e}function lC(e,t,n){if(Db.test(e)){let r=e,s=r.startsWith("//")?new URL(t.protocol+r):new URL(r),o=Xl(s.pathname,n)!=null;if(s.origin===t.origin&&o)return s.pathname+s.search+s.hash}return e}function fl(e,t,n,r){let s=e.createURL(pj(t)).toString(),o={signal:n};if(r&&bs(r.formMethod)){let{formMethod:l,formEncType:u}=r;o.method=l.toUpperCase(),u==="application/json"?(o.headers=new Headers({"Content-Type":u}),o.body=JSON.stringify(r.json)):u==="text/plain"?o.body=r.text:u==="application/x-www-form-urlencoded"&&r.formData?o.body=My(r.formData):o.body=r.formData}return new Request(s,o)}function My(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function cC(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function b2(e,t,n,r,s,o){let l={},u=null,d,f=!1,h={},m=r&&Br(r[1])?r[1].error:void 0;return n.forEach((g,x)=>{let b=t[x].route.id;if(Ct(!ii(g),"Cannot handle redirect results in processLoaderData"),Br(g)){let w=g.error;m!==void 0&&(w=m,m=void 0),u=u||{};{let C=jl(e,b);u[C.route.id]==null&&(u[C.route.id]=w)}l[b]=void 0,f||(f=!0,d=mh(g.error)?g.error.status:500),g.headers&&(h[b]=g.headers)}else ai(g)?(s.set(b,g.deferredData),l[b]=g.deferredData.data,g.statusCode!=null&&g.statusCode!==200&&!f&&(d=g.statusCode),g.headers&&(h[b]=g.headers)):(l[b]=g.data,g.statusCode&&g.statusCode!==200&&!f&&(d=g.statusCode),g.headers&&(h[b]=g.headers))}),m!==void 0&&r&&(u={[r[0]]:m},l[r[0]]=void 0),{loaderData:l,errors:u,statusCode:d||200,loaderHeaders:h}}function uC(e,t,n,r,s,o,l,u){let{loaderData:d,errors:f}=b2(t,n,r,s,u);for(let h=0;hr.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function pC(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function lr(e,t){let{pathname:n,routeId:r,method:s,type:o,message:l}=t===void 0?{}:t,u="Unknown Server Error",d="Unknown @remix-run/router error";return e===400?(u="Bad Request",o==="route-discovery"?d='Unable to match URL "'+n+'" - the `unstable_patchRoutesOnMiss()` '+(`function threw the following error: +`+l):s&&n&&r?d="You made a "+s+' request to "'+n+'" but '+('did not provide a `loader` for route "'+r+'", ')+"so there is no way to handle the request.":o==="defer-action"?d="defer() is not supported in actions":o==="invalid-body"&&(d="Unable to encode submission body")):e===403?(u="Forbidden",d='Route "'+r+'" does not match URL "'+n+'"'):e===404?(u="Not Found",d='No route matches URL "'+n+'"'):e===405&&(u="Method Not Allowed",s&&n&&r?d="You made a "+s.toUpperCase()+' request to "'+n+'" but '+('did not provide an `action` for route "'+r+'", ')+"so there is no way to handle the request.":s&&(d='Invalid request method "'+s.toUpperCase()+'"')),new Ab(e||500,u,new Error(d),!0)}function hC(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(ii(n))return{result:n,idx:t}}}function pj(e){let t=typeof e=="string"?_a(e):e;return wi(mn({},t,{hash:""}))}function x2(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function w2(e){return typeof e=="object"&&e!=null&&"then"in e}function S2(e){return hj(e.result)&&o2.has(e.result.status)}function ai(e){return e.type===Zt.deferred}function Br(e){return e.type===Zt.error}function ii(e){return(e&&e.type)===Zt.redirect}function C2(e){let t=e;return t&&typeof t=="object"&&typeof t.data=="object"&&typeof t.subscribe=="function"&&typeof t.cancel=="function"&&typeof t.resolveData=="function"}function hj(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function E2(e){return s2.has(e.toLowerCase())}function bs(e){return n2.has(e.toLowerCase())}async function gC(e,t,n,r,s,o){for(let l=0;lm.route.id===d.route.id),h=f!=null&&!dj(f,d)&&(o&&o[d.route.id])!==void 0;if(ai(u)&&(s||h)){let m=r[l];Ct(m,"Expected an AbortSignal for revalidating fetcher deferred result"),await gj(u,m,s).then(g=>{g&&(n[l]=g||n[l])})}}}async function gj(e,t,n){if(n===void 0&&(n=!1),!await e.deferredData.resolveData(t)){if(n)try{return{type:Zt.data,data:e.deferredData.unwrappedData}}catch(s){return{type:Zt.error,error:s}}return{type:Zt.data,data:e.deferredData.data}}}function Fb(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function gu(e,t){let n=typeof t=="string"?_a(t).search:t.search;if(e[e.length-1].route.index&&Fb(n||""))return e[e.length-1];let r=lj(e);return r[r.length-1]}function mC(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:o,json:l}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(l!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:l,text:void 0}}}function hv(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function k2(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function tu(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function j2(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function da(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function T2(e,t){try{let n=e.sessionStorage.getItem(uj);if(n){let r=JSON.parse(n);for(let[s,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(s,new Set(o||[]))}}catch{}}function N2(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem(uj,JSON.stringify(n))}catch(r){Ll(!1,"Failed to save applied view transitions in sessionStorage ("+r+").")}}}/** + * React Router v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Rp(){return Rp=Object.assign?Object.assign.bind():function(e){for(var t=1;t{u.current=!0}),y.useCallback(function(f,h){if(h===void 0&&(h={}),!u.current)return;if(typeof f=="number"){r.go(f);return}let m=gh(f,JSON.parse(l),o,h.relative==="path");e==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:To([t,m.pathname])),(h.replace?r.replace:r.push)(m,h.state,h)},[t,r,l,o,e])}function ls(){let{matches:e}=y.useContext(Po),t=e[e.length-1];return t?t.params:{}}function bj(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=y.useContext(Ra),{matches:s}=y.useContext(Po),{pathname:o}=Pi(),l=JSON.stringify(hh(s,r.v7_relativeSplatPath));return y.useMemo(()=>gh(e,JSON.parse(l),o,n==="path"),[e,l,o,n])}function R2(e,t,n,r){ec()||Ct(!1);let{navigator:s}=y.useContext(Ra),{matches:o}=y.useContext(Po),l=o[o.length-1],u=l?l.params:{};l&&l.pathname;let d=l?l.pathnameBase:"/";l&&l.route;let f=Pi(),h;h=f;let m=h.pathname||"/",g=m;if(d!=="/"){let w=d.replace(/^\//,"").split("/");g="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let x=oi(e,{pathname:g});return D2(x&&x.map(w=>Object.assign({},w,{params:Object.assign({},u,w.params),pathname:To([d,s.encodeLocation?s.encodeLocation(w.pathname).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?d:To([d,s.encodeLocation?s.encodeLocation(w.pathnameBase).pathname:w.pathnameBase])})),o,n,r)}function P2(){let e=B2(),t=mh(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},t),n?y.createElement("pre",{style:s},n):null,null)}const O2=y.createElement(P2,null);class I2 extends y.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?y.createElement(Po.Provider,{value:this.props.routeContext},y.createElement(vj.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function A2(e){let{routeContext:t,match:n,children:r}=e,s=y.useContext(vh);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),y.createElement(Po.Provider,{value:t},r)}function D2(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var o;if((o=n)!=null&&o.errors)e=n.matches;else return null}let l=e,u=(s=n)==null?void 0:s.errors;if(u!=null){let h=l.findIndex(m=>m.route.id&&u?.[m.route.id]!==void 0);h>=0||Ct(!1),l=l.slice(0,Math.min(l.length,h+1))}let d=!1,f=-1;if(n&&r&&r.v7_partialHydration)for(let h=0;h=0?l=l.slice(0,f+1):l=[l[0]];break}}}return l.reduceRight((h,m,g)=>{let x,b=!1,w=null,C=null;n&&(x=u&&m.route.id?u[m.route.id]:void 0,w=m.route.errorElement||O2,d&&(f<0&&g===0?(U2("route-fallback"),b=!0,C=null):f===g&&(b=!0,C=m.route.hydrateFallbackElement||null)));let k=t.concat(l.slice(0,g+1)),j=()=>{let M;return x?M=w:b?M=C:m.route.Component?M=y.createElement(m.route.Component,null):m.route.element?M=m.route.element:M=h,y.createElement(A2,{match:m,routeContext:{outlet:h,matches:k,isDataRoute:n!=null},children:M})};return n&&(m.route.ErrorBoundary||m.route.errorElement||g===0)?y.createElement(I2,{location:n.location,revalidation:n.revalidation,component:w,error:x,children:j(),routeContext:{outlet:null,matches:k,isDataRoute:!0}}):j()},null)}var xj=(function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e})(xj||{}),wj=(function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e})(wj||{});function F2(e){let t=y.useContext(vh);return t||Ct(!1),t}function L2(e){let t=y.useContext(mj);return t||Ct(!1),t}function $2(e){let t=y.useContext(Po);return t||Ct(!1),t}function Sj(e){let t=$2(),n=t.matches[t.matches.length-1];return n.route.id||Ct(!1),n.route.id}function B2(){var e;let t=y.useContext(vj),n=L2(wj.UseRouteError),r=Sj();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function z2(){let{router:e}=F2(xj.UseNavigateStable),t=Sj(),n=y.useRef(!1);return yj(()=>{n.current=!0}),y.useCallback(function(s,o){o===void 0&&(o={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Rp({fromRouteId:t},o)))},[e,t])}const vC={};function U2(e,t,n){vC[e]||(vC[e]=!0)}function Cj(e){let{to:t,replace:n,state:r,relative:s}=e;ec()||Ct(!1);let{future:o,static:l}=y.useContext(Ra),{matches:u}=y.useContext(Po),{pathname:d}=Pi(),f=dn(),h=gh(t,hh(u,o.v7_relativeSplatPath),d,s==="path"),m=JSON.stringify(h);return y.useEffect(()=>f(JSON.parse(m),{replace:n,state:r,relative:s}),[f,m,s,n,r]),null}function V2(e){let{basename:t="/",children:n=null,location:r,navigationType:s=_n.Pop,navigator:o,static:l=!1,future:u}=e;ec()&&Ct(!1);let d=t.replace(/^\/*/,"/"),f=y.useMemo(()=>({basename:d,navigator:o,static:l,future:Rp({v7_relativeSplatPath:!1},u)}),[d,u,o,l]);typeof r=="string"&&(r=_a(r));let{pathname:h="/",search:m="",hash:g="",state:x=null,key:b="default"}=r,w=y.useMemo(()=>{let C=Xl(h,d);return C==null?null:{location:{pathname:C,search:m,hash:g,state:x,key:b},navigationType:s}},[d,h,m,g,x,b,s]);return w==null?null:y.createElement(Ra.Provider,{value:f},y.createElement(Lb.Provider,{children:n,value:w}))}new Promise(()=>{});function H2(e){let t={hasErrorBoundary:e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&Object.assign(t,{element:y.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:y.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:y.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}/** + * React Router DOM v6.25.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Du(){return Du=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function K2(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function W2(e,t){return e.button===0&&(!t||t==="_self")&&!K2(e)}function _y(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(s=>[n,s]):[[n,r]])},[]))}function G2(e,t){let n=_y(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(o=>{n.append(s,o)})}),n}const J2=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],Q2="6";try{window.__reactRouterVersion=Q2}catch{}function Z2(e,t){return c2({basename:void 0,future:Du({},void 0,{v7_prependBasename:!0}),history:OF({window:void 0}),hydrationData:Y2(),routes:e,mapRouteProperties:H2,unstable_dataStrategy:void 0,unstable_patchRoutesOnMiss:void 0,window:void 0}).initialize()}function Y2(){var e;let t=(e=window)==null?void 0:e.__staticRouterHydrationData;return t&&t.errors&&(t=Du({},t,{errors:X2(t.errors)})),t}function X2(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new Ab(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(s.__subType){let o=window[s.__subType];if(typeof o=="function")try{let l=new o(s.message);l.stack="",n[r]=l}catch{}}if(n[r]==null){let o=new Error(s.message);o.stack="",n[r]=o}}else n[r]=s;return n}const eL=y.createContext({isTransitioning:!1}),tL=y.createContext(new Map),nL="startTransition",yC=Yl[nL],rL="flushSync",bC=PF[rL];function sL(e){yC?yC(e):e()}function nu(e){bC?bC(e):e()}class oL{constructor(){this.status="pending",this.promise=new Promise((t,n)=>{this.resolve=r=>{this.status==="pending"&&(this.status="resolved",t(r))},this.reject=r=>{this.status==="pending"&&(this.status="rejected",n(r))}})}}function aL(e){let{fallbackElement:t,router:n,future:r}=e,[s,o]=y.useState(n.state),[l,u]=y.useState(),[d,f]=y.useState({isTransitioning:!1}),[h,m]=y.useState(),[g,x]=y.useState(),[b,w]=y.useState(),C=y.useRef(new Map),{v7_startTransition:k}=r||{},j=y.useCallback(D=>{k?sL(D):D()},[k]),M=y.useCallback((D,z)=>{let{deletedFetchers:Q,unstable_flushSync:pe,unstable_viewTransitionOpts:V}=z;Q.forEach(W=>C.current.delete(W)),D.fetchers.forEach((W,ie)=>{W.data!==void 0&&C.current.set(ie,W.data)});let G=n.window==null||n.window.document==null||typeof n.window.document.startViewTransition!="function";if(!V||G){pe?nu(()=>o(D)):j(()=>o(D));return}if(pe){nu(()=>{g&&(h&&h.resolve(),g.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:V.currentLocation,nextLocation:V.nextLocation})});let W=n.window.document.startViewTransition(()=>{nu(()=>o(D))});W.finished.finally(()=>{nu(()=>{m(void 0),x(void 0),u(void 0),f({isTransitioning:!1})})}),nu(()=>x(W));return}g?(h&&h.resolve(),g.skipTransition(),w({state:D,currentLocation:V.currentLocation,nextLocation:V.nextLocation})):(u(D),f({isTransitioning:!0,flushSync:!1,currentLocation:V.currentLocation,nextLocation:V.nextLocation}))},[n.window,g,h,C,j]);y.useLayoutEffect(()=>n.subscribe(M),[n,M]),y.useEffect(()=>{d.isTransitioning&&!d.flushSync&&m(new oL)},[d]),y.useEffect(()=>{if(h&&l&&n.window){let D=l,z=h.promise,Q=n.window.document.startViewTransition(async()=>{j(()=>o(D)),await z});Q.finished.finally(()=>{m(void 0),x(void 0),u(void 0),f({isTransitioning:!1})}),x(Q)}},[j,l,h,n.window]),y.useEffect(()=>{h&&l&&s.location.key===l.location.key&&h.resolve()},[h,g,s.location,l]),y.useEffect(()=>{!d.isTransitioning&&b&&(u(b.state),f({isTransitioning:!0,flushSync:!1,currentLocation:b.currentLocation,nextLocation:b.nextLocation}),w(void 0))},[d.isTransitioning,b]),y.useEffect(()=>{},[]);let _=y.useMemo(()=>({createHref:n.createHref,encodeLocation:n.encodeLocation,go:D=>n.navigate(D),push:(D,z,Q)=>n.navigate(D,{state:z,preventScrollReset:Q?.preventScrollReset}),replace:(D,z,Q)=>n.navigate(D,{replace:!0,state:z,preventScrollReset:Q?.preventScrollReset})}),[n]),R=n.basename||"/",N=y.useMemo(()=>({router:n,navigator:_,static:!1,basename:R}),[n,_,R]),O=y.useMemo(()=>({v7_relativeSplatPath:n.future.v7_relativeSplatPath}),[n.future.v7_relativeSplatPath]);return y.createElement(y.Fragment,null,y.createElement(vh.Provider,{value:N},y.createElement(mj.Provider,{value:s},y.createElement(tL.Provider,{value:C.current},y.createElement(eL.Provider,{value:d},y.createElement(V2,{basename:R,location:s.location,navigationType:s.historyAction,navigator:_,future:O},s.initialized||n.future.v7_partialHydration?y.createElement(iL,{routes:n.routes,future:n.future,state:s}):t))))),null)}const iL=y.memo(lL);function lL(e){let{routes:t,future:n,state:r}=e;return R2(t,void 0,r,n)}const cL=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",uL=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Fu=y.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:o,replace:l,state:u,target:d,to:f,preventScrollReset:h,unstable_viewTransition:m}=t,g=q2(t,J2),{basename:x}=y.useContext(Ra),b,w=!1;if(typeof f=="string"&&uL.test(f)&&(b=f,cL))try{let M=new URL(window.location.href),_=f.startsWith("//")?new URL(M.protocol+f):new URL(f),R=Xl(_.pathname,x);_.origin===M.origin&&R!=null?f=R+_.search+_.hash:w=!0}catch{}let C=M2(f,{relative:s}),k=dL(f,{replace:l,state:u,target:d,preventScrollReset:h,relative:s,unstable_viewTransition:m});function j(M){r&&r(M),M.defaultPrevented||k(M)}return y.createElement("a",Du({},g,{href:b||C,onClick:w||o?r:j,ref:n,target:d}))});var xC;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(xC||(xC={}));var wC;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(wC||(wC={}));function dL(e,t){let{target:n,replace:r,state:s,preventScrollReset:o,relative:l,unstable_viewTransition:u}=t===void 0?{}:t,d=dn(),f=Pi(),h=bj(e,{relative:l});return y.useCallback(m=>{if(W2(m,n)){m.preventDefault();let g=r!==void 0?r:wi(f)===wi(h);d(e,{replace:g,state:s,preventScrollReset:o,relative:l,unstable_viewTransition:u})}},[f,d,h,r,s,n,e,o,l,u])}function hd(e){let t=y.useRef(_y(e)),n=y.useRef(!1),r=Pi(),s=y.useMemo(()=>G2(r.search,n.current?null:t.current),[r.search]),o=dn(),l=y.useCallback((u,d)=>{const f=_y(typeof u=="function"?u(s):u);n.current=!0,o("?"+f,d)},[o,s]);return[s,l]}function Ej(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;ttypeof e=="number"&&!isNaN(e),pi=e=>typeof e=="string",Ur=e=>typeof e=="function",up=e=>pi(e)||Ur(e)?e:null,Ry=e=>y.isValidElement(e)||pi(e)||Ur(e)||Lu(e);function fL(e,t,n){n===void 0&&(n=300);const{scrollHeight:r,style:s}=e;requestAnimationFrame(()=>{s.minHeight="initial",s.height=r+"px",s.transition=`all ${n}ms`,requestAnimationFrame(()=>{s.height="0",s.padding="0",s.margin="0",setTimeout(t,n)})})}function yh(e){let{enter:t,exit:n,appendPosition:r=!1,collapse:s=!0,collapseDuration:o=300}=e;return function(l){let{children:u,position:d,preventExitTransition:f,done:h,nodeRef:m,isIn:g,playToast:x}=l;const b=r?`${t}--${d}`:t,w=r?`${n}--${d}`:n,C=y.useRef(0);return y.useLayoutEffect(()=>{const k=m.current,j=b.split(" "),M=_=>{_.target===m.current&&(x(),k.removeEventListener("animationend",M),k.removeEventListener("animationcancel",M),C.current===0&&_.type!=="animationcancel"&&k.classList.remove(...j))};k.classList.add(...j),k.addEventListener("animationend",M),k.addEventListener("animationcancel",M)},[]),y.useEffect(()=>{const k=m.current,j=()=>{k.removeEventListener("animationend",j),s?fL(k,h,o):h()};g||(f?j():(C.current=1,k.className+=` ${w}`,k.addEventListener("animationend",j)))},[g]),qe.createElement(qe.Fragment,null,u)}}function SC(e,t){return e!=null?{content:e.content,containerId:e.props.containerId,id:e.props.toastId,theme:e.props.theme,type:e.props.type,data:e.props.data||{},isLoading:e.props.isLoading,icon:e.props.icon,status:t}:{}}const ur=new Map;let $u=[];const Py=new Set,pL=e=>Py.forEach(t=>t(e)),kj=()=>ur.size>0;function jj(e,t){var n;if(t)return!((n=ur.get(t))==null||!n.isToastActive(e));let r=!1;return ur.forEach(s=>{s.isToastActive(e)&&(r=!0)}),r}function Tj(e,t){Ry(e)&&(kj()||$u.push({content:e,options:t}),ur.forEach(n=>{n.buildToast(e,t)}))}function CC(e,t){ur.forEach(n=>{t!=null&&t!=null&&t.containerId?t?.containerId===n.id&&n.toggle(e,t?.id):n.toggle(e,t?.id)})}function hL(e){const{subscribe:t,getSnapshot:n,setProps:r}=y.useRef((function(o){const l=o.containerId||1;return{subscribe(u){const d=(function(h,m,g){let x=1,b=0,w=[],C=[],k=[],j=m;const M=new Map,_=new Set,R=()=>{k=Array.from(M.values()),_.forEach(D=>D())},N=D=>{C=D==null?[]:C.filter(z=>z!==D),R()},O=D=>{const{toastId:z,onOpen:Q,updateId:pe,children:V}=D.props,G=pe==null;D.staleId&&M.delete(D.staleId),M.set(z,D),C=[...C,D.props.toastId].filter(W=>W!==D.staleId),R(),g(SC(D,G?"added":"updated")),G&&Ur(Q)&&Q(y.isValidElement(V)&&V.props)};return{id:h,props:j,observe:D=>(_.add(D),()=>_.delete(D)),toggle:(D,z)=>{M.forEach(Q=>{z!=null&&z!==Q.props.toastId||Ur(Q.toggle)&&Q.toggle(D)})},removeToast:N,toasts:M,clearQueue:()=>{b-=w.length,w=[]},buildToast:(D,z)=>{if((F=>{let{containerId:fe,toastId:te,updateId:de}=F;const ge=fe?fe!==h:h!==1,Z=M.has(te)&&de==null;return ge||Z})(z))return;const{toastId:Q,updateId:pe,data:V,staleId:G,delay:W}=z,ie=()=>{N(Q)},re=pe==null;re&&b++;const Y={...j,style:j.toastStyle,key:x++,...Object.fromEntries(Object.entries(z).filter(F=>{let[fe,te]=F;return te!=null})),toastId:Q,updateId:pe,data:V,closeToast:ie,isIn:!1,className:up(z.className||j.toastClassName),bodyClassName:up(z.bodyClassName||j.bodyClassName),progressClassName:up(z.progressClassName||j.progressClassName),autoClose:!z.isLoading&&(H=z.autoClose,q=j.autoClose,H===!1||Lu(H)&&H>0?H:q),deleteToast(){const F=M.get(Q),{onClose:fe,children:te}=F.props;Ur(fe)&&fe(y.isValidElement(te)&&te.props),g(SC(F,"removed")),M.delete(Q),b--,b<0&&(b=0),w.length>0?O(w.shift()):R()}};var H,q;Y.closeButton=j.closeButton,z.closeButton===!1||Ry(z.closeButton)?Y.closeButton=z.closeButton:z.closeButton===!0&&(Y.closeButton=!Ry(j.closeButton)||j.closeButton);let he=D;y.isValidElement(D)&&!pi(D.type)?he=y.cloneElement(D,{closeToast:ie,toastProps:Y,data:V}):Ur(D)&&(he=D({closeToast:ie,toastProps:Y,data:V}));const A={content:he,props:Y,staleId:G};j.limit&&j.limit>0&&b>j.limit&&re?w.push(A):Lu(W)?setTimeout(()=>{O(A)},W):O(A)},setProps(D){j=D},setToggle:(D,z)=>{M.get(D).toggle=z},isToastActive:D=>C.some(z=>z===D),getSnapshot:()=>j.newestOnTop?k.reverse():k}})(l,o,pL);ur.set(l,d);const f=d.observe(u);return $u.forEach(h=>Tj(h.content,h.options)),$u=[],()=>{f(),ur.delete(l)}},setProps(u){var d;(d=ur.get(l))==null||d.setProps(u)},getSnapshot(){var u;return(u=ur.get(l))==null?void 0:u.getSnapshot()}}})(e)).current;r(e);const s=y.useSyncExternalStore(t,n,n);return{getToastToRender:function(o){if(!s)return[];const l=new Map;return s.forEach(u=>{const{position:d}=u.props;l.has(d)||l.set(d,[]),l.get(d).push(u)}),Array.from(l,u=>o(u[0],u[1]))},isToastActive:jj,count:s?.length}}function gL(e){const[t,n]=y.useState(!1),[r,s]=y.useState(!1),o=y.useRef(null),l=y.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:u,pauseOnHover:d,closeToast:f,onClick:h,closeOnClick:m}=e;var g,x;function b(){n(!0)}function w(){n(!1)}function C(M){const _=o.current;l.canDrag&&_&&(l.didMove=!0,t&&w(),l.delta=e.draggableDirection==="x"?M.clientX-l.start:M.clientY-l.start,l.start!==M.clientX&&(l.canCloseOnClick=!1),_.style.transform=`translate3d(${e.draggableDirection==="x"?`${l.delta}px, var(--y)`:`0, calc(${l.delta}px + var(--y))`},0)`,_.style.opacity=""+(1-Math.abs(l.delta/l.removalDistance)))}function k(){document.removeEventListener("pointermove",C),document.removeEventListener("pointerup",k);const M=o.current;if(l.canDrag&&l.didMove&&M){if(l.canDrag=!1,Math.abs(l.delta)>l.removalDistance)return s(!0),e.closeToast(),void e.collapseAll();M.style.transition="transform 0.2s, opacity 0.2s",M.style.removeProperty("transform"),M.style.removeProperty("opacity")}}(x=ur.get((g={id:e.toastId,containerId:e.containerId,fn:n}).containerId||1))==null||x.setToggle(g.id,g.fn),y.useEffect(()=>{if(e.pauseOnFocusLoss)return document.hasFocus()||w(),window.addEventListener("focus",b),window.addEventListener("blur",w),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",w)}},[e.pauseOnFocusLoss]);const j={onPointerDown:function(M){if(e.draggable===!0||e.draggable===M.pointerType){l.didMove=!1,document.addEventListener("pointermove",C),document.addEventListener("pointerup",k);const _=o.current;l.canCloseOnClick=!0,l.canDrag=!0,_.style.transition="none",e.draggableDirection==="x"?(l.start=M.clientX,l.removalDistance=_.offsetWidth*(e.draggablePercent/100)):(l.start=M.clientY,l.removalDistance=_.offsetHeight*(e.draggablePercent===80?1.5*e.draggablePercent:e.draggablePercent)/100)}},onPointerUp:function(M){const{top:_,bottom:R,left:N,right:O}=o.current.getBoundingClientRect();M.nativeEvent.type!=="touchend"&&e.pauseOnHover&&M.clientX>=N&&M.clientX<=O&&M.clientY>=_&&M.clientY<=R?w():b()}};return u&&d&&(j.onMouseEnter=w,e.stacked||(j.onMouseLeave=b)),m&&(j.onClick=M=>{h&&h(M),l.canCloseOnClick&&f()}),{playToast:b,pauseToast:w,isRunning:t,preventExitTransition:r,toastRef:o,eventHandlers:j}}function mL(e){let{delay:t,isRunning:n,closeToast:r,type:s="default",hide:o,className:l,style:u,controlledProgress:d,progress:f,rtl:h,isIn:m,theme:g}=e;const x=o||d&&f===0,b={...u,animationDuration:`${t}ms`,animationPlayState:n?"running":"paused"};d&&(b.transform=`scaleX(${f})`);const w=wo("Toastify__progress-bar",d?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${g}`,`Toastify__progress-bar--${s}`,{"Toastify__progress-bar--rtl":h}),C=Ur(l)?l({rtl:h,type:s,defaultClassName:w}):wo(w,l),k={[d&&f>=1?"onTransitionEnd":"onAnimationEnd"]:d&&f<1?null:()=>{m&&r()}};return qe.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":x},qe.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${g} Toastify__progress-bar--${s}`}),qe.createElement("div",{role:"progressbar","aria-hidden":x?"true":"false","aria-label":"notification timer",className:C,style:b,...k}))}let vL=1;const Nj=()=>""+vL++;function yL(e){return e&&(pi(e.toastId)||Lu(e.toastId))?e.toastId:Nj()}function ku(e,t){return Tj(e,t),t.toastId}function Pp(e,t){return{...t,type:t&&t.type||e,toastId:yL(t)}}function Lf(e){return(t,n)=>ku(t,Pp(e,n))}function me(e,t){return ku(e,Pp("default",t))}me.loading=(e,t)=>ku(e,Pp("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),me.promise=function(e,t,n){let r,{pending:s,error:o,success:l}=t;s&&(r=pi(s)?me.loading(s,n):me.loading(s.render,{...n,...s}));const u={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},d=(h,m,g)=>{if(m==null)return void me.dismiss(r);const x={type:h,...u,...n,data:g},b=pi(m)?{render:m}:m;return r?me.update(r,{...x,...b}):me(b.render,{...x,...b}),g},f=Ur(e)?e():e;return f.then(h=>d("success",l,h)).catch(h=>d("error",o,h)),f},me.success=Lf("success"),me.info=Lf("info"),me.error=Lf("error"),me.warning=Lf("warning"),me.warn=me.warning,me.dark=(e,t)=>ku(e,Pp("default",{theme:"dark",...t})),me.dismiss=function(e){(function(t){var n;if(kj()){if(t==null||pi(n=t)||Lu(n))ur.forEach(r=>{r.removeToast(t)});else if(t&&("containerId"in t||"id"in t)){const r=ur.get(t.containerId);r?r.removeToast(t.id):ur.forEach(s=>{s.removeToast(t.id)})}}else $u=$u.filter(r=>t!=null&&r.options.toastId!==t)})(e)},me.clearWaitingQueue=function(e){e===void 0&&(e={}),ur.forEach(t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()})},me.isActive=jj,me.update=function(e,t){t===void 0&&(t={});const n=((r,s)=>{var o;let{containerId:l}=s;return(o=ur.get(l||1))==null?void 0:o.toasts.get(r)})(e,t);if(n){const{props:r,content:s}=n,o={delay:100,...r,...t,toastId:t.toastId||e,updateId:Nj()};o.toastId!==e&&(o.staleId=e);const l=o.render||s;delete o.render,ku(l,o)}},me.done=e=>{me.update(e,{progress:1})},me.onChange=function(e){return Py.add(e),()=>{Py.delete(e)}},me.play=e=>CC(!0,e),me.pause=e=>CC(!1,e);const bL=typeof window<"u"?y.useLayoutEffect:y.useEffect,$f=e=>{let{theme:t,type:n,isLoading:r,...s}=e;return qe.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:t==="colored"?"currentColor":`var(--toastify-icon-color-${n})`,...s})},gv={info:function(e){return qe.createElement($f,{...e},qe.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(e){return qe.createElement($f,{...e},qe.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(e){return qe.createElement($f,{...e},qe.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(e){return qe.createElement($f,{...e},qe.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return qe.createElement("div",{className:"Toastify__spinner"})}},xL=e=>{const{isRunning:t,preventExitTransition:n,toastRef:r,eventHandlers:s,playToast:o}=gL(e),{closeButton:l,children:u,autoClose:d,onClick:f,type:h,hideProgressBar:m,closeToast:g,transition:x,position:b,className:w,style:C,bodyClassName:k,bodyStyle:j,progressClassName:M,progressStyle:_,updateId:R,role:N,progress:O,rtl:D,toastId:z,deleteToast:Q,isIn:pe,isLoading:V,closeOnClick:G,theme:W}=e,ie=wo("Toastify__toast",`Toastify__toast-theme--${W}`,`Toastify__toast--${h}`,{"Toastify__toast--rtl":D},{"Toastify__toast--close-on-click":G}),re=Ur(w)?w({rtl:D,position:b,type:h,defaultClassName:ie}):wo(ie,w),Y=(function(A){let{theme:F,type:fe,isLoading:te,icon:de}=A,ge=null;const Z={theme:F,type:fe};return de===!1||(Ur(de)?ge=de({...Z,isLoading:te}):y.isValidElement(de)?ge=y.cloneElement(de,Z):te?ge=gv.spinner():(ye=>ye in gv)(fe)&&(ge=gv[fe](Z))),ge})(e),H=!!O||!d,q={closeToast:g,type:h,theme:W};let he=null;return l===!1||(he=Ur(l)?l(q):y.isValidElement(l)?y.cloneElement(l,q):(function(A){let{closeToast:F,theme:fe,ariaLabel:te="close"}=A;return qe.createElement("button",{className:`Toastify__close-button Toastify__close-button--${fe}`,type:"button",onClick:de=>{de.stopPropagation(),F(de)},"aria-label":te},qe.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},qe.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))})(q)),qe.createElement(x,{isIn:pe,done:Q,position:b,preventExitTransition:n,nodeRef:r,playToast:o},qe.createElement("div",{id:z,onClick:f,"data-in":pe,className:re,...s,style:C,ref:r},qe.createElement("div",{...pe&&{role:N},className:Ur(k)?k({type:h}):wo("Toastify__toast-body",k),style:j},Y!=null&&qe.createElement("div",{className:wo("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!V})},Y),qe.createElement("div",null,u)),he,qe.createElement(mL,{...R&&!H?{key:`pb-${R}`}:{},rtl:D,theme:W,delay:d,isRunning:t,isIn:pe,closeToast:g,hide:m,type:h,style:_,className:M,controlledProgress:H,progress:O||0})))},bh=function(e,t){return t===void 0&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}},wL=yh(bh("bounce",!0));yh(bh("slide",!0));yh(bh("zoom"));yh(bh("flip"));const SL={position:"top-right",transition:wL,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function CL(e){let t={...SL,...e};const n=e.stacked,[r,s]=y.useState(!0),o=y.useRef(null),{getToastToRender:l,isToastActive:u,count:d}=hL(t),{className:f,style:h,rtl:m,containerId:g}=t;function x(w){const C=wo("Toastify__toast-container",`Toastify__toast-container--${w}`,{"Toastify__toast-container--rtl":m});return Ur(f)?f({position:w,rtl:m,defaultClassName:C}):wo(C,up(f))}function b(){n&&(s(!0),me.play())}return bL(()=>{if(n){var w;const C=o.current.querySelectorAll('[data-in="true"]'),k=12,j=(w=t.position)==null?void 0:w.includes("top");let M=0,_=0;Array.from(C).reverse().forEach((R,N)=>{const O=R;O.classList.add("Toastify__toast--stacked"),N>0&&(O.dataset.collapsed=`${r}`),O.dataset.pos||(O.dataset.pos=j?"top":"bot");const D=M*(r?.2:1)+(r?0:k*N);O.style.setProperty("--y",`${j?D:-1*D}px`),O.style.setProperty("--g",`${k}`),O.style.setProperty("--s",""+(1-(r?_:0))),M+=O.offsetHeight,_+=.025})}},[r,d,n]),qe.createElement("div",{ref:o,className:"Toastify",id:g,onMouseEnter:()=>{n&&(s(!1),me.pause())},onMouseLeave:b},l((w,C)=>{const k=C.length?{...h}:{...h,pointerEvents:"none"};return qe.createElement("div",{className:x(w),style:k,key:`container-${w}`},C.map(j=>{let{content:M,props:_}=j;return qe.createElement(xL,{..._,stacked:n,collapseAll:b,isIn:u(_.toastId,_.containerId),style:_.style,key:`toast-${_.key}`},M)}))}))}const EL={theme:"system",setTheme:()=>null},Mj=y.createContext(EL);function kL({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const[s,o]=y.useState(()=>localStorage.getItem(n)||t);y.useEffect(()=>{const u=window.document.documentElement;if(u.classList.remove("light","dark"),s==="system"){const d=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";u.classList.add(d);return}u.classList.add(s)},[s]);const l={theme:s,setTheme:u=>{localStorage.setItem(n,u),o(u)}};return i.jsx(Mj.Provider,{...r,value:l,children:e})}const tc=()=>{const e=y.useContext(Mj);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e};let mv=!1;const _j=new KD({defaultOptions:{queries:{staleTime:1e3*60*5,retry(e){return e>=3?(mv===!1&&(mv=!0,me.error("The application is taking longer than expected to load, please try again in a few minutes.",{onClose:()=>{mv=!1}})),!1):!0}}}});var jn=(e=>(e.API_URL="apiUrl",e.TOKEN="token",e.INSTANCE_ID="instanceId",e.INSTANCE_NAME="instanceName",e.INSTANCE_TOKEN="instanceToken",e.VERSION="version",e.FACEBOOK_APP_ID="facebookAppId",e.FACEBOOK_CONFIG_ID="facebookConfigId",e.FACEBOOK_USER_TOKEN="facebookUserToken",e.CLIENT_NAME="clientName",e))(jn||{});const Rj=async e=>{if(e.url){const t=e.url.endsWith("/")?e.url.slice(0,-1):e.url;localStorage.setItem("apiUrl",t)}e.token&&localStorage.setItem("token",e.token),e.version&&localStorage.setItem("version",e.version),e.facebookAppId&&localStorage.setItem("facebookAppId",e.facebookAppId),e.facebookConfigId&&localStorage.setItem("facebookConfigId",e.facebookConfigId),e.facebookUserToken&&localStorage.setItem("facebookUserToken",e.facebookUserToken),e.clientName&&localStorage.setItem("clientName",e.clientName)},Pj=()=>{localStorage.removeItem("apiUrl"),localStorage.removeItem("token"),localStorage.removeItem("version"),localStorage.removeItem("facebookAppId"),localStorage.removeItem("facebookConfigId"),localStorage.removeItem("facebookUserToken"),localStorage.removeItem("clientName")},dr=e=>localStorage.getItem(e),tn=({children:e})=>{const t=dr(jn.API_URL),n=dr(jn.TOKEN),r=dr(jn.VERSION);return!t||!n||!r?i.jsx(Cj,{to:"/manager/login"}):e},jL=({children:e})=>{const t=dr(jn.API_URL),n=dr(jn.TOKEN),r=dr(jn.VERSION);return t&&n&&r?i.jsx(Cj,{to:"/"}):e};function Oj(e,t){return function(){return e.apply(t,arguments)}}const{toString:TL}=Object.prototype,{getPrototypeOf:$b}=Object,{iterator:xh,toStringTag:Ij}=Symbol,wh=(e=>t=>{const n=TL.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Rs=e=>(e=e.toLowerCase(),t=>wh(t)===e),Sh=e=>t=>typeof t===e,{isArray:nc}=Array,$l=Sh("undefined");function gd(e){return e!==null&&!$l(e)&&e.constructor!==null&&!$l(e.constructor)&&jr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Aj=Rs("ArrayBuffer");function NL(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Aj(e.buffer),t}const ML=Sh("string"),jr=Sh("function"),Dj=Sh("number"),md=e=>e!==null&&typeof e=="object",_L=e=>e===!0||e===!1,dp=e=>{if(wh(e)!=="object")return!1;const t=$b(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ij in e)&&!(xh in e)},RL=e=>{if(!md(e)||gd(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},PL=Rs("Date"),OL=Rs("File"),IL=Rs("Blob"),AL=Rs("FileList"),DL=e=>md(e)&&jr(e.pipe),FL=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||jr(e.append)&&((t=wh(e))==="formdata"||t==="object"&&jr(e.toString)&&e.toString()==="[object FormData]"))},LL=Rs("URLSearchParams"),[$L,BL,zL,UL]=["ReadableStream","Request","Response","Headers"].map(Rs),VL=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function vd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),nc(e))for(r=0,s=e.length;r0;)if(s=n[r],t===s.toLowerCase())return s;return null}const li=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Lj=e=>!$l(e)&&e!==li;function Oy(){const{caseless:e,skipUndefined:t}=Lj(this)&&this||{},n={},r=(s,o)=>{const l=e&&Fj(n,o)||o;dp(n[l])&&dp(s)?n[l]=Oy(n[l],s):dp(s)?n[l]=Oy({},s):nc(s)?n[l]=s.slice():(!t||!$l(s))&&(n[l]=s)};for(let s=0,o=arguments.length;s(vd(t,(s,o)=>{n&&jr(s)?e[o]=Oj(s,n):e[o]=s},{allOwnKeys:r}),e),qL=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),KL=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},WL=(e,t,n,r)=>{let s,o,l;const u={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)l=s[o],(!r||r(l,e,t))&&!u[l]&&(t[l]=e[l],u[l]=!0);e=n!==!1&&$b(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},GL=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},JL=e=>{if(!e)return null;if(nc(e))return e;let t=e.length;if(!Dj(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},QL=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$b(Uint8Array)),ZL=(e,t)=>{const r=(e&&e[xh]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},YL=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},XL=Rs("HTMLFormElement"),e4=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),EC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),t4=Rs("RegExp"),$j=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};vd(n,(s,o)=>{let l;(l=t(s,o,e))!==!1&&(r[o]=l||s)}),Object.defineProperties(e,r)},n4=e=>{$j(e,(t,n)=>{if(jr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(jr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},r4=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return nc(e)?r(e):r(String(e).split(t)),n},s4=()=>{},o4=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function a4(e){return!!(e&&jr(e.append)&&e[Ij]==="FormData"&&e[xh])}const i4=e=>{const t=new Array(10),n=(r,s)=>{if(md(r)){if(t.indexOf(r)>=0)return;if(gd(r))return r;if(!("toJSON"in r)){t[s]=r;const o=nc(r)?[]:{};return vd(r,(l,u)=>{const d=n(l,s+1);!$l(d)&&(o[u]=d)}),t[s]=void 0,o}}return r};return n(e,0)},l4=Rs("AsyncFunction"),c4=e=>e&&(md(e)||jr(e))&&jr(e.then)&&jr(e.catch),Bj=((e,t)=>e?setImmediate:t?((n,r)=>(li.addEventListener("message",({source:s,data:o})=>{s===li&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),li.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",jr(li.postMessage)),u4=typeof queueMicrotask<"u"?queueMicrotask.bind(li):typeof process<"u"&&process.nextTick||Bj,d4=e=>e!=null&&jr(e[xh]),ce={isArray:nc,isArrayBuffer:Aj,isBuffer:gd,isFormData:FL,isArrayBufferView:NL,isString:ML,isNumber:Dj,isBoolean:_L,isObject:md,isPlainObject:dp,isEmptyObject:RL,isReadableStream:$L,isRequest:BL,isResponse:zL,isHeaders:UL,isUndefined:$l,isDate:PL,isFile:OL,isBlob:IL,isRegExp:t4,isFunction:jr,isStream:DL,isURLSearchParams:LL,isTypedArray:QL,isFileList:AL,forEach:vd,merge:Oy,extend:HL,trim:VL,stripBOM:qL,inherits:KL,toFlatObject:WL,kindOf:wh,kindOfTest:Rs,endsWith:GL,toArray:JL,forEachEntry:ZL,matchAll:YL,isHTMLForm:XL,hasOwnProperty:EC,hasOwnProp:EC,reduceDescriptors:$j,freezeMethods:n4,toObjectSet:r4,toCamelCase:e4,noop:s4,toFiniteNumber:o4,findKey:Fj,global:li,isContextDefined:Lj,isSpecCompliantForm:a4,toJSONObject:i4,isAsyncFn:l4,isThenable:c4,setImmediate:Bj,asap:u4,isIterable:d4};function vt(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}ce.inherits(vt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ce.toJSONObject(this.config),code:this.code,status:this.status}}});const zj=vt.prototype,Uj={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Uj[e]={value:e}});Object.defineProperties(vt,Uj);Object.defineProperty(zj,"isAxiosError",{value:!0});vt.from=(e,t,n,r,s,o)=>{const l=Object.create(zj);ce.toFlatObject(e,l,function(h){return h!==Error.prototype},f=>f!=="isAxiosError");const u=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return vt.call(l,u,d,n,r,s),e&&l.cause==null&&Object.defineProperty(l,"cause",{value:e,configurable:!0}),l.name=e&&e.name||"Error",o&&Object.assign(l,o),l};const f4=null;function Iy(e){return ce.isPlainObject(e)||ce.isArray(e)}function Vj(e){return ce.endsWith(e,"[]")?e.slice(0,-2):e}function kC(e,t,n){return e?e.concat(t).map(function(s,o){return s=Vj(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function p4(e){return ce.isArray(e)&&!e.some(Iy)}const h4=ce.toFlatObject(ce,{},null,function(t){return/^is[A-Z]/.test(t)});function Ch(e,t,n){if(!ce.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ce.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,C){return!ce.isUndefined(C[w])});const r=n.metaTokens,s=n.visitor||h,o=n.dots,l=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&ce.isSpecCompliantForm(t);if(!ce.isFunction(s))throw new TypeError("visitor must be a function");function f(b){if(b===null)return"";if(ce.isDate(b))return b.toISOString();if(ce.isBoolean(b))return b.toString();if(!d&&ce.isBlob(b))throw new vt("Blob is not supported. Use a Buffer instead.");return ce.isArrayBuffer(b)||ce.isTypedArray(b)?d&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function h(b,w,C){let k=b;if(b&&!C&&typeof b=="object"){if(ce.endsWith(w,"{}"))w=r?w:w.slice(0,-2),b=JSON.stringify(b);else if(ce.isArray(b)&&p4(b)||(ce.isFileList(b)||ce.endsWith(w,"[]"))&&(k=ce.toArray(b)))return w=Vj(w),k.forEach(function(M,_){!(ce.isUndefined(M)||M===null)&&t.append(l===!0?kC([w],_,o):l===null?w:w+"[]",f(M))}),!1}return Iy(b)?!0:(t.append(kC(C,w,o),f(b)),!1)}const m=[],g=Object.assign(h4,{defaultVisitor:h,convertValue:f,isVisitable:Iy});function x(b,w){if(!ce.isUndefined(b)){if(m.indexOf(b)!==-1)throw Error("Circular reference detected in "+w.join("."));m.push(b),ce.forEach(b,function(k,j){(!(ce.isUndefined(k)||k===null)&&s.call(t,k,ce.isString(j)?j.trim():j,w,g))===!0&&x(k,w?w.concat(j):[j])}),m.pop()}}if(!ce.isObject(e))throw new TypeError("data must be an object");return x(e),t}function jC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Bb(e,t){this._pairs=[],e&&Ch(e,this,t)}const Hj=Bb.prototype;Hj.append=function(t,n){this._pairs.push([t,n])};Hj.toString=function(t){const n=t?function(r){return t.call(this,r,jC)}:jC;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function g4(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function qj(e,t,n){if(!t)return e;const r=n&&n.encode||g4;ce.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(t,n):o=ce.isURLSearchParams(t)?t.toString():new Bb(t,n).toString(r),o){const l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class TC{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ce.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Kj={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},m4=typeof URLSearchParams<"u"?URLSearchParams:Bb,v4=typeof FormData<"u"?FormData:null,y4=typeof Blob<"u"?Blob:null,b4={isBrowser:!0,classes:{URLSearchParams:m4,FormData:v4,Blob:y4},protocols:["http","https","file","blob","url","data"]},zb=typeof window<"u"&&typeof document<"u",Ay=typeof navigator=="object"&&navigator||void 0,x4=zb&&(!Ay||["ReactNative","NativeScript","NS"].indexOf(Ay.product)<0),w4=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",S4=zb&&window.location.href||"http://localhost",C4=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:zb,hasStandardBrowserEnv:x4,hasStandardBrowserWebWorkerEnv:w4,navigator:Ay,origin:S4},Symbol.toStringTag,{value:"Module"})),rr={...C4,...b4};function E4(e,t){return Ch(e,new rr.classes.URLSearchParams,{visitor:function(n,r,s,o){return rr.isNode&&ce.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function k4(e){return ce.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function j4(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r=n.length;return l=!l&&ce.isArray(s)?s.length:l,d?(ce.hasOwnProp(s,l)?s[l]=[s[l],r]:s[l]=r,!u):((!s[l]||!ce.isObject(s[l]))&&(s[l]=[]),t(n,r,s[l],o)&&ce.isArray(s[l])&&(s[l]=j4(s[l])),!u)}if(ce.isFormData(e)&&ce.isFunction(e.entries)){const n={};return ce.forEachEntry(e,(r,s)=>{t(k4(r),s,n,0)}),n}return null}function T4(e,t,n){if(ce.isString(e))try{return(t||JSON.parse)(e),ce.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const yd={transitional:Kj,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=ce.isObject(t);if(o&&ce.isHTMLForm(t)&&(t=new FormData(t)),ce.isFormData(t))return s?JSON.stringify(Wj(t)):t;if(ce.isArrayBuffer(t)||ce.isBuffer(t)||ce.isStream(t)||ce.isFile(t)||ce.isBlob(t)||ce.isReadableStream(t))return t;if(ce.isArrayBufferView(t))return t.buffer;if(ce.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let u;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return E4(t,this.formSerializer).toString();if((u=ce.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return Ch(u?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),T4(t)):t}],transformResponse:[function(t){const n=this.transitional||yd.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(ce.isResponse(t)||ce.isReadableStream(t))return t;if(t&&ce.isString(t)&&(r&&!this.responseType||s)){const l=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(u){if(l)throw u.name==="SyntaxError"?vt.from(u,vt.ERR_BAD_RESPONSE,this,null,this.response):u}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:rr.classes.FormData,Blob:rr.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ce.forEach(["delete","get","head","post","put","patch"],e=>{yd.headers[e]={}});const N4=ce.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),M4=e=>{const t={};let n,r,s;return e&&e.split(` +`).forEach(function(l){s=l.indexOf(":"),n=l.substring(0,s).trim().toLowerCase(),r=l.substring(s+1).trim(),!(!n||t[n]&&N4[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},NC=Symbol("internals");function ru(e){return e&&String(e).trim().toLowerCase()}function fp(e){return e===!1||e==null?e:ce.isArray(e)?e.map(fp):String(e)}function _4(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const R4=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function vv(e,t,n,r,s){if(ce.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!ce.isString(t)){if(ce.isString(r))return t.indexOf(r)!==-1;if(ce.isRegExp(r))return r.test(t)}}function P4(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function O4(e,t){const n=ce.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,l){return this[r].call(this,t,s,o,l)},configurable:!0})})}let Tr=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(u,d,f){const h=ru(d);if(!h)throw new Error("header name must be a non-empty string");const m=ce.findKey(s,h);(!m||s[m]===void 0||f===!0||f===void 0&&s[m]!==!1)&&(s[m||d]=fp(u))}const l=(u,d)=>ce.forEach(u,(f,h)=>o(f,h,d));if(ce.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(ce.isString(t)&&(t=t.trim())&&!R4(t))l(M4(t),n);else if(ce.isObject(t)&&ce.isIterable(t)){let u={},d,f;for(const h of t){if(!ce.isArray(h))throw TypeError("Object iterator must return a key-value pair");u[f=h[0]]=(d=u[f])?ce.isArray(d)?[...d,h[1]]:[d,h[1]]:h[1]}l(u,n)}else t!=null&&o(n,t,r);return this}get(t,n){if(t=ru(t),t){const r=ce.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return _4(s);if(ce.isFunction(n))return n.call(this,s,r);if(ce.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ru(t),t){const r=ce.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||vv(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(l){if(l=ru(l),l){const u=ce.findKey(r,l);u&&(!n||vv(r,r[u],u,n))&&(delete r[u],s=!0)}}return ce.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||vv(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return ce.forEach(this,(s,o)=>{const l=ce.findKey(r,o);if(l){n[l]=fp(s),delete n[o];return}const u=t?P4(o):String(o).trim();u!==o&&delete n[o],n[u]=fp(s),r[u]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ce.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&ce.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[NC]=this[NC]={accessors:{}}).accessors,s=this.prototype;function o(l){const u=ru(l);r[u]||(O4(s,l),r[u]=!0)}return ce.isArray(t)?t.forEach(o):o(t),this}};Tr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ce.reduceDescriptors(Tr.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ce.freezeMethods(Tr);function yv(e,t){const n=this||yd,r=t||n,s=Tr.from(r.headers);let o=r.data;return ce.forEach(e,function(u){o=u.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function Gj(e){return!!(e&&e.__CANCEL__)}function rc(e,t,n){vt.call(this,e??"canceled",vt.ERR_CANCELED,t,n),this.name="CanceledError"}ce.inherits(rc,vt,{__CANCEL__:!0});function Jj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new vt("Request failed with status code "+n.status,[vt.ERR_BAD_REQUEST,vt.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function I4(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function A4(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,l;return t=t!==void 0?t:1e3,function(d){const f=Date.now(),h=r[o];l||(l=f),n[s]=d,r[s]=f;let m=o,g=0;for(;m!==s;)g+=n[m++],m=m%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),f-l{n=h,s=null,o&&(clearTimeout(o),o=null),e(...f)};return[(...f)=>{const h=Date.now(),m=h-n;m>=r?l(f,h):(s=f,o||(o=setTimeout(()=>{o=null,l(s)},r-m)))},()=>s&&l(s)]}const Op=(e,t,n=3)=>{let r=0;const s=A4(50,250);return D4(o=>{const l=o.loaded,u=o.lengthComputable?o.total:void 0,d=l-r,f=s(d),h=l<=u;r=l;const m={loaded:l,total:u,progress:u?l/u:void 0,bytes:d,rate:f||void 0,estimated:f&&u&&h?(u-l)/f:void 0,event:o,lengthComputable:u!=null,[t?"download":"upload"]:!0};e(m)},n)},MC=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},_C=e=>(...t)=>ce.asap(()=>e(...t)),F4=rr.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,rr.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(rr.origin),rr.navigator&&/(msie|trident)/i.test(rr.navigator.userAgent)):()=>!0,L4=rr.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const l=[e+"="+encodeURIComponent(t)];ce.isNumber(n)&&l.push("expires="+new Date(n).toGMTString()),ce.isString(r)&&l.push("path="+r),ce.isString(s)&&l.push("domain="+s),o===!0&&l.push("secure"),document.cookie=l.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $4(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function B4(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Qj(e,t,n){let r=!$4(t);return e&&(r||n==!1)?B4(e,t):t}const RC=e=>e instanceof Tr?{...e}:e;function Si(e,t){t=t||{};const n={};function r(f,h,m,g){return ce.isPlainObject(f)&&ce.isPlainObject(h)?ce.merge.call({caseless:g},f,h):ce.isPlainObject(h)?ce.merge({},h):ce.isArray(h)?h.slice():h}function s(f,h,m,g){if(ce.isUndefined(h)){if(!ce.isUndefined(f))return r(void 0,f,m,g)}else return r(f,h,m,g)}function o(f,h){if(!ce.isUndefined(h))return r(void 0,h)}function l(f,h){if(ce.isUndefined(h)){if(!ce.isUndefined(f))return r(void 0,f)}else return r(void 0,h)}function u(f,h,m){if(m in t)return r(f,h);if(m in e)return r(void 0,f)}const d={url:o,method:o,data:o,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:u,headers:(f,h,m)=>s(RC(f),RC(h),m,!0)};return ce.forEach(Object.keys({...e,...t}),function(h){const m=d[h]||s,g=m(e[h],t[h],h);ce.isUndefined(g)&&m!==u||(n[h]=g)}),n}const Zj=e=>{const t=Si({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:l,auth:u}=t;if(t.headers=l=Tr.from(l),t.url=qj(Qj(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),u&&l.set("Authorization","Basic "+btoa((u.username||"")+":"+(u.password?unescape(encodeURIComponent(u.password)):""))),ce.isFormData(n)){if(rr.hasStandardBrowserEnv||rr.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(ce.isFunction(n.getHeaders)){const d=n.getHeaders(),f=["content-type","content-length"];Object.entries(d).forEach(([h,m])=>{f.includes(h.toLowerCase())&&l.set(h,m)})}}if(rr.hasStandardBrowserEnv&&(r&&ce.isFunction(r)&&(r=r(t)),r||r!==!1&&F4(t.url))){const d=s&&o&&L4.read(o);d&&l.set(s,d)}return t},z4=typeof XMLHttpRequest<"u",U4=z4&&function(e){return new Promise(function(n,r){const s=Zj(e);let o=s.data;const l=Tr.from(s.headers).normalize();let{responseType:u,onUploadProgress:d,onDownloadProgress:f}=s,h,m,g,x,b;function w(){x&&x(),b&&b(),s.cancelToken&&s.cancelToken.unsubscribe(h),s.signal&&s.signal.removeEventListener("abort",h)}let C=new XMLHttpRequest;C.open(s.method.toUpperCase(),s.url,!0),C.timeout=s.timeout;function k(){if(!C)return;const M=Tr.from("getAllResponseHeaders"in C&&C.getAllResponseHeaders()),R={data:!u||u==="text"||u==="json"?C.responseText:C.response,status:C.status,statusText:C.statusText,headers:M,config:e,request:C};Jj(function(O){n(O),w()},function(O){r(O),w()},R),C=null}"onloadend"in C?C.onloadend=k:C.onreadystatechange=function(){!C||C.readyState!==4||C.status===0&&!(C.responseURL&&C.responseURL.indexOf("file:")===0)||setTimeout(k)},C.onabort=function(){C&&(r(new vt("Request aborted",vt.ECONNABORTED,e,C)),C=null)},C.onerror=function(_){const R=_&&_.message?_.message:"Network Error",N=new vt(R,vt.ERR_NETWORK,e,C);N.event=_||null,r(N),C=null},C.ontimeout=function(){let _=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const R=s.transitional||Kj;s.timeoutErrorMessage&&(_=s.timeoutErrorMessage),r(new vt(_,R.clarifyTimeoutError?vt.ETIMEDOUT:vt.ECONNABORTED,e,C)),C=null},o===void 0&&l.setContentType(null),"setRequestHeader"in C&&ce.forEach(l.toJSON(),function(_,R){C.setRequestHeader(R,_)}),ce.isUndefined(s.withCredentials)||(C.withCredentials=!!s.withCredentials),u&&u!=="json"&&(C.responseType=s.responseType),f&&([g,b]=Op(f,!0),C.addEventListener("progress",g)),d&&C.upload&&([m,x]=Op(d),C.upload.addEventListener("progress",m),C.upload.addEventListener("loadend",x)),(s.cancelToken||s.signal)&&(h=M=>{C&&(r(!M||M.type?new rc(null,e,C):M),C.abort(),C=null)},s.cancelToken&&s.cancelToken.subscribe(h),s.signal&&(s.signal.aborted?h():s.signal.addEventListener("abort",h)));const j=I4(s.url);if(j&&rr.protocols.indexOf(j)===-1){r(new vt("Unsupported protocol "+j+":",vt.ERR_BAD_REQUEST,e));return}C.send(o||null)})},V4=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const o=function(f){if(!s){s=!0,u();const h=f instanceof Error?f:this.reason;r.abort(h instanceof vt?h:new rc(h instanceof Error?h.message:h))}};let l=t&&setTimeout(()=>{l=null,o(new vt(`timeout ${t} of ms exceeded`,vt.ETIMEDOUT))},t);const u=()=>{e&&(l&&clearTimeout(l),l=null,e.forEach(f=>{f.unsubscribe?f.unsubscribe(o):f.removeEventListener("abort",o)}),e=null)};e.forEach(f=>f.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>ce.asap(u),d}},H4=function*(e,t){let n=e.byteLength;if(n{const s=q4(e,t);let o=0,l,u=d=>{l||(l=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:f,value:h}=await s.next();if(f){u(),d.close();return}let m=h.byteLength;if(n){let g=o+=m;n(g)}d.enqueue(new Uint8Array(h))}catch(f){throw u(f),f}},cancel(d){return u(d),s.return()}},{highWaterMark:2})},OC=64*1024,{isFunction:Bf}=ce,W4=(({Request:e,Response:t})=>({Request:e,Response:t}))(ce.global),{ReadableStream:IC,TextEncoder:AC}=ce.global,DC=(e,...t)=>{try{return!!e(...t)}catch{return!1}},G4=e=>{e=ce.merge.call({skipUndefined:!0},W4,e);const{fetch:t,Request:n,Response:r}=e,s=t?Bf(t):typeof fetch=="function",o=Bf(n),l=Bf(r);if(!s)return!1;const u=s&&Bf(IC),d=s&&(typeof AC=="function"?(b=>w=>b.encode(w))(new AC):async b=>new Uint8Array(await new n(b).arrayBuffer())),f=o&&u&&DC(()=>{let b=!1;const w=new n(rr.origin,{body:new IC,method:"POST",get duplex(){return b=!0,"half"}}).headers.has("Content-Type");return b&&!w}),h=l&&u&&DC(()=>ce.isReadableStream(new r("").body)),m={stream:h&&(b=>b.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(b=>{!m[b]&&(m[b]=(w,C)=>{let k=w&&w[b];if(k)return k.call(w);throw new vt(`Response type '${b}' is not supported`,vt.ERR_NOT_SUPPORT,C)})});const g=async b=>{if(b==null)return 0;if(ce.isBlob(b))return b.size;if(ce.isSpecCompliantForm(b))return(await new n(rr.origin,{method:"POST",body:b}).arrayBuffer()).byteLength;if(ce.isArrayBufferView(b)||ce.isArrayBuffer(b))return b.byteLength;if(ce.isURLSearchParams(b)&&(b=b+""),ce.isString(b))return(await d(b)).byteLength},x=async(b,w)=>{const C=ce.toFiniteNumber(b.getContentLength());return C??g(w)};return async b=>{let{url:w,method:C,data:k,signal:j,cancelToken:M,timeout:_,onDownloadProgress:R,onUploadProgress:N,responseType:O,headers:D,withCredentials:z="same-origin",fetchOptions:Q}=Zj(b),pe=t||fetch;O=O?(O+"").toLowerCase():"text";let V=V4([j,M&&M.toAbortSignal()],_),G=null;const W=V&&V.unsubscribe&&(()=>{V.unsubscribe()});let ie;try{if(N&&f&&C!=="get"&&C!=="head"&&(ie=await x(D,k))!==0){let A=new n(w,{method:"POST",body:k,duplex:"half"}),F;if(ce.isFormData(k)&&(F=A.headers.get("content-type"))&&D.setContentType(F),A.body){const[fe,te]=MC(ie,Op(_C(N)));k=PC(A.body,OC,fe,te)}}ce.isString(z)||(z=z?"include":"omit");const re=o&&"credentials"in n.prototype,Y={...Q,signal:V,method:C.toUpperCase(),headers:D.normalize().toJSON(),body:k,duplex:"half",credentials:re?z:void 0};G=o&&new n(w,Y);let H=await(o?pe(G,Q):pe(w,Y));const q=h&&(O==="stream"||O==="response");if(h&&(R||q&&W)){const A={};["status","statusText","headers"].forEach(de=>{A[de]=H[de]});const F=ce.toFiniteNumber(H.headers.get("content-length")),[fe,te]=R&&MC(F,Op(_C(R),!0))||[];H=new r(PC(H.body,OC,fe,()=>{te&&te(),W&&W()}),A)}O=O||"text";let he=await m[ce.findKey(m,O)||"text"](H,b);return!q&&W&&W(),await new Promise((A,F)=>{Jj(A,F,{data:he,headers:Tr.from(H.headers),status:H.status,statusText:H.statusText,config:b,request:G})})}catch(re){throw W&&W(),re&&re.name==="TypeError"&&/Load failed|fetch/i.test(re.message)?Object.assign(new vt("Network Error",vt.ERR_NETWORK,b,G),{cause:re.cause||re}):vt.from(re,re&&re.code,b,G)}}},J4=new Map,Yj=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:s}=t,o=[r,s,n];let l=o.length,u=l,d,f,h=J4;for(;u--;)d=o[u],f=h.get(d),f===void 0&&h.set(d,f=u?new Map:G4(t)),h=f;return f};Yj();const Dy={http:f4,xhr:U4,fetch:{get:Yj}};ce.forEach(Dy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const FC=e=>`- ${e}`,Q4=e=>ce.isFunction(e)||e===null||e===!1,Xj={getAdapter:(e,t)=>{e=ce.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let l=0;l`adapter ${d} `+(f===!1?"is not supported by the environment":"is not available in the build"));let u=n?l.length>1?`since : +`+l.map(FC).join(` +`):" "+FC(l[0]):"as no adapter specified";throw new vt("There is no suitable adapter to dispatch the request "+u,"ERR_NOT_SUPPORT")}return s},adapters:Dy};function bv(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new rc(null,e)}function LC(e){return bv(e),e.headers=Tr.from(e.headers),e.data=yv.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Xj.getAdapter(e.adapter||yd.adapter,e)(e).then(function(r){return bv(e),r.data=yv.call(e,e.transformResponse,r),r.headers=Tr.from(r.headers),r},function(r){return Gj(r)||(bv(e),r&&r.response&&(r.response.data=yv.call(e,e.transformResponse,r.response),r.response.headers=Tr.from(r.response.headers))),Promise.reject(r)})}const eT="1.12.2",Eh={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Eh[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const $C={};Eh.transitional=function(t,n,r){function s(o,l){return"[Axios v"+eT+"] Transitional option '"+o+"'"+l+(r?". "+r:"")}return(o,l,u)=>{if(t===!1)throw new vt(s(l," has been removed"+(n?" in "+n:"")),vt.ERR_DEPRECATED);return n&&!$C[l]&&($C[l]=!0,console.warn(s(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,l,u):!0}};Eh.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Z4(e,t,n){if(typeof e!="object")throw new vt("options must be an object",vt.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],l=t[o];if(l){const u=e[o],d=u===void 0||l(u,o,e);if(d!==!0)throw new vt("option "+o+" must be "+d,vt.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new vt("Unknown option "+o,vt.ERR_BAD_OPTION)}}const pp={assertOptions:Z4,validators:Eh},$s=pp.validators;let hi=class{constructor(t){this.defaults=t||{},this.interceptors={request:new TC,response:new TC}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Si(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&pp.assertOptions(r,{silentJSONParsing:$s.transitional($s.boolean),forcedJSONParsing:$s.transitional($s.boolean),clarifyTimeoutError:$s.transitional($s.boolean)},!1),s!=null&&(ce.isFunction(s)?n.paramsSerializer={serialize:s}:pp.assertOptions(s,{encode:$s.function,serialize:$s.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),pp.assertOptions(n,{baseUrl:$s.spelling("baseURL"),withXsrfToken:$s.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=o&&ce.merge(o.common,o[n.method]);o&&ce.forEach(["delete","get","head","post","put","patch","common"],b=>{delete o[b]}),n.headers=Tr.concat(l,o);const u=[];let d=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(n)===!1||(d=d&&w.synchronous,u.unshift(w.fulfilled,w.rejected))});const f=[];this.interceptors.response.forEach(function(w){f.push(w.fulfilled,w.rejected)});let h,m=0,g;if(!d){const b=[LC.bind(this),void 0];for(b.unshift(...u),b.push(...f),g=b.length,h=Promise.resolve(n);m{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const l=new Promise(u=>{r.subscribe(u),o=u}).then(s);return l.cancel=function(){r.unsubscribe(o)},l},t(function(o,l,u){r.reason||(r.reason=new rc(o,l,u),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new tT(function(s){t=s}),cancel:t}}};function X4(e){return function(n){return e.apply(null,n)}}function e$(e){return ce.isObject(e)&&e.isAxiosError===!0}const Fy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Fy).forEach(([e,t])=>{Fy[t]=e});function nT(e){const t=new hi(e),n=Oj(hi.prototype.request,t);return ce.extend(n,hi.prototype,t,{allOwnKeys:!0}),ce.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return nT(Si(e,s))},n}const sn=nT(yd);sn.Axios=hi;sn.CanceledError=rc;sn.CancelToken=Y4;sn.isCancel=Gj;sn.VERSION=eT;sn.toFormData=Ch;sn.AxiosError=vt;sn.Cancel=sn.CanceledError;sn.all=function(t){return Promise.all(t)};sn.spread=X4;sn.isAxiosError=e$;sn.mergeConfig=Si;sn.AxiosHeaders=Tr;sn.formToJSON=e=>Wj(ce.isHTMLForm(e)?new FormData(e):e);sn.getAdapter=Xj.getAdapter;sn.HttpStatusCode=Fy;sn.default=sn;const{Axios:aie,AxiosError:iie,CanceledError:lie,isCancel:cie,CancelToken:uie,VERSION:die,all:fie,Cancel:pie,isAxiosError:rT,spread:hie,toFormData:gie,AxiosHeaders:mie,HttpStatusCode:vie,formToJSON:yie,getAdapter:bie,mergeConfig:xie}=sn,t$=e=>["auth","verifyServer",JSON.stringify(e)],sT=async({url:e})=>(await sn.get(`${e}/`)).data,n$=e=>{const{url:t,...n}=e;return mt({...n,queryKey:t$({url:t}),queryFn:()=>sT({url:t}),enabled:!!t})};function r$(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function kh(...e){return t=>e.forEach(n=>r$(n,t))}function Rt(...e){return y.useCallback(kh(...e),e)}var No=y.forwardRef((e,t)=>{const{children:n,...r}=e,s=y.Children.toArray(n),o=s.find(o$);if(o){const l=o.props.children,u=s.map(d=>d===o?y.Children.count(l)>1?y.Children.only(null):y.isValidElement(l)?l.props.children:null:d);return i.jsx(Ly,{...r,ref:t,children:y.isValidElement(l)?y.cloneElement(l,void 0,u):null})}return i.jsx(Ly,{...r,ref:t,children:n})});No.displayName="Slot";var Ly=y.forwardRef((e,t)=>{const{children:n,...r}=e;if(y.isValidElement(n)){const s=i$(n);return y.cloneElement(n,{...a$(r,n.props),ref:t?kh(t,s):s})}return y.Children.count(n)>1?y.Children.only(null):null});Ly.displayName="SlotClone";var s$=({children:e})=>i.jsx(i.Fragment,{children:e});function o$(e){return y.isValidElement(e)&&e.type===s$}function a$(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...u)=>{o(...u),s(...u)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function i$(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function oT(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;ttypeof e=="boolean"?"".concat(e):e===0?"0":e,zC=l$,jh=(e,t)=>n=>{var r;if(t?.variants==null)return zC(e,n?.class,n?.className);const{variants:s,defaultVariants:o}=t,l=Object.keys(s).map(f=>{const h=n?.[f],m=o?.[f];if(h===null)return null;const g=BC(h)||BC(m);return s[f][g]}),u=n&&Object.entries(n).reduce((f,h)=>{let[m,g]=h;return g===void 0||(f[m]=g),f},{}),d=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,h)=>{let{class:m,className:g,...x}=h;return Object.entries(x).every(b=>{let[w,C]=b;return Array.isArray(C)?C.includes({...o,...u}[w]):{...o,...u}[w]===C})?[...f,m,g]:f},[]);return zC(e,l,d,n?.class,n?.className)},Ub="-";function c$(e){const t=d$(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;function s(l){const u=l.split(Ub);return u[0]===""&&u.length!==1&&u.shift(),aT(u,t)||u$(l)}function o(l,u){const d=n[l]||[];return u&&r[l]?[...d,...r[l]]:d}return{getClassGroupId:s,getConflictingClassGroupIds:o}}function aT(e,t){if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?aT(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const o=e.join(Ub);return t.validators.find(({validator:l})=>l(o))?.classGroupId}const UC=/^\[(.+)\]$/;function u$(e){if(UC.test(e)){const t=UC.exec(e)[1],n=t?.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function d$(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return p$(Object.entries(e.classGroups),n).forEach(([o,l])=>{$y(l,r,o,t)}),r}function $y(e,t,n,r){e.forEach(s=>{if(typeof s=="string"){const o=s===""?t:VC(t,s);o.classGroupId=n;return}if(typeof s=="function"){if(f$(s)){$y(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([o,l])=>{$y(l,VC(t,o),n,r)})})}function VC(e,t){let n=e;return t.split(Ub).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function f$(e){return e.isThemeGetter}function p$(e,t){return t?e.map(([n,r])=>{const s=r.map(o=>typeof o=="string"?t+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([l,u])=>[t+l,u])):o);return[n,s]}):e}function h$(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function s(o,l){n.set(o,l),t++,t>e&&(t=0,r=n,n=new Map)}return{get(o){let l=n.get(o);if(l!==void 0)return l;if((l=r.get(o))!==void 0)return s(o,l),l},set(o,l){n.has(o)?n.set(o,l):s(o,l)}}}const iT="!";function g$(e){const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],o=t.length;function l(u){const d=[];let f=0,h=0,m;for(let C=0;Ch?m-h:void 0;return{modifiers:d,hasImportantModifier:x,baseClassName:b,maybePostfixModifierPosition:w}}return n?function(d){return n({className:d,parseClassName:l})}:l}function m$(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function v$(e){return{cache:h$(e.cacheSize),parseClassName:g$(e),...c$(e)}}const y$=/\s+/;function b$(e,t){const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,o=new Set;return e.trim().split(y$).map(l=>{const{modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:h}=n(l);let m=!!h,g=r(m?f.substring(0,h):f);if(!g){if(!m)return{isTailwindClass:!1,originalClassName:l};if(g=r(f),!g)return{isTailwindClass:!1,originalClassName:l};m=!1}const x=m$(u).join(":");return{isTailwindClass:!0,modifierId:d?x+iT:x,classGroupId:g,originalClassName:l,hasPostfixModifier:m}}).reverse().filter(l=>{if(!l.isTailwindClass)return!0;const{modifierId:u,classGroupId:d,hasPostfixModifier:f}=l,h=u+d;return o.has(h)?!1:(o.add(h),s(d,f).forEach(m=>o.add(u+m)),!0)}).reverse().map(l=>l.originalClassName).join(" ")}function x$(){let e=0,t,n,r="";for(;em(h),e());return n=v$(f),r=n.cache.get,s=n.cache.set,o=u,u(d)}function u(d){const f=r(d);if(f)return f;const h=b$(d,n);return s(d,h),h}return function(){return o(x$.apply(null,arguments))}}function nn(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const cT=/^\[(?:([a-z-]+):)?(.+)\]$/i,S$=/^\d+\/\d+$/,C$=new Set(["px","full","screen"]),E$=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,k$=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,j$=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,T$=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,N$=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function ho(e){return ci(e)||C$.has(e)||S$.test(e)}function ca(e){return sc(e,"length",D$)}function ci(e){return!!e&&!Number.isNaN(Number(e))}function zf(e){return sc(e,"number",ci)}function su(e){return!!e&&Number.isInteger(Number(e))}function M$(e){return e.endsWith("%")&&ci(e.slice(0,-1))}function xt(e){return cT.test(e)}function ua(e){return E$.test(e)}const _$=new Set(["length","size","percentage"]);function R$(e){return sc(e,_$,uT)}function P$(e){return sc(e,"position",uT)}const O$=new Set(["image","url"]);function I$(e){return sc(e,O$,L$)}function A$(e){return sc(e,"",F$)}function ou(){return!0}function sc(e,t,n){const r=cT.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function D$(e){return k$.test(e)&&!j$.test(e)}function uT(){return!1}function F$(e){return T$.test(e)}function L$(e){return N$.test(e)}function $$(){const e=nn("colors"),t=nn("spacing"),n=nn("blur"),r=nn("brightness"),s=nn("borderColor"),o=nn("borderRadius"),l=nn("borderSpacing"),u=nn("borderWidth"),d=nn("contrast"),f=nn("grayscale"),h=nn("hueRotate"),m=nn("invert"),g=nn("gap"),x=nn("gradientColorStops"),b=nn("gradientColorStopPositions"),w=nn("inset"),C=nn("margin"),k=nn("opacity"),j=nn("padding"),M=nn("saturate"),_=nn("scale"),R=nn("sepia"),N=nn("skew"),O=nn("space"),D=nn("translate"),z=()=>["auto","contain","none"],Q=()=>["auto","hidden","clip","visible","scroll"],pe=()=>["auto",xt,t],V=()=>[xt,t],G=()=>["",ho,ca],W=()=>["auto",ci,xt],ie=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],re=()=>["solid","dashed","dotted","double","none"],Y=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],H=()=>["start","end","center","between","around","evenly","stretch"],q=()=>["","0",xt],he=()=>["auto","avoid","all","avoid-page","page","left","right","column"],A=()=>[ci,zf],F=()=>[ci,xt];return{cacheSize:500,separator:":",theme:{colors:[ou],spacing:[ho,ca],blur:["none","",ua,xt],brightness:A(),borderColor:[e],borderRadius:["none","","full",ua,xt],borderSpacing:V(),borderWidth:G(),contrast:A(),grayscale:q(),hueRotate:F(),invert:q(),gap:V(),gradientColorStops:[e],gradientColorStopPositions:[M$,ca],inset:pe(),margin:pe(),opacity:A(),padding:V(),saturate:A(),scale:A(),sepia:q(),skew:F(),space:V(),translate:V()},classGroups:{aspect:[{aspect:["auto","square","video",xt]}],container:["container"],columns:[{columns:[ua]}],"break-after":[{"break-after":he()}],"break-before":[{"break-before":he()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ie(),xt]}],overflow:[{overflow:Q()}],"overflow-x":[{"overflow-x":Q()}],"overflow-y":[{"overflow-y":Q()}],overscroll:[{overscroll:z()}],"overscroll-x":[{"overscroll-x":z()}],"overscroll-y":[{"overscroll-y":z()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[w]}],"inset-x":[{"inset-x":[w]}],"inset-y":[{"inset-y":[w]}],start:[{start:[w]}],end:[{end:[w]}],top:[{top:[w]}],right:[{right:[w]}],bottom:[{bottom:[w]}],left:[{left:[w]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",su,xt]}],basis:[{basis:pe()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",xt]}],grow:[{grow:q()}],shrink:[{shrink:q()}],order:[{order:["first","last","none",su,xt]}],"grid-cols":[{"grid-cols":[ou]}],"col-start-end":[{col:["auto",{span:["full",su,xt]},xt]}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":[ou]}],"row-start-end":[{row:["auto",{span:[su,xt]},xt]}],"row-start":[{"row-start":W()}],"row-end":[{"row-end":W()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",xt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",xt]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[j]}],px:[{px:[j]}],py:[{py:[j]}],ps:[{ps:[j]}],pe:[{pe:[j]}],pt:[{pt:[j]}],pr:[{pr:[j]}],pb:[{pb:[j]}],pl:[{pl:[j]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[O]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[O]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",xt,t]}],"min-w":[{"min-w":[xt,t,"min","max","fit"]}],"max-w":[{"max-w":[xt,t,"none","full","min","max","fit","prose",{screen:[ua]},ua]}],h:[{h:[xt,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[xt,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[xt,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[xt,t,"auto","min","max","fit"]}],"font-size":[{text:["base",ua,ca]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",zf]}],"font-family":[{font:[ou]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",xt]}],"line-clamp":[{"line-clamp":["none",ci,zf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ho,xt]}],"list-image":[{"list-image":["none",xt]}],"list-style-type":[{list:["none","disc","decimal",xt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[k]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[k]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ho,ca]}],"underline-offset":[{"underline-offset":["auto",ho,xt]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:V()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",xt]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",xt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[k]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ie(),P$]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",R$]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},I$]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[x]}],"gradient-via":[{via:[x]}],"gradient-to":[{to:[x]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[u]}],"border-w-x":[{"border-x":[u]}],"border-w-y":[{"border-y":[u]}],"border-w-s":[{"border-s":[u]}],"border-w-e":[{"border-e":[u]}],"border-w-t":[{"border-t":[u]}],"border-w-r":[{"border-r":[u]}],"border-w-b":[{"border-b":[u]}],"border-w-l":[{"border-l":[u]}],"border-opacity":[{"border-opacity":[k]}],"border-style":[{border:[...re(),"hidden"]}],"divide-x":[{"divide-x":[u]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[u]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[k]}],"divide-style":[{divide:re()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...re()]}],"outline-offset":[{"outline-offset":[ho,xt]}],"outline-w":[{outline:[ho,ca]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:G()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[k]}],"ring-offset-w":[{"ring-offset":[ho,ca]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",ua,A$]}],"shadow-color":[{shadow:[ou]}],opacity:[{opacity:[k]}],"mix-blend":[{"mix-blend":[...Y(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Y()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",ua,xt]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[M]}],sepia:[{sepia:[R]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[k]}],"backdrop-saturate":[{"backdrop-saturate":[M]}],"backdrop-sepia":[{"backdrop-sepia":[R]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",xt]}],duration:[{duration:F()}],ease:[{ease:["linear","in","out","in-out",xt]}],delay:[{delay:F()}],animate:[{animate:["none","spin","ping","pulse","bounce",xt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[_]}],"scale-x":[{"scale-x":[_]}],"scale-y":[{"scale-y":[_]}],rotate:[{rotate:[su,xt]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[N]}],"skew-y":[{"skew-y":[N]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",xt]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",xt]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":V()}],"scroll-mx":[{"scroll-mx":V()}],"scroll-my":[{"scroll-my":V()}],"scroll-ms":[{"scroll-ms":V()}],"scroll-me":[{"scroll-me":V()}],"scroll-mt":[{"scroll-mt":V()}],"scroll-mr":[{"scroll-mr":V()}],"scroll-mb":[{"scroll-mb":V()}],"scroll-ml":[{"scroll-ml":V()}],"scroll-p":[{"scroll-p":V()}],"scroll-px":[{"scroll-px":V()}],"scroll-py":[{"scroll-py":V()}],"scroll-ps":[{"scroll-ps":V()}],"scroll-pe":[{"scroll-pe":V()}],"scroll-pt":[{"scroll-pt":V()}],"scroll-pr":[{"scroll-pr":V()}],"scroll-pb":[{"scroll-pb":V()}],"scroll-pl":[{"scroll-pl":V()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",xt]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[ho,ca,zf]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}}const B$=w$($$);function Ie(...e){return B$(wo(e))}const z$=jh("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",warning:"bg-amber-600 shadow-sm hover:bg-amber-600/90 data-active:bg-amber-600/90 text-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),se=y.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...s},o)=>{const l=r?No:"button";return i.jsx(l,{className:Ie(z$({variant:t,size:n,className:e})),ref:o,...s})});se.displayName="Button";function Vb(){const{t:e}=Ve(),t=dr(jn.API_URL),{data:n}=n$({url:t}),r=y.useMemo(()=>n?.clientName,[n]),s=y.useMemo(()=>n?.version,[n]),o=[{name:"Discord",url:"https://evolution-api.com/discord"},{name:"Postman",url:"https://evolution-api.com/postman"},{name:"GitHub",url:"https://github.com/EvolutionAPI/evolution-api"},{name:"Docs",url:"https://doc.evolution-api.com"}];return i.jsxs("footer",{className:"flex w-full flex-col items-center justify-between p-6 text-xs text-secondary-foreground sm:flex-row",children:[i.jsxs("div",{className:"flex items-center space-x-3 divide-x",children:[r&&r!==""&&i.jsxs("span",{children:[e("footer.clientName"),": ",i.jsx("strong",{children:r})]}),s&&s!==""&&i.jsxs("span",{className:"pl-3",children:[e("footer.version"),": ",i.jsx("strong",{children:s})]})]}),i.jsx("div",{className:"flex gap-2",children:o.map(l=>i.jsx(se,{variant:"link",asChild:!0,size:"sm",className:"text-xs",children:i.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",children:l.name})},l.url))})]})}/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const U$=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),dT=(...e)=>e.filter((t,n,r)=>!!t&&r.indexOf(t)===n).join(" ");/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var V$={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const H$=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:o,iconNode:l,...u},d)=>y.createElement("svg",{ref:d,...V$,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:dT("lucide",s),...u},[...l.map(([f,h])=>y.createElement(f,h)),...Array.isArray(o)?o:[o]]));/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Qe=(e,t)=>{const n=y.forwardRef(({className:r,...s},o)=>y.createElement(H$,{ref:o,iconNode:t,className:dT(`lucide-${U$(e)}`,r),...s}));return n.displayName=`${e}`,n};/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HC=Qe("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Th=Qe("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const q$=Qe("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K$=Qe("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fT=Qe("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nh=Qe("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const W$=Qe("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const G$=Qe("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const J$=Qe("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Q$=Qe("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oi=Qe("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{width:"6",height:"6",x:"9",y:"9",key:"1wrtvo"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pT=Qe("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Z$=Qe("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Y$=Qe("Club",[["path",{d:"M17.28 9.05a5.5 5.5 0 1 0-10.56 0A5.5 5.5 0 1 0 12 17.66a5.5 5.5 0 1 0 5.28-8.6Z",key:"27yuqz"}],["path",{d:"M12 17.66L12 22",key:"ogfahf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oo=Qe("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const X$=Qe("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ii=Qe("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const eB=Qe("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Pa=Qe("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const tB=Qe("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nB=Qe("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rB=Qe("FilePlus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const sB=Qe("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hb=Qe("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const oB=Qe("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const aB=Qe("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const iB=Qe("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lB=Qe("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cB=Qe("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uB=Qe("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dB=Qe("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fB=Qe("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pB=Qe("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hB=Qe("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gB=Qe("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ai=Qe("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mB=Qe("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vB=Qe("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yB=Qe("MapPin",[["path",{d:"M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z",key:"2oe9fu"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bl=Qe("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hT=Qe("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bB=Qe("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Di=Qe("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fi=Qe("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cs=Qe("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ip=Qe("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Li=Qe("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xB=Qe("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gT=Qe("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wB=Qe("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const SB=Qe("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const CB=Qe("Sticker",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M14 3v4a2 2 0 0 0 2 2h4",key:"36rjfy"}],["path",{d:"M8 13h.01",key:"1sbv64"}],["path",{d:"M16 13h.01",key:"wip0gl"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const EB=Qe("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kB=Qe("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ap=Qe("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jB=Qe("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const TB=Qe("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qb=Qe("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** + * @license lucide-react v0.408.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mT=Qe("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Ee=sn.create({timeout:3e4});Ee.interceptors.request.use(async e=>{const t=dr(jn.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=dr(jn.INSTANCE_TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const bd=sn.create({timeout:3e4});bd.interceptors.request.use(async e=>{const t=dr(jn.API_URL);if(t&&(e.baseURL=t.toString()),!e.headers.apiKey||e.headers.apiKey===""){const n=dr(jn.TOKEN);n&&(e.headers.apikey=`${n}`)}return e},e=>Promise.reject(e));const NB=e=>["instance","fetchInstance",JSON.stringify(e)],MB=async({instanceId:e})=>{const t=await bd.get("/instance/fetchInstances",{params:{instanceId:e}});return Array.isArray(t.data)?t.data[0]:t.data},vT=e=>{const{instanceId:t,...n}=e;return mt({...n,queryKey:NB({instanceId:t}),queryFn:()=>MB({instanceId:t}),enabled:!!t})};function Ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s.defaultPrevented)return t?.(s)}}function _B(e,t){const n=y.createContext(t);function r(o){const{children:l,...u}=o,d=y.useMemo(()=>u,Object.values(u));return i.jsx(n.Provider,{value:d,children:l})}function s(o){const l=y.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function us(e,t=[]){let n=[];function r(o,l){const u=y.createContext(l),d=n.length;n=[...n,l];function f(m){const{scope:g,children:x,...b}=m,w=g?.[e][d]||u,C=y.useMemo(()=>b,Object.values(b));return i.jsx(w.Provider,{value:C,children:x})}function h(m,g){const x=g?.[e][d]||u,b=y.useContext(x);if(b)return b;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${o}\``)}return f.displayName=o+"Provider",[f,h]}const s=()=>{const o=n.map(l=>y.createContext(l));return function(u){const d=u?.[e]||o;return y.useMemo(()=>({[`__scope${e}`]:{...u,[e]:d}}),[u,d])}};return s.scopeName=e,[r,RB(s,...t)]}function RB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const l=r.reduce((u,{useScope:d,scopeName:f})=>{const m=d(o)[`__scope${f}`];return{...u,...m}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function Rn(e){const t=y.useRef(e);return y.useEffect(()=>{t.current=e}),y.useMemo(()=>(...n)=>t.current?.(...n),[])}function ya({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,s]=PB({defaultProp:t,onChange:n}),o=e!==void 0,l=o?e:r,u=Rn(n),d=y.useCallback(f=>{if(o){const m=typeof f=="function"?f(e):f;m!==e&&u(m)}else s(f)},[o,e,s,u]);return[l,d]}function PB({defaultProp:e,onChange:t}){const n=y.useState(e),[r]=n,s=y.useRef(r),o=Rn(t);return y.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),n}var OB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],rt=OB.reduce((e,t)=>{const n=y.forwardRef((r,s)=>{const{asChild:o,...l}=r,u=o?No:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(u,{...l,ref:s})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function yT(e,t){e&&Ma.flushSync(()=>e.dispatchEvent(t))}function Kb(e){const t=e+"CollectionProvider",[n,r]=us(t),[s,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=x=>{const{scope:b,children:w}=x,C=qe.useRef(null),k=qe.useRef(new Map).current;return i.jsx(s,{scope:b,itemMap:k,collectionRef:C,children:w})};l.displayName=t;const u=e+"CollectionSlot",d=qe.forwardRef((x,b)=>{const{scope:w,children:C}=x,k=o(u,w),j=Rt(b,k.collectionRef);return i.jsx(No,{ref:j,children:C})});d.displayName=u;const f=e+"CollectionItemSlot",h="data-radix-collection-item",m=qe.forwardRef((x,b)=>{const{scope:w,children:C,...k}=x,j=qe.useRef(null),M=Rt(b,j),_=o(f,w);return qe.useEffect(()=>(_.itemMap.set(j,{ref:j,...k}),()=>void _.itemMap.delete(j))),i.jsx(No,{[h]:"",ref:M,children:C})});m.displayName=f;function g(x){const b=o(e+"CollectionConsumer",x);return qe.useCallback(()=>{const C=b.collectionRef.current;if(!C)return[];const k=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(b.itemMap.values()).sort((_,R)=>k.indexOf(_.ref.current)-k.indexOf(R.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:d,ItemSlot:m},g,r]}var IB=y.createContext(void 0);function xd(e){const t=y.useContext(IB);return e||t||"ltr"}function AB(e,t=globalThis?.document){const n=Rn(e);y.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var DB="DismissableLayer",By="dismissableLayer.update",FB="dismissableLayer.pointerDownOutside",LB="dismissableLayer.focusOutside",qC,bT=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Mh=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:l,onDismiss:u,...d}=e,f=y.useContext(bT),[h,m]=y.useState(null),g=h?.ownerDocument??globalThis?.document,[,x]=y.useState({}),b=Rt(t,O=>m(O)),w=Array.from(f.layers),[C]=[...f.layersWithOutsidePointerEventsDisabled].slice(-1),k=w.indexOf(C),j=h?w.indexOf(h):-1,M=f.layersWithOutsidePointerEventsDisabled.size>0,_=j>=k,R=zB(O=>{const D=O.target,z=[...f.branches].some(Q=>Q.contains(D));!_||z||(s?.(O),l?.(O),O.defaultPrevented||u?.())},g),N=UB(O=>{const D=O.target;[...f.branches].some(Q=>Q.contains(D))||(o?.(O),l?.(O),O.defaultPrevented||u?.())},g);return AB(O=>{j===f.layers.size-1&&(r?.(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},g),y.useEffect(()=>{if(h)return n&&(f.layersWithOutsidePointerEventsDisabled.size===0&&(qC=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),f.layersWithOutsidePointerEventsDisabled.add(h)),f.layers.add(h),KC(),()=>{n&&f.layersWithOutsidePointerEventsDisabled.size===1&&(g.body.style.pointerEvents=qC)}},[h,g,n,f]),y.useEffect(()=>()=>{h&&(f.layers.delete(h),f.layersWithOutsidePointerEventsDisabled.delete(h),KC())},[h,f]),y.useEffect(()=>{const O=()=>x({});return document.addEventListener(By,O),()=>document.removeEventListener(By,O)},[]),i.jsx(rt.div,{...d,ref:b,style:{pointerEvents:M?_?"auto":"none":void 0,...e.style},onFocusCapture:Ue(e.onFocusCapture,N.onFocusCapture),onBlurCapture:Ue(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:Ue(e.onPointerDownCapture,R.onPointerDownCapture)})});Mh.displayName=DB;var $B="DismissableLayerBranch",BB=y.forwardRef((e,t)=>{const n=y.useContext(bT),r=y.useRef(null),s=Rt(t,r);return y.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),i.jsx(rt.div,{...e,ref:s})});BB.displayName=$B;function zB(e,t=globalThis?.document){const n=Rn(e),r=y.useRef(!1),s=y.useRef(()=>{});return y.useEffect(()=>{const o=u=>{if(u.target&&!r.current){let d=function(){xT(FB,n,f,{discrete:!0})};const f={originalEvent:u};u.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=d,t.addEventListener("click",s.current,{once:!0})):d()}else t.removeEventListener("click",s.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function UB(e,t=globalThis?.document){const n=Rn(e),r=y.useRef(!1);return y.useEffect(()=>{const s=o=>{o.target&&!r.current&&xT(LB,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function KC(){const e=new CustomEvent(By);document.dispatchEvent(e)}function xT(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?yT(s,o):s.dispatchEvent(o)}var xv=0;function Wb(){y.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??WC()),document.body.insertAdjacentElement("beforeend",e[1]??WC()),xv++,()=>{xv===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),xv--}},[])}function WC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var wv="focusScope.autoFocusOnMount",Sv="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},VB="FocusScope",_h=y.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...l}=e,[u,d]=y.useState(null),f=Rn(s),h=Rn(o),m=y.useRef(null),g=Rt(t,w=>d(w)),x=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(r){let w=function(M){if(x.paused||!u)return;const _=M.target;u.contains(_)?m.current=_:fa(m.current,{select:!0})},C=function(M){if(x.paused||!u)return;const _=M.relatedTarget;_!==null&&(u.contains(_)||fa(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const R of M)R.removedNodes.length>0&&fa(u)};document.addEventListener("focusin",w),document.addEventListener("focusout",C);const j=new MutationObserver(k);return u&&j.observe(u,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",w),document.removeEventListener("focusout",C),j.disconnect()}}},[r,u,x.paused]),y.useEffect(()=>{if(u){QC.add(x);const w=document.activeElement;if(!u.contains(w)){const k=new CustomEvent(wv,GC);u.addEventListener(wv,f),u.dispatchEvent(k),k.defaultPrevented||(HB(JB(wT(u)),{select:!0}),document.activeElement===w&&fa(u))}return()=>{u.removeEventListener(wv,f),setTimeout(()=>{const k=new CustomEvent(Sv,GC);u.addEventListener(Sv,h),u.dispatchEvent(k),k.defaultPrevented||fa(w??document.body,{select:!0}),u.removeEventListener(Sv,h),QC.remove(x)},0)}}},[u,f,h,x]);const b=y.useCallback(w=>{if(!n&&!r||x.paused)return;const C=w.key==="Tab"&&!w.altKey&&!w.ctrlKey&&!w.metaKey,k=document.activeElement;if(C&&k){const j=w.currentTarget,[M,_]=qB(j);M&&_?!w.shiftKey&&k===_?(w.preventDefault(),n&&fa(M,{select:!0})):w.shiftKey&&k===M&&(w.preventDefault(),n&&fa(_,{select:!0})):k===j&&w.preventDefault()}},[n,r,x.paused]);return i.jsx(rt.div,{tabIndex:-1,...l,ref:g,onKeyDown:b})});_h.displayName=VB;function HB(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(fa(r,{select:t}),document.activeElement!==n)return}function qB(e){const t=wT(e),n=JC(t,e),r=JC(t.reverse(),e);return[n,r]}function wT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function JC(e,t){for(const n of e)if(!KB(n,{upTo:t}))return n}function KB(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function WB(e){return e instanceof HTMLInputElement&&"select"in e}function fa(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&WB(e)&&t&&e.select()}}var QC=GB();function GB(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ZC(e,t),e.unshift(t)},remove(t){e=ZC(e,t),e[0]?.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function JB(e){return e.filter(t=>t.tagName!=="A")}var Ln=globalThis?.document?y.useLayoutEffect:()=>{},QB=Yl.useId||(()=>{}),ZB=0;function Es(e){const[t,n]=y.useState(QB());return Ln(()=>{n(r=>r??String(ZB++))},[e]),t?`radix-${t}`:""}const YB=["top","right","bottom","left"],Hs=Math.min,zr=Math.max,Dp=Math.round,Uf=Math.floor,ba=e=>({x:e,y:e}),XB={left:"right",right:"left",bottom:"top",top:"bottom"},e3={start:"end",end:"start"};function zy(e,t,n){return zr(e,Hs(t,n))}function Mo(e,t){return typeof e=="function"?e(t):e}function _o(e){return e.split("-")[0]}function oc(e){return e.split("-")[1]}function Gb(e){return e==="x"?"y":"x"}function Jb(e){return e==="y"?"height":"width"}function xa(e){return["top","bottom"].includes(_o(e))?"y":"x"}function Qb(e){return Gb(xa(e))}function t3(e,t,n){n===void 0&&(n=!1);const r=oc(e),s=Qb(e),o=Jb(s);let l=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(l=Fp(l)),[l,Fp(l)]}function n3(e){const t=Fp(e);return[Uy(e),t,Uy(t)]}function Uy(e){return e.replace(/start|end/g,t=>e3[t])}function r3(e,t,n){const r=["left","right"],s=["right","left"],o=["top","bottom"],l=["bottom","top"];switch(e){case"top":case"bottom":return n?t?s:r:t?r:s;case"left":case"right":return t?o:l;default:return[]}}function s3(e,t,n,r){const s=oc(e);let o=r3(_o(e),n==="start",r);return s&&(o=o.map(l=>l+"-"+s),t&&(o=o.concat(o.map(Uy)))),o}function Fp(e){return e.replace(/left|right|bottom|top/g,t=>XB[t])}function o3(e){return{top:0,right:0,bottom:0,left:0,...e}}function ST(e){return typeof e!="number"?o3(e):{top:e,right:e,bottom:e,left:e}}function Lp(e){const{x:t,y:n,width:r,height:s}=e;return{width:r,height:s,top:n,left:t,right:t+r,bottom:n+s,x:t,y:n}}function YC(e,t,n){let{reference:r,floating:s}=e;const o=xa(t),l=Qb(t),u=Jb(l),d=_o(t),f=o==="y",h=r.x+r.width/2-s.width/2,m=r.y+r.height/2-s.height/2,g=r[u]/2-s[u]/2;let x;switch(d){case"top":x={x:h,y:r.y-s.height};break;case"bottom":x={x:h,y:r.y+r.height};break;case"right":x={x:r.x+r.width,y:m};break;case"left":x={x:r.x-s.width,y:m};break;default:x={x:r.x,y:r.y}}switch(oc(t)){case"start":x[l]-=g*(n&&f?-1:1);break;case"end":x[l]+=g*(n&&f?-1:1);break}return x}const a3=async(e,t,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:l}=n,u=o.filter(Boolean),d=await(l.isRTL==null?void 0:l.isRTL(t));let f=await l.getElementRects({reference:e,floating:t,strategy:s}),{x:h,y:m}=YC(f,r,d),g=r,x={},b=0;for(let w=0;w({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:o,platform:l,elements:u,middlewareData:d}=t,{element:f,padding:h=0}=Mo(e,t)||{};if(f==null)return{};const m=ST(h),g={x:n,y:r},x=Qb(s),b=Jb(x),w=await l.getDimensions(f),C=x==="y",k=C?"top":"left",j=C?"bottom":"right",M=C?"clientHeight":"clientWidth",_=o.reference[b]+o.reference[x]-g[x]-o.floating[b],R=g[x]-o.reference[x],N=await(l.getOffsetParent==null?void 0:l.getOffsetParent(f));let O=N?N[M]:0;(!O||!await(l.isElement==null?void 0:l.isElement(N)))&&(O=u.floating[M]||o.floating[b]);const D=_/2-R/2,z=O/2-w[b]/2-1,Q=Hs(m[k],z),pe=Hs(m[j],z),V=Q,G=O-w[b]-pe,W=O/2-w[b]/2+D,ie=zy(V,W,G),re=!d.arrow&&oc(s)!=null&&W!==ie&&o.reference[b]/2-(WW<=0)){var pe,V;const W=(((pe=o.flip)==null?void 0:pe.index)||0)+1,ie=O[W];if(ie)return{data:{index:W,overflows:Q},reset:{placement:ie}};let re=(V=Q.filter(Y=>Y.overflows[0]<=0).sort((Y,H)=>Y.overflows[1]-H.overflows[1])[0])==null?void 0:V.placement;if(!re)switch(x){case"bestFit":{var G;const Y=(G=Q.filter(H=>{if(N){const q=xa(H.placement);return q===j||q==="y"}return!0}).map(H=>[H.placement,H.overflows.filter(q=>q>0).reduce((q,he)=>q+he,0)]).sort((H,q)=>H[1]-q[1])[0])==null?void 0:G[0];Y&&(re=Y);break}case"initialPlacement":re=u;break}if(s!==re)return{reset:{placement:re}}}return{}}}};function XC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function e1(e){return YB.some(t=>e[t]>=0)}const c3=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...s}=Mo(e,t);switch(r){case"referenceHidden":{const o=await Bu(t,{...s,elementContext:"reference"}),l=XC(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:e1(l)}}}case"escaped":{const o=await Bu(t,{...s,altBoundary:!0}),l=XC(o,n.floating);return{data:{escapedOffsets:l,escaped:e1(l)}}}default:return{}}}}};async function u3(e,t){const{placement:n,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),l=_o(n),u=oc(n),d=xa(n)==="y",f=["left","top"].includes(l)?-1:1,h=o&&d?-1:1,m=Mo(t,e);let{mainAxis:g,crossAxis:x,alignmentAxis:b}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return u&&typeof b=="number"&&(x=u==="end"?b*-1:b),d?{x:x*h,y:g*f}:{x:g*f,y:x*h}}const d3=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:s,y:o,placement:l,middlewareData:u}=t,d=await u3(t,e);return l===((n=u.offset)==null?void 0:n.placement)&&(r=u.arrow)!=null&&r.alignmentOffset?{}:{x:s+d.x,y:o+d.y,data:{...d,placement:l}}}}},f3=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:s}=t,{mainAxis:o=!0,crossAxis:l=!1,limiter:u={fn:C=>{let{x:k,y:j}=C;return{x:k,y:j}}},...d}=Mo(e,t),f={x:n,y:r},h=await Bu(t,d),m=xa(_o(s)),g=Gb(m);let x=f[g],b=f[m];if(o){const C=g==="y"?"top":"left",k=g==="y"?"bottom":"right",j=x+h[C],M=x-h[k];x=zy(j,x,M)}if(l){const C=m==="y"?"top":"left",k=m==="y"?"bottom":"right",j=b+h[C],M=b-h[k];b=zy(j,b,M)}const w=u.fn({...t,[g]:x,[m]:b});return{...w,data:{x:w.x-n,y:w.y-r}}}}},p3=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:s,rects:o,middlewareData:l}=t,{offset:u=0,mainAxis:d=!0,crossAxis:f=!0}=Mo(e,t),h={x:n,y:r},m=xa(s),g=Gb(m);let x=h[g],b=h[m];const w=Mo(u,t),C=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(d){const M=g==="y"?"height":"width",_=o.reference[g]-o.floating[M]+C.mainAxis,R=o.reference[g]+o.reference[M]-C.mainAxis;x<_?x=_:x>R&&(x=R)}if(f){var k,j;const M=g==="y"?"width":"height",_=["top","left"].includes(_o(s)),R=o.reference[m]-o.floating[M]+(_&&((k=l.offset)==null?void 0:k[m])||0)+(_?0:C.crossAxis),N=o.reference[m]+o.reference[M]+(_?0:((j=l.offset)==null?void 0:j[m])||0)-(_?C.crossAxis:0);bN&&(b=N)}return{[g]:x,[m]:b}}}},h3=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:s,elements:o}=t,{apply:l=()=>{},...u}=Mo(e,t),d=await Bu(t,u),f=_o(n),h=oc(n),m=xa(n)==="y",{width:g,height:x}=r.floating;let b,w;f==="top"||f==="bottom"?(b=f,w=h===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(w=f,b=h==="end"?"top":"bottom");const C=x-d.top-d.bottom,k=g-d.left-d.right,j=Hs(x-d[b],C),M=Hs(g-d[w],k),_=!t.middlewareData.shift;let R=j,N=M;if(m?N=h||_?Hs(M,k):k:R=h||_?Hs(j,C):C,_&&!h){const D=zr(d.left,0),z=zr(d.right,0),Q=zr(d.top,0),pe=zr(d.bottom,0);m?N=g-2*(D!==0||z!==0?D+z:zr(d.left,d.right)):R=x-2*(Q!==0||pe!==0?Q+pe:zr(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:R});const O=await s.getDimensions(o.floating);return g!==O.width||x!==O.height?{reset:{rects:!0}}:{}}}};function ac(e){return CT(e)?(e.nodeName||"").toLowerCase():"#document"}function Vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Io(e){var t;return(t=(CT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function CT(e){return e instanceof Node||e instanceof Vr(e).Node}function Gs(e){return e instanceof Element||e instanceof Vr(e).Element}function Js(e){return e instanceof HTMLElement||e instanceof Vr(e).HTMLElement}function t1(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Vr(e).ShadowRoot}function wd(e){const{overflow:t,overflowX:n,overflowY:r,display:s}=Ns(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(s)}function g3(e){return["table","td","th"].includes(ac(e))}function Rh(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function Zb(e){const t=Yb(),n=Ns(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function m3(e){let t=wa(e);for(;Js(t)&&!zl(t);){if(Rh(t))return null;if(Zb(t))return t;t=wa(t)}return null}function Yb(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function zl(e){return["html","body","#document"].includes(ac(e))}function Ns(e){return Vr(e).getComputedStyle(e)}function Ph(e){return Gs(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function wa(e){if(ac(e)==="html")return e;const t=e.assignedSlot||e.parentNode||t1(e)&&e.host||Io(e);return t1(t)?t.host:t}function ET(e){const t=wa(e);return zl(t)?e.ownerDocument?e.ownerDocument.body:e.body:Js(t)&&wd(t)?t:ET(t)}function zu(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const s=ET(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),l=Vr(s);return o?t.concat(l,l.visualViewport||[],wd(s)?s:[],l.frameElement&&n?zu(l.frameElement):[]):t.concat(s,zu(s,[],n))}function kT(e){const t=Ns(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Js(e),o=s?e.offsetWidth:n,l=s?e.offsetHeight:r,u=Dp(n)!==o||Dp(r)!==l;return u&&(n=o,r=l),{width:n,height:r,$:u}}function Xb(e){return Gs(e)?e:e.contextElement}function Rl(e){const t=Xb(e);if(!Js(t))return ba(1);const n=t.getBoundingClientRect(),{width:r,height:s,$:o}=kT(t);let l=(o?Dp(n.width):n.width)/r,u=(o?Dp(n.height):n.height)/s;return(!l||!Number.isFinite(l))&&(l=1),(!u||!Number.isFinite(u))&&(u=1),{x:l,y:u}}const v3=ba(0);function jT(e){const t=Vr(e);return!Yb()||!t.visualViewport?v3:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function y3(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Vr(e)?!1:t}function Ci(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const s=e.getBoundingClientRect(),o=Xb(e);let l=ba(1);t&&(r?Gs(r)&&(l=Rl(r)):l=Rl(e));const u=y3(o,n,r)?jT(o):ba(0);let d=(s.left+u.x)/l.x,f=(s.top+u.y)/l.y,h=s.width/l.x,m=s.height/l.y;if(o){const g=Vr(o),x=r&&Gs(r)?Vr(r):r;let b=g,w=b.frameElement;for(;w&&r&&x!==b;){const C=Rl(w),k=w.getBoundingClientRect(),j=Ns(w),M=k.left+(w.clientLeft+parseFloat(j.paddingLeft))*C.x,_=k.top+(w.clientTop+parseFloat(j.paddingTop))*C.y;d*=C.x,f*=C.y,h*=C.x,m*=C.y,d+=M,f+=_,b=Vr(w),w=b.frameElement}}return Lp({width:h,height:m,x:d,y:f})}function b3(e){let{elements:t,rect:n,offsetParent:r,strategy:s}=e;const o=s==="fixed",l=Io(r),u=t?Rh(t.floating):!1;if(r===l||u&&o)return n;let d={scrollLeft:0,scrollTop:0},f=ba(1);const h=ba(0),m=Js(r);if((m||!m&&!o)&&((ac(r)!=="body"||wd(l))&&(d=Ph(r)),Js(r))){const g=Ci(r);f=Rl(r),h.x=g.x+r.clientLeft,h.y=g.y+r.clientTop}return{width:n.width*f.x,height:n.height*f.y,x:n.x*f.x-d.scrollLeft*f.x+h.x,y:n.y*f.y-d.scrollTop*f.y+h.y}}function x3(e){return Array.from(e.getClientRects())}function TT(e){return Ci(Io(e)).left+Ph(e).scrollLeft}function w3(e){const t=Io(e),n=Ph(e),r=e.ownerDocument.body,s=zr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=zr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+TT(e);const u=-n.scrollTop;return Ns(r).direction==="rtl"&&(l+=zr(t.clientWidth,r.clientWidth)-s),{width:s,height:o,x:l,y:u}}function S3(e,t){const n=Vr(e),r=Io(e),s=n.visualViewport;let o=r.clientWidth,l=r.clientHeight,u=0,d=0;if(s){o=s.width,l=s.height;const f=Yb();(!f||f&&t==="fixed")&&(u=s.offsetLeft,d=s.offsetTop)}return{width:o,height:l,x:u,y:d}}function C3(e,t){const n=Ci(e,!0,t==="fixed"),r=n.top+e.clientTop,s=n.left+e.clientLeft,o=Js(e)?Rl(e):ba(1),l=e.clientWidth*o.x,u=e.clientHeight*o.y,d=s*o.x,f=r*o.y;return{width:l,height:u,x:d,y:f}}function n1(e,t,n){let r;if(t==="viewport")r=S3(e,n);else if(t==="document")r=w3(Io(e));else if(Gs(t))r=C3(t,n);else{const s=jT(e);r={...t,x:t.x-s.x,y:t.y-s.y}}return Lp(r)}function NT(e,t){const n=wa(e);return n===t||!Gs(n)||zl(n)?!1:Ns(n).position==="fixed"||NT(n,t)}function E3(e,t){const n=t.get(e);if(n)return n;let r=zu(e,[],!1).filter(u=>Gs(u)&&ac(u)!=="body"),s=null;const o=Ns(e).position==="fixed";let l=o?wa(e):e;for(;Gs(l)&&!zl(l);){const u=Ns(l),d=Zb(l);!d&&u.position==="fixed"&&(s=null),(o?!d&&!s:!d&&u.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||wd(l)&&!d&&NT(e,l))?r=r.filter(h=>h!==l):s=u,l=wa(l)}return t.set(e,r),r}function k3(e){let{element:t,boundary:n,rootBoundary:r,strategy:s}=e;const l=[...n==="clippingAncestors"?Rh(t)?[]:E3(t,this._c):[].concat(n),r],u=l[0],d=l.reduce((f,h)=>{const m=n1(t,h,s);return f.top=zr(m.top,f.top),f.right=Hs(m.right,f.right),f.bottom=Hs(m.bottom,f.bottom),f.left=zr(m.left,f.left),f},n1(t,u,s));return{width:d.right-d.left,height:d.bottom-d.top,x:d.left,y:d.top}}function j3(e){const{width:t,height:n}=kT(e);return{width:t,height:n}}function T3(e,t,n){const r=Js(t),s=Io(t),o=n==="fixed",l=Ci(e,!0,o,t);let u={scrollLeft:0,scrollTop:0};const d=ba(0);if(r||!r&&!o)if((ac(t)!=="body"||wd(s))&&(u=Ph(t)),r){const m=Ci(t,!0,o,t);d.x=m.x+t.clientLeft,d.y=m.y+t.clientTop}else s&&(d.x=TT(s));const f=l.left+u.scrollLeft-d.x,h=l.top+u.scrollTop-d.y;return{x:f,y:h,width:l.width,height:l.height}}function Cv(e){return Ns(e).position==="static"}function r1(e,t){return!Js(e)||Ns(e).position==="fixed"?null:t?t(e):e.offsetParent}function MT(e,t){const n=Vr(e);if(Rh(e))return n;if(!Js(e)){let s=wa(e);for(;s&&!zl(s);){if(Gs(s)&&!Cv(s))return s;s=wa(s)}return n}let r=r1(e,t);for(;r&&g3(r)&&Cv(r);)r=r1(r,t);return r&&zl(r)&&Cv(r)&&!Zb(r)?n:r||m3(e)||n}const N3=async function(e){const t=this.getOffsetParent||MT,n=this.getDimensions,r=await n(e.floating);return{reference:T3(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function M3(e){return Ns(e).direction==="rtl"}const _3={convertOffsetParentRelativeRectToViewportRelativeRect:b3,getDocumentElement:Io,getClippingRect:k3,getOffsetParent:MT,getElementRects:N3,getClientRects:x3,getDimensions:j3,getScale:Rl,isElement:Gs,isRTL:M3};function R3(e,t){let n=null,r;const s=Io(e);function o(){var u;clearTimeout(r),(u=n)==null||u.disconnect(),n=null}function l(u,d){u===void 0&&(u=!1),d===void 0&&(d=1),o();const{left:f,top:h,width:m,height:g}=e.getBoundingClientRect();if(u||t(),!m||!g)return;const x=Uf(h),b=Uf(s.clientWidth-(f+m)),w=Uf(s.clientHeight-(h+g)),C=Uf(f),j={rootMargin:-x+"px "+-b+"px "+-w+"px "+-C+"px",threshold:zr(0,Hs(1,d))||1};let M=!0;function _(R){const N=R[0].intersectionRatio;if(N!==d){if(!M)return l();N?l(!1,N):r=setTimeout(()=>{l(!1,1e-7)},1e3)}M=!1}try{n=new IntersectionObserver(_,{...j,root:s.ownerDocument})}catch{n=new IntersectionObserver(_,j)}n.observe(e)}return l(!0),o}function _T(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:u=typeof IntersectionObserver=="function",animationFrame:d=!1}=r,f=Xb(e),h=s||o?[...f?zu(f):[],...zu(t)]:[];h.forEach(k=>{s&&k.addEventListener("scroll",n,{passive:!0}),o&&k.addEventListener("resize",n)});const m=f&&u?R3(f,n):null;let g=-1,x=null;l&&(x=new ResizeObserver(k=>{let[j]=k;j&&j.target===f&&x&&(x.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{var M;(M=x)==null||M.observe(t)})),n()}),f&&!d&&x.observe(f),x.observe(t));let b,w=d?Ci(e):null;d&&C();function C(){const k=Ci(e);w&&(k.x!==w.x||k.y!==w.y||k.width!==w.width||k.height!==w.height)&&n(),w=k,b=requestAnimationFrame(C)}return n(),()=>{var k;h.forEach(j=>{s&&j.removeEventListener("scroll",n),o&&j.removeEventListener("resize",n)}),m?.(),(k=x)==null||k.disconnect(),x=null,d&&cancelAnimationFrame(b)}}const P3=d3,O3=f3,I3=l3,A3=h3,D3=c3,s1=i3,F3=p3,L3=(e,t,n)=>{const r=new Map,s={platform:_3,...n},o={...s.platform,_c:r};return a3(e,t,{...s,platform:o})};var hp=typeof document<"u"?y.useLayoutEffect:y.useEffect;function $p(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,s;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!$p(e[r],t[r]))return!1;return!0}if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,s[r]))return!1;for(r=n;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!$p(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function RT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function o1(e,t){const n=RT(e);return Math.round(t*n)/n}function a1(e){const t=y.useRef(e);return hp(()=>{t.current=e}),t}function PT(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:l}={},transform:u=!0,whileElementsMounted:d,open:f}=e,[h,m]=y.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,x]=y.useState(r);$p(g,r)||x(r);const[b,w]=y.useState(null),[C,k]=y.useState(null),j=y.useCallback(Y=>{Y!==N.current&&(N.current=Y,w(Y))},[]),M=y.useCallback(Y=>{Y!==O.current&&(O.current=Y,k(Y))},[]),_=o||b,R=l||C,N=y.useRef(null),O=y.useRef(null),D=y.useRef(h),z=d!=null,Q=a1(d),pe=a1(s),V=y.useCallback(()=>{if(!N.current||!O.current)return;const Y={placement:t,strategy:n,middleware:g};pe.current&&(Y.platform=pe.current),L3(N.current,O.current,Y).then(H=>{const q={...H,isPositioned:!0};G.current&&!$p(D.current,q)&&(D.current=q,Ma.flushSync(()=>{m(q)}))})},[g,t,n,pe]);hp(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(Y=>({...Y,isPositioned:!1})))},[f]);const G=y.useRef(!1);hp(()=>(G.current=!0,()=>{G.current=!1}),[]),hp(()=>{if(_&&(N.current=_),R&&(O.current=R),_&&R){if(Q.current)return Q.current(_,R,V);V()}},[_,R,V,Q,z]);const W=y.useMemo(()=>({reference:N,floating:O,setReference:j,setFloating:M}),[j,M]),ie=y.useMemo(()=>({reference:_,floating:R}),[_,R]),re=y.useMemo(()=>{const Y={position:n,left:0,top:0};if(!ie.floating)return Y;const H=o1(ie.floating,h.x),q=o1(ie.floating,h.y);return u?{...Y,transform:"translate("+H+"px, "+q+"px)",...RT(ie.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:q}},[n,u,ie.floating,h.x,h.y]);return y.useMemo(()=>({...h,update:V,refs:W,elements:ie,floatingStyles:re}),[h,V,W,ie,re])}const $3=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:s}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?s1({element:r.current,padding:s}).fn(n):{}:r?s1({element:r,padding:s}).fn(n):{}}}},OT=(e,t)=>({...P3(e),options:[e,t]}),IT=(e,t)=>({...O3(e),options:[e,t]}),AT=(e,t)=>({...F3(e),options:[e,t]}),DT=(e,t)=>({...I3(e),options:[e,t]}),FT=(e,t)=>({...A3(e),options:[e,t]}),LT=(e,t)=>({...D3(e),options:[e,t]}),$T=(e,t)=>({...$3(e),options:[e,t]});var B3="Arrow",BT=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return i.jsx(rt.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:i.jsx("polygon",{points:"0,0 30,0 15,10"})})});BT.displayName=B3;var z3=BT;function zT(e){const[t,n]=y.useState(void 0);return Ln(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let l,u;if("borderBoxSize"in o){const d=o.borderBoxSize,f=Array.isArray(d)?d[0]:d;l=f.inlineSize,u=f.blockSize}else l=e.offsetWidth,u=e.offsetHeight;n({width:l,height:u})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var ex="Popper",[UT,Oh]=us(ex),[U3,VT]=UT(ex),HT=e=>{const{__scopePopper:t,children:n}=e,[r,s]=y.useState(null);return i.jsx(U3,{scope:t,anchor:r,onAnchorChange:s,children:n})};HT.displayName=ex;var qT="PopperAnchor",KT=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=VT(qT,n),l=y.useRef(null),u=Rt(t,l);return y.useEffect(()=>{o.onAnchorChange(r?.current||l.current)}),r?null:i.jsx(rt.div,{...s,ref:u})});KT.displayName=qT;var tx="PopperContent",[V3,H3]=UT(tx),WT=y.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:l=0,arrowPadding:u=0,avoidCollisions:d=!0,collisionBoundary:f=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:g=!1,updatePositionStrategy:x="optimized",onPlaced:b,...w}=e,C=VT(tx,n),[k,j]=y.useState(null),M=Rt(t,Z=>j(Z)),[_,R]=y.useState(null),N=zT(_),O=N?.width??0,D=N?.height??0,z=r+(o!=="center"?"-"+o:""),Q=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},pe=Array.isArray(f)?f:[f],V=pe.length>0,G={padding:Q,boundary:pe.filter(K3),altBoundary:V},{refs:W,floatingStyles:ie,placement:re,isPositioned:Y,middlewareData:H}=PT({strategy:"fixed",placement:z,whileElementsMounted:(...Z)=>_T(...Z,{animationFrame:x==="always"}),elements:{reference:C.anchor},middleware:[OT({mainAxis:s+D,alignmentAxis:l}),d&&IT({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?AT():void 0,...G}),d&&DT({...G}),FT({...G,apply:({elements:Z,rects:ye,availableWidth:Re,availableHeight:$e})=>{const{width:Ye,height:Fe}=ye.reference,ft=Z.floating.style;ft.setProperty("--radix-popper-available-width",`${Re}px`),ft.setProperty("--radix-popper-available-height",`${$e}px`),ft.setProperty("--radix-popper-anchor-width",`${Ye}px`),ft.setProperty("--radix-popper-anchor-height",`${Fe}px`)}}),_&&$T({element:_,padding:u}),W3({arrowWidth:O,arrowHeight:D}),g&<({strategy:"referenceHidden",...G})]}),[q,he]=QT(re),A=Rn(b);Ln(()=>{Y&&A?.()},[Y,A]);const F=H.arrow?.x,fe=H.arrow?.y,te=H.arrow?.centerOffset!==0,[de,ge]=y.useState();return Ln(()=>{k&&ge(window.getComputedStyle(k).zIndex)},[k]),i.jsx("div",{ref:W.setFloating,"data-radix-popper-content-wrapper":"",style:{...ie,transform:Y?ie.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:de,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:i.jsx(V3,{scope:n,placedSide:q,onArrowChange:R,arrowX:F,arrowY:fe,shouldHideArrow:te,children:i.jsx(rt.div,{"data-side":q,"data-align":he,...w,ref:M,style:{...w.style,animation:Y?void 0:"none"}})})})});WT.displayName=tx;var GT="PopperArrow",q3={top:"bottom",right:"left",bottom:"top",left:"right"},JT=y.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=H3(GT,r),l=q3[o.placedSide];return i.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:i.jsx(z3,{...s,ref:n,style:{...s.style,display:"block"}})})});JT.displayName=GT;function K3(e){return e!==null}var W3=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:s}=t,l=s.arrow?.centerOffset!==0,u=l?0:e.arrowWidth,d=l?0:e.arrowHeight,[f,h]=QT(n),m={start:"0%",center:"50%",end:"100%"}[h],g=(s.arrow?.x??0)+u/2,x=(s.arrow?.y??0)+d/2;let b="",w="";return f==="bottom"?(b=l?m:`${g}px`,w=`${-d}px`):f==="top"?(b=l?m:`${g}px`,w=`${r.floating.height+d}px`):f==="right"?(b=`${-d}px`,w=l?m:`${x}px`):f==="left"&&(b=`${r.floating.width+d}px`,w=l?m:`${x}px`),{data:{x:b,y:w}}}});function QT(e){const[t,n="center"]=e.split("-");return[t,n]}var ZT=HT,YT=KT,XT=WT,eN=JT,G3="Portal",Ih=y.forwardRef((e,t)=>{const{container:n,...r}=e,[s,o]=y.useState(!1);Ln(()=>o(!0),[]);const l=n||s&&globalThis?.document?.body;return l?Ib.createPortal(i.jsx(rt.div,{...r,ref:t}),l):null});Ih.displayName=G3;function J3(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Mr=e=>{const{present:t,children:n}=e,r=Q3(t),s=typeof n=="function"?n({present:r.isPresent}):y.Children.only(n),o=Rt(r.ref,Z3(s));return typeof n=="function"||r.isPresent?y.cloneElement(s,{ref:o}):null};Mr.displayName="Presence";function Q3(e){const[t,n]=y.useState(),r=y.useRef({}),s=y.useRef(e),o=y.useRef("none"),l=e?"mounted":"unmounted",[u,d]=J3(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const f=Vf(r.current);o.current=u==="mounted"?f:"none"},[u]),Ln(()=>{const f=r.current,h=s.current;if(h!==e){const g=o.current,x=Vf(f);e?d("MOUNT"):x==="none"||f?.display==="none"?d("UNMOUNT"):d(h&&g!==x?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,d]),Ln(()=>{if(t){const f=m=>{const x=Vf(r.current).includes(m.animationName);m.target===t&&x&&Ma.flushSync(()=>d("ANIMATION_END"))},h=m=>{m.target===t&&(o.current=Vf(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:y.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function Vf(e){return e?.animationName||"none"}function Z3(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Ev="rovingFocusGroup.onEntryFocus",Y3={bubbles:!1,cancelable:!0},Ah="RovingFocusGroup",[Vy,tN,X3]=Kb(Ah),[ez,Dh]=us(Ah,[X3]),[tz,nz]=ez(Ah),nN=y.forwardRef((e,t)=>i.jsx(Vy.Provider,{scope:e.__scopeRovingFocusGroup,children:i.jsx(Vy.Slot,{scope:e.__scopeRovingFocusGroup,children:i.jsx(rz,{...e,ref:t})})}));nN.displayName=Ah;var rz=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:s=!1,dir:o,currentTabStopId:l,defaultCurrentTabStopId:u,onCurrentTabStopIdChange:d,onEntryFocus:f,preventScrollOnEntryFocus:h=!1,...m}=e,g=y.useRef(null),x=Rt(t,g),b=xd(o),[w=null,C]=ya({prop:l,defaultProp:u,onChange:d}),[k,j]=y.useState(!1),M=Rn(f),_=tN(n),R=y.useRef(!1),[N,O]=y.useState(0);return y.useEffect(()=>{const D=g.current;if(D)return D.addEventListener(Ev,M),()=>D.removeEventListener(Ev,M)},[M]),i.jsx(tz,{scope:n,orientation:r,dir:b,loop:s,currentTabStopId:w,onItemFocus:y.useCallback(D=>C(D),[C]),onItemShiftTab:y.useCallback(()=>j(!0),[]),onFocusableItemAdd:y.useCallback(()=>O(D=>D+1),[]),onFocusableItemRemove:y.useCallback(()=>O(D=>D-1),[]),children:i.jsx(rt.div,{tabIndex:k||N===0?-1:0,"data-orientation":r,...m,ref:x,style:{outline:"none",...e.style},onMouseDown:Ue(e.onMouseDown,()=>{R.current=!0}),onFocus:Ue(e.onFocus,D=>{const z=!R.current;if(D.target===D.currentTarget&&z&&!k){const Q=new CustomEvent(Ev,Y3);if(D.currentTarget.dispatchEvent(Q),!Q.defaultPrevented){const pe=_().filter(re=>re.focusable),V=pe.find(re=>re.active),G=pe.find(re=>re.id===w),ie=[V,G,...pe].filter(Boolean).map(re=>re.ref.current);oN(ie,h)}}R.current=!1}),onBlur:Ue(e.onBlur,()=>j(!1))})})}),rN="RovingFocusGroupItem",sN=y.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:s=!1,tabStopId:o,...l}=e,u=Es(),d=o||u,f=nz(rN,n),h=f.currentTabStopId===d,m=tN(n),{onFocusableItemAdd:g,onFocusableItemRemove:x}=f;return y.useEffect(()=>{if(r)return g(),()=>x()},[r,g,x]),i.jsx(Vy.ItemSlot,{scope:n,id:d,focusable:r,active:s,children:i.jsx(rt.span,{tabIndex:h?0:-1,"data-orientation":f.orientation,...l,ref:t,onMouseDown:Ue(e.onMouseDown,b=>{r?f.onItemFocus(d):b.preventDefault()}),onFocus:Ue(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Ue(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const w=az(b,f.orientation,f.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let k=m().filter(j=>j.focusable).map(j=>j.ref.current);if(w==="last")k.reverse();else if(w==="prev"||w==="next"){w==="prev"&&k.reverse();const j=k.indexOf(b.currentTarget);k=f.loop?iz(k,j+1):k.slice(j+1)}setTimeout(()=>oN(k))}})})})});sN.displayName=rN;var sz={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function oz(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function az(e,t,n){const r=oz(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return sz[r]}function oN(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function iz(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var aN=nN,iN=sN,lz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},pl=new WeakMap,Hf=new WeakMap,qf={},kv=0,lN=function(e){return e&&(e.host||lN(e.parentNode))},cz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lN(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},uz=function(e,t,n,r){var s=cz(t,Array.isArray(e)?e:[e]);qf[n]||(qf[n]=new WeakMap);var o=qf[n],l=[],u=new Set,d=new Set(s),f=function(m){!m||u.has(m)||(u.add(m),f(m.parentNode))};s.forEach(f);var h=function(m){!m||d.has(m)||Array.prototype.forEach.call(m.children,function(g){if(u.has(g))h(g);else try{var x=g.getAttribute(r),b=x!==null&&x!=="false",w=(pl.get(g)||0)+1,C=(o.get(g)||0)+1;pl.set(g,w),o.set(g,C),l.push(g),w===1&&b&&Hf.set(g,!0),C===1&&g.setAttribute(n,"true"),b||g.setAttribute(r,"true")}catch(k){console.error("aria-hidden: cannot operate on ",g,k)}})};return h(t),u.clear(),kv++,function(){l.forEach(function(m){var g=pl.get(m)-1,x=o.get(m)-1;pl.set(m,g),o.set(m,x),g||(Hf.has(m)||m.removeAttribute(r),Hf.delete(m)),x||m.removeAttribute(n)}),kv--,kv||(pl=new WeakMap,pl=new WeakMap,Hf=new WeakMap,qf={})}},nx=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=lz(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),uz(r,s,n,"aria-hidden")):function(){return null}},zs=function(){return zs=Object.assign||function(t){for(var n,r=1,s=arguments.length;r"u")return Tz;var t=Nz(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},_z=fN(),Pl="data-scroll-locked",Rz=function(e,t,n,r){var s=e.left,o=e.top,l=e.right,u=e.gap;return n===void 0&&(n="margin"),` + .`.concat(fz,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(u,"px ").concat(r,`; + } + body[`).concat(Pl,`] { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(s,`px; + padding-top: `).concat(o,`px; + padding-right: `).concat(l,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(u,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(u,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(gp,` { + right: `).concat(u,"px ").concat(r,`; + } + + .`).concat(mp,` { + margin-right: `).concat(u,"px ").concat(r,`; + } + + .`).concat(gp," .").concat(gp,` { + right: 0 `).concat(r,`; + } + + .`).concat(mp," .").concat(mp,` { + margin-right: 0 `).concat(r,`; + } + + body[`).concat(Pl,`] { + `).concat(pz,": ").concat(u,`px; + } +`)},l1=function(){var e=parseInt(document.body.getAttribute(Pl)||"0",10);return isFinite(e)?e:0},Pz=function(){y.useEffect(function(){return document.body.setAttribute(Pl,(l1()+1).toString()),function(){var e=l1()-1;e<=0?document.body.removeAttribute(Pl):document.body.setAttribute(Pl,e.toString())}},[])},Oz=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;Pz();var o=y.useMemo(function(){return Mz(s)},[s]);return y.createElement(_z,{styles:Rz(o,!t,s,n?"":"!important")})},Hy=!1;if(typeof window<"u")try{var Kf=Object.defineProperty({},"passive",{get:function(){return Hy=!0,!0}});window.addEventListener("test",Kf,Kf),window.removeEventListener("test",Kf,Kf)}catch{Hy=!1}var hl=Hy?{passive:!1}:!1,Iz=function(e){return e.tagName==="TEXTAREA"},pN=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Iz(e)&&n[t]==="visible")},Az=function(e){return pN(e,"overflowY")},Dz=function(e){return pN(e,"overflowX")},c1=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=hN(e,r);if(s){var o=gN(e,r),l=o[1],u=o[2];if(l>u)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Fz=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Lz=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},hN=function(e,t){return e==="v"?Az(t):Dz(t)},gN=function(e,t){return e==="v"?Fz(t):Lz(t)},$z=function(e,t){return e==="h"&&t==="rtl"?-1:1},Bz=function(e,t,n,r,s){var o=$z(e,window.getComputedStyle(t).direction),l=o*r,u=n.target,d=t.contains(u),f=!1,h=l>0,m=0,g=0;do{var x=gN(e,u),b=x[0],w=x[1],C=x[2],k=w-C-o*b;(b||k)&&hN(e,u)&&(m+=k,g+=b),u instanceof ShadowRoot?u=u.host:u=u.parentNode}while(!d&&u!==document.body||d&&(t.contains(u)||t===u));return(h&&Math.abs(m)<1||!h&&Math.abs(g)<1)&&(f=!0),f},Wf=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},u1=function(e){return[e.deltaX,e.deltaY]},d1=function(e){return e&&"current"in e?e.current:e},zz=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Uz=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},Vz=0,gl=[];function Hz(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),s=y.useState(Vz++)[0],o=y.useState(fN)[0],l=y.useRef(e);y.useEffect(function(){l.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var w=dz([e.lockRef.current],(e.shards||[]).map(d1),!0).filter(Boolean);return w.forEach(function(C){return C.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),w.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var u=y.useCallback(function(w,C){if("touches"in w&&w.touches.length===2)return!l.current.allowPinchZoom;var k=Wf(w),j=n.current,M="deltaX"in w?w.deltaX:j[0]-k[0],_="deltaY"in w?w.deltaY:j[1]-k[1],R,N=w.target,O=Math.abs(M)>Math.abs(_)?"h":"v";if("touches"in w&&O==="h"&&N.type==="range")return!1;var D=c1(O,N);if(!D)return!0;if(D?R=O:(R=O==="v"?"h":"v",D=c1(O,N)),!D)return!1;if(!r.current&&"changedTouches"in w&&(M||_)&&(r.current=R),!R)return!0;var z=r.current||R;return Bz(z,C,w,z==="h"?M:_)},[]),d=y.useCallback(function(w){var C=w;if(!(!gl.length||gl[gl.length-1]!==o)){var k="deltaY"in C?u1(C):Wf(C),j=t.current.filter(function(R){return R.name===C.type&&(R.target===C.target||C.target===R.shadowParent)&&zz(R.delta,k)})[0];if(j&&j.should){C.cancelable&&C.preventDefault();return}if(!j){var M=(l.current.shards||[]).map(d1).filter(Boolean).filter(function(R){return R.contains(C.target)}),_=M.length>0?u(C,M[0]):!l.current.noIsolation;_&&C.cancelable&&C.preventDefault()}}},[]),f=y.useCallback(function(w,C,k,j){var M={name:w,delta:C,target:k,should:j,shadowParent:qz(k)};t.current.push(M),setTimeout(function(){t.current=t.current.filter(function(_){return _!==M})},1)},[]),h=y.useCallback(function(w){n.current=Wf(w),r.current=void 0},[]),m=y.useCallback(function(w){f(w.type,u1(w),w.target,u(w,e.lockRef.current))},[]),g=y.useCallback(function(w){f(w.type,Wf(w),w.target,u(w,e.lockRef.current))},[]);y.useEffect(function(){return gl.push(o),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",d,hl),document.addEventListener("touchmove",d,hl),document.addEventListener("touchstart",h,hl),function(){gl=gl.filter(function(w){return w!==o}),document.removeEventListener("wheel",d,hl),document.removeEventListener("touchmove",d,hl),document.removeEventListener("touchstart",h,hl)}},[]);var x=e.removeScrollBar,b=e.inert;return y.createElement(y.Fragment,null,b?y.createElement(o,{styles:Uz(s)}):null,x?y.createElement(Oz,{gapMode:e.gapMode}):null)}function qz(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Kz=xz(dN,Hz);var Lh=y.forwardRef(function(e,t){return y.createElement(Fh,zs({},e,{ref:t,sideCar:Kz}))});Lh.classNames=Fh.classNames;var qy=["Enter"," "],Wz=["ArrowDown","PageUp","Home"],mN=["ArrowUp","PageDown","End"],Gz=[...Wz,...mN],Jz={ltr:[...qy,"ArrowRight"],rtl:[...qy,"ArrowLeft"]},Qz={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Sd="Menu",[Uu,Zz,Yz]=Kb(Sd),[$i,vN]=us(Sd,[Yz,Oh,Dh]),$h=Oh(),yN=Dh(),[Xz,Bi]=$i(Sd),[eU,Cd]=$i(Sd),bN=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:s,onOpenChange:o,modal:l=!0}=e,u=$h(t),[d,f]=y.useState(null),h=y.useRef(!1),m=Rn(o),g=xd(s);return y.useEffect(()=>{const x=()=>{h.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>h.current=!1;return document.addEventListener("keydown",x,{capture:!0}),()=>{document.removeEventListener("keydown",x,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),i.jsx(ZT,{...u,children:i.jsx(Xz,{scope:t,open:n,onOpenChange:m,content:d,onContentChange:f,children:i.jsx(eU,{scope:t,onClose:y.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:l,children:r})})})};bN.displayName=Sd;var tU="MenuAnchor",rx=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=$h(n);return i.jsx(YT,{...s,...r,ref:t})});rx.displayName=tU;var sx="MenuPortal",[nU,xN]=$i(sx,{forceMount:void 0}),wN=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:s}=e,o=Bi(sx,t);return i.jsx(nU,{scope:t,forceMount:n,children:i.jsx(Mr,{present:n||o.open,children:i.jsx(Ih,{asChild:!0,container:s,children:r})})})};wN.displayName=sx;var is="MenuContent",[rU,ox]=$i(is),SN=y.forwardRef((e,t)=>{const n=xN(is,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Bi(is,e.__scopeMenu),l=Cd(is,e.__scopeMenu);return i.jsx(Uu.Provider,{scope:e.__scopeMenu,children:i.jsx(Mr,{present:r||o.open,children:i.jsx(Uu.Slot,{scope:e.__scopeMenu,children:l.modal?i.jsx(sU,{...s,ref:t}):i.jsx(oU,{...s,ref:t})})})})}),sU=y.forwardRef((e,t)=>{const n=Bi(is,e.__scopeMenu),r=y.useRef(null),s=Rt(t,r);return y.useEffect(()=>{const o=r.current;if(o)return nx(o)},[]),i.jsx(ax,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),oU=y.forwardRef((e,t)=>{const n=Bi(is,e.__scopeMenu);return i.jsx(ax,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),ax=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:l,disableOutsidePointerEvents:u,onEntryFocus:d,onEscapeKeyDown:f,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:x,disableOutsideScroll:b,...w}=e,C=Bi(is,n),k=Cd(is,n),j=$h(n),M=yN(n),_=Zz(n),[R,N]=y.useState(null),O=y.useRef(null),D=Rt(t,O,C.onContentChange),z=y.useRef(0),Q=y.useRef(""),pe=y.useRef(0),V=y.useRef(null),G=y.useRef("right"),W=y.useRef(0),ie=b?Lh:y.Fragment,re=b?{as:No,allowPinchZoom:!0}:void 0,Y=q=>{const he=Q.current+q,A=_().filter(Z=>!Z.disabled),F=document.activeElement,fe=A.find(Z=>Z.ref.current===F)?.textValue,te=A.map(Z=>Z.textValue),de=vU(te,he,fe),ge=A.find(Z=>Z.textValue===de)?.ref.current;(function Z(ye){Q.current=ye,window.clearTimeout(z.current),ye!==""&&(z.current=window.setTimeout(()=>Z(""),1e3))})(he),ge&&setTimeout(()=>ge.focus())};y.useEffect(()=>()=>window.clearTimeout(z.current),[]),Wb();const H=y.useCallback(q=>G.current===V.current?.side&&bU(q,V.current?.area),[]);return i.jsx(rU,{scope:n,searchRef:Q,onItemEnter:y.useCallback(q=>{H(q)&&q.preventDefault()},[H]),onItemLeave:y.useCallback(q=>{H(q)||(O.current?.focus(),N(null))},[H]),onTriggerLeave:y.useCallback(q=>{H(q)&&q.preventDefault()},[H]),pointerGraceTimerRef:pe,onPointerGraceIntentChange:y.useCallback(q=>{V.current=q},[]),children:i.jsx(ie,{...re,children:i.jsx(_h,{asChild:!0,trapped:s,onMountAutoFocus:Ue(o,q=>{q.preventDefault(),O.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:i.jsx(Mh,{asChild:!0,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:x,children:i.jsx(aN,{asChild:!0,...M,dir:k.dir,orientation:"vertical",loop:r,currentTabStopId:R,onCurrentTabStopIdChange:N,onEntryFocus:Ue(d,q=>{k.isUsingKeyboardRef.current||q.preventDefault()}),preventScrollOnEntryFocus:!0,children:i.jsx(XT,{role:"menu","aria-orientation":"vertical","data-state":LN(C.open),"data-radix-menu-content":"",dir:k.dir,...j,...w,ref:D,style:{outline:"none",...w.style},onKeyDown:Ue(w.onKeyDown,q=>{const A=q.target.closest("[data-radix-menu-content]")===q.currentTarget,F=q.ctrlKey||q.altKey||q.metaKey,fe=q.key.length===1;A&&(q.key==="Tab"&&q.preventDefault(),!F&&fe&&Y(q.key));const te=O.current;if(q.target!==te||!Gz.includes(q.key))return;q.preventDefault();const ge=_().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);mN.includes(q.key)&&ge.reverse(),gU(ge)}),onBlur:Ue(e.onBlur,q=>{q.currentTarget.contains(q.target)||(window.clearTimeout(z.current),Q.current="")}),onPointerMove:Ue(e.onPointerMove,Vu(q=>{const he=q.target,A=W.current!==q.clientX;if(q.currentTarget.contains(he)&&A){const F=q.clientX>W.current?"right":"left";G.current=F,W.current=q.clientX}}))})})})})})})});SN.displayName=is;var aU="MenuGroup",ix=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(rt.div,{role:"group",...r,ref:t})});ix.displayName=aU;var iU="MenuLabel",CN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(rt.div,{...r,ref:t})});CN.displayName=iU;var Bp="MenuItem",f1="menu.itemSelect",Bh=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...s}=e,o=y.useRef(null),l=Cd(Bp,e.__scopeMenu),u=ox(Bp,e.__scopeMenu),d=Rt(t,o),f=y.useRef(!1),h=()=>{const m=o.current;if(!n&&m){const g=new CustomEvent(f1,{bubbles:!0,cancelable:!0});m.addEventListener(f1,x=>r?.(x),{once:!0}),yT(m,g),g.defaultPrevented?f.current=!1:l.onClose()}};return i.jsx(EN,{...s,ref:d,disabled:n,onClick:Ue(e.onClick,h),onPointerDown:m=>{e.onPointerDown?.(m),f.current=!0},onPointerUp:Ue(e.onPointerUp,m=>{f.current||m.currentTarget?.click()}),onKeyDown:Ue(e.onKeyDown,m=>{const g=u.searchRef.current!=="";n||g&&m.key===" "||qy.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});Bh.displayName=Bp;var EN=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:s,...o}=e,l=ox(Bp,n),u=yN(n),d=y.useRef(null),f=Rt(t,d),[h,m]=y.useState(!1),[g,x]=y.useState("");return y.useEffect(()=>{const b=d.current;b&&x((b.textContent??"").trim())},[o.children]),i.jsx(Uu.ItemSlot,{scope:n,disabled:r,textValue:s??g,children:i.jsx(iN,{asChild:!0,...u,focusable:!r,children:i.jsx(rt.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:f,onPointerMove:Ue(e.onPointerMove,Vu(b=>{r?l.onItemLeave(b):(l.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ue(e.onPointerLeave,Vu(b=>l.onItemLeave(b))),onFocus:Ue(e.onFocus,()=>m(!0)),onBlur:Ue(e.onBlur,()=>m(!1))})})})}),lU="MenuCheckboxItem",kN=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...s}=e;return i.jsx(_N,{scope:e.__scopeMenu,checked:n,children:i.jsx(Bh,{role:"menuitemcheckbox","aria-checked":zp(n)?"mixed":n,...s,ref:t,"data-state":cx(n),onSelect:Ue(s.onSelect,()=>r?.(zp(n)?!0:!n),{checkForDefaultPrevented:!1})})})});kN.displayName=lU;var jN="MenuRadioGroup",[cU,uU]=$i(jN,{value:void 0,onValueChange:()=>{}}),TN=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...s}=e,o=Rn(r);return i.jsx(cU,{scope:e.__scopeMenu,value:n,onValueChange:o,children:i.jsx(ix,{...s,ref:t})})});TN.displayName=jN;var NN="MenuRadioItem",MN=y.forwardRef((e,t)=>{const{value:n,...r}=e,s=uU(NN,e.__scopeMenu),o=n===s.value;return i.jsx(_N,{scope:e.__scopeMenu,checked:o,children:i.jsx(Bh,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":cx(o),onSelect:Ue(r.onSelect,()=>s.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});MN.displayName=NN;var lx="MenuItemIndicator",[_N,dU]=$i(lx,{checked:!1}),RN=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...s}=e,o=dU(lx,n);return i.jsx(Mr,{present:r||zp(o.checked)||o.checked===!0,children:i.jsx(rt.span,{...s,ref:t,"data-state":cx(o.checked)})})});RN.displayName=lx;var fU="MenuSeparator",PN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(rt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});PN.displayName=fU;var pU="MenuArrow",ON=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,s=$h(n);return i.jsx(eN,{...s,...r,ref:t})});ON.displayName=pU;var hU="MenuSub",[wie,IN]=$i(hU),mu="MenuSubTrigger",AN=y.forwardRef((e,t)=>{const n=Bi(mu,e.__scopeMenu),r=Cd(mu,e.__scopeMenu),s=IN(mu,e.__scopeMenu),o=ox(mu,e.__scopeMenu),l=y.useRef(null),{pointerGraceTimerRef:u,onPointerGraceIntentChange:d}=o,f={__scopeMenu:e.__scopeMenu},h=y.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return y.useEffect(()=>h,[h]),y.useEffect(()=>{const m=u.current;return()=>{window.clearTimeout(m),d(null)}},[u,d]),i.jsx(rx,{asChild:!0,...f,children:i.jsx(EN,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":s.contentId,"data-state":LN(n.open),...e,ref:kh(t,s.onTriggerChange),onClick:m=>{e.onClick?.(m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ue(e.onPointerMove,Vu(m=>{o.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!l.current&&(o.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:Ue(e.onPointerLeave,Vu(m=>{h();const g=n.content?.getBoundingClientRect();if(g){const x=n.content?.dataset.side,b=x==="right",w=b?-5:5,C=g[b?"left":"right"],k=g[b?"right":"left"];o.onPointerGraceIntentChange({area:[{x:m.clientX+w,y:m.clientY},{x:C,y:g.top},{x:k,y:g.top},{x:k,y:g.bottom},{x:C,y:g.bottom}],side:x}),window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(m),m.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Ue(e.onKeyDown,m=>{const g=o.searchRef.current!=="";e.disabled||g&&m.key===" "||Jz[r.dir].includes(m.key)&&(n.onOpenChange(!0),n.content?.focus(),m.preventDefault())})})})});AN.displayName=mu;var DN="MenuSubContent",FN=y.forwardRef((e,t)=>{const n=xN(is,e.__scopeMenu),{forceMount:r=n.forceMount,...s}=e,o=Bi(is,e.__scopeMenu),l=Cd(is,e.__scopeMenu),u=IN(DN,e.__scopeMenu),d=y.useRef(null),f=Rt(t,d);return i.jsx(Uu.Provider,{scope:e.__scopeMenu,children:i.jsx(Mr,{present:r||o.open,children:i.jsx(Uu.Slot,{scope:e.__scopeMenu,children:i.jsx(ax,{id:u.contentId,"aria-labelledby":u.triggerId,...s,ref:f,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{l.isUsingKeyboardRef.current&&d.current?.focus(),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:Ue(e.onFocusOutside,h=>{h.target!==u.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Ue(e.onEscapeKeyDown,h=>{l.onClose(),h.preventDefault()}),onKeyDown:Ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=Qz[l.dir].includes(h.key);m&&g&&(o.onOpenChange(!1),u.trigger?.focus(),h.preventDefault())})})})})})});FN.displayName=DN;function LN(e){return e?"open":"closed"}function zp(e){return e==="indeterminate"}function cx(e){return zp(e)?"indeterminate":e?"checked":"unchecked"}function gU(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function mU(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function vU(e,t,n){const s=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let l=mU(e,Math.max(o,0));s.length===1&&(l=l.filter(f=>f!==n));const d=l.find(f=>f.toLowerCase().startsWith(s.toLowerCase()));return d!==n?d:void 0}function yU(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,l=t.length-1;or!=h>r&&n<(f-u)*(r-d)/(h-d)+u&&(s=!s)}return s}function bU(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return yU(n,t)}function Vu(e){return t=>t.pointerType==="mouse"?e(t):void 0}var xU=bN,wU=rx,SU=wN,CU=SN,EU=ix,kU=CN,jU=Bh,TU=kN,NU=TN,MU=MN,_U=RN,RU=PN,PU=ON,OU=AN,IU=FN,ux="DropdownMenu",[AU]=us(ux,[vN]),pr=vN(),[DU,$N]=AU(ux),dx=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:s,defaultOpen:o,onOpenChange:l,modal:u=!0}=e,d=pr(t),f=y.useRef(null),[h=!1,m]=ya({prop:s,defaultProp:o,onChange:l});return i.jsx(DU,{scope:t,triggerId:Es(),triggerRef:f,contentId:Es(),open:h,onOpenChange:m,onOpenToggle:y.useCallback(()=>m(g=>!g),[m]),modal:u,children:i.jsx(xU,{...d,open:h,onOpenChange:m,dir:r,modal:u,children:n})})};dx.displayName=ux;var BN="DropdownMenuTrigger",fx=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...s}=e,o=$N(BN,n),l=pr(n);return i.jsx(wU,{asChild:!0,...l,children:i.jsx(rt.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:kh(t,o.triggerRef),onPointerDown:Ue(e.onPointerDown,u=>{!r&&u.button===0&&u.ctrlKey===!1&&(o.onOpenToggle(),o.open||u.preventDefault())}),onKeyDown:Ue(e.onKeyDown,u=>{r||(["Enter"," "].includes(u.key)&&o.onOpenToggle(),u.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(u.key)&&u.preventDefault())})})})});fx.displayName=BN;var FU="DropdownMenuPortal",zN=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pr(t);return i.jsx(SU,{...r,...n})};zN.displayName=FU;var UN="DropdownMenuContent",VN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=$N(UN,n),o=pr(n),l=y.useRef(!1);return i.jsx(CU,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:t,onCloseAutoFocus:Ue(e.onCloseAutoFocus,u=>{l.current||s.triggerRef.current?.focus(),l.current=!1,u.preventDefault()}),onInteractOutside:Ue(e.onInteractOutside,u=>{const d=u.detail.originalEvent,f=d.button===0&&d.ctrlKey===!0,h=d.button===2||f;(!s.modal||h)&&(l.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});VN.displayName=UN;var LU="DropdownMenuGroup",$U=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(EU,{...s,...r,ref:t})});$U.displayName=LU;var BU="DropdownMenuLabel",HN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(kU,{...s,...r,ref:t})});HN.displayName=BU;var zU="DropdownMenuItem",qN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(jU,{...s,...r,ref:t})});qN.displayName=zU;var UU="DropdownMenuCheckboxItem",KN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(TU,{...s,...r,ref:t})});KN.displayName=UU;var VU="DropdownMenuRadioGroup",HU=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(NU,{...s,...r,ref:t})});HU.displayName=VU;var qU="DropdownMenuRadioItem",WN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(MU,{...s,...r,ref:t})});WN.displayName=qU;var KU="DropdownMenuItemIndicator",GN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(_U,{...s,...r,ref:t})});GN.displayName=KU;var WU="DropdownMenuSeparator",JN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(RU,{...s,...r,ref:t})});JN.displayName=WU;var GU="DropdownMenuArrow",JU=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(PU,{...s,...r,ref:t})});JU.displayName=GU;var QU="DropdownMenuSubTrigger",QN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(OU,{...s,...r,ref:t})});QN.displayName=QU;var ZU="DropdownMenuSubContent",ZN=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,s=pr(n);return i.jsx(IU,{...s,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ZN.displayName=ZU;var YU=dx,XU=fx,e5=zN,YN=VN,XN=HN,eM=qN,tM=KN,nM=WN,rM=GN,Oa=JN,sM=QN,oM=ZN;const Kr=YU,Wr=XU,t5=y.forwardRef(({className:e,inset:t,children:n,...r},s)=>i.jsxs(sM,{ref:s,className:Ie("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,i.jsx(W$,{className:"ml-auto h-4 w-4"})]}));t5.displayName=sM.displayName;const n5=y.forwardRef(({className:e,...t},n)=>i.jsx(oM,{ref:n,className:Ie("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));n5.displayName=oM.displayName;const hr=y.forwardRef(({className:e,sideOffset:t=4,...n},r)=>i.jsx(e5,{children:i.jsx(YN,{ref:r,sideOffset:t,className:Ie("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));hr.displayName=YN.displayName;const wt=y.forwardRef(({className:e,inset:t,...n},r)=>i.jsx(eM,{ref:r,className:Ie("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));wt.displayName=eM.displayName;const aM=y.forwardRef(({className:e,children:t,checked:n,...r},s)=>i.jsxs(tM,{ref:s,className:Ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[i.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:i.jsx(rM,{children:i.jsx(fT,{className:"h-4 w-4"})})}),t]}));aM.displayName=tM.displayName;const r5=y.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(nM,{ref:r,className:Ie("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[i.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:i.jsx(rM,{children:i.jsx(Z$,{className:"h-2 w-2 fill-current"})})}),t]}));r5.displayName=nM.displayName;const Ao=y.forwardRef(({className:e,inset:t,...n},r)=>i.jsx(XN,{ref:r,className:Ie("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Ao.displayName=XN.displayName;const Xs=y.forwardRef(({className:e,...t},n)=>i.jsx(Oa,{ref:n,className:Ie("-mx-1 my-1 h-px bg-muted",e),...t}));Xs.displayName=Oa.displayName;function iM(){const{t:e,i18n:t}=Ve(),n=r=>{t.changeLanguage(r),localStorage.setItem("i18nextLng",r),window.location.reload()};return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"outline",size:"icon",children:[i.jsx(fB,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all"}),i.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(wt,{className:t.language==="pt-BR"?"font-bold":"",onClick:()=>n("pt-BR"),children:e("header.language.portuguese")}),i.jsx(wt,{className:t.language==="en-US"?"font-bold":"",onClick:()=>n("en-US"),children:e("header.language.english")}),i.jsx(wt,{className:t.language==="es-ES"?"font-bold":"",onClick:()=>n("es-ES"),children:e("header.language.spanish")}),i.jsx(wt,{className:t.language==="fr-FR"?"font-bold":"",onClick:()=>n("fr-FR"),children:e("header.language.french")})]})]})}function lM(){const{t:e}=Ve(),{setTheme:t}=tc();return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"outline",size:"icon",children:[i.jsx(EB,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),i.jsx(bB,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),i.jsx("span",{className:"sr-only",children:e("header.theme.label")})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(wt,{onClick:()=>t("light"),children:e("header.theme.light")}),i.jsx(wt,{onClick:()=>t("dark"),children:e("header.theme.dark")}),i.jsx(wt,{onClick:()=>t("system"),children:e("header.theme.system")})]})]})}var px="Avatar",[s5]=us(px),[o5,cM]=s5(px),uM=y.forwardRef((e,t)=>{const{__scopeAvatar:n,...r}=e,[s,o]=y.useState("idle");return i.jsx(o5,{scope:n,imageLoadingStatus:s,onImageLoadingStatusChange:o,children:i.jsx(rt.span,{...r,ref:t})})});uM.displayName=px;var dM="AvatarImage",fM=y.forwardRef((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:s=()=>{},...o}=e,l=cM(dM,n),u=a5(r),d=Rn(f=>{s(f),l.onImageLoadingStatusChange(f)});return Ln(()=>{u!=="idle"&&d(u)},[u,d]),u==="loaded"?i.jsx(rt.img,{...o,ref:t,src:r}):null});fM.displayName=dM;var pM="AvatarFallback",hM=y.forwardRef((e,t)=>{const{__scopeAvatar:n,delayMs:r,...s}=e,o=cM(pM,n),[l,u]=y.useState(r===void 0);return y.useEffect(()=>{if(r!==void 0){const d=window.setTimeout(()=>u(!0),r);return()=>window.clearTimeout(d)}},[r]),l&&o.imageLoadingStatus!=="loaded"?i.jsx(rt.span,{...s,ref:t}):null});hM.displayName=pM;function a5(e){const[t,n]=y.useState("idle");return Ln(()=>{if(!e){n("error");return}let r=!0;const s=new window.Image,o=l=>()=>{r&&n(l)};return n("loading"),s.onload=o("loaded"),s.onerror=o("error"),s.src=e,()=>{r=!1}},[e]),t}var gM=uM,mM=fM,vM=hM;const Ei=y.forwardRef(({className:e,...t},n)=>i.jsx(gM,{ref:n,className:Ie("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Ei.displayName=gM.displayName;const ki=y.forwardRef(({className:e,...t},n)=>i.jsx(mM,{ref:n,className:Ie("aspect-square h-full w-full",e),...t}));ki.displayName=mM.displayName;const Up=y.forwardRef(({className:e,...t},n)=>i.jsx(vM,{ref:n,className:Ie("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Up.displayName=vM.displayName;var hx="Dialog",[yM]=us(hx),[i5,Ps]=yM(hx),bM=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:l=!0}=e,u=y.useRef(null),d=y.useRef(null),[f=!1,h]=ya({prop:r,defaultProp:s,onChange:o});return i.jsx(i5,{scope:t,triggerRef:u,contentRef:d,contentId:Es(),titleId:Es(),descriptionId:Es(),open:f,onOpenChange:h,onOpenToggle:y.useCallback(()=>h(m=>!m),[h]),modal:l,children:n})};bM.displayName=hx;var xM="DialogTrigger",wM=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Ps(xM,n),o=Rt(t,s.triggerRef);return i.jsx(rt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":vx(s.open),...r,ref:o,onClick:Ue(e.onClick,s.onOpenToggle)})});wM.displayName=xM;var gx="DialogPortal",[l5,SM]=yM(gx,{forceMount:void 0}),CM=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:s}=e,o=Ps(gx,t);return i.jsx(l5,{scope:t,forceMount:n,children:y.Children.map(r,l=>i.jsx(Mr,{present:n||o.open,children:i.jsx(Ih,{asChild:!0,container:s,children:l})}))})};CM.displayName=gx;var Vp="DialogOverlay",EM=y.forwardRef((e,t)=>{const n=SM(Vp,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=Ps(Vp,e.__scopeDialog);return o.modal?i.jsx(Mr,{present:r||o.open,children:i.jsx(c5,{...s,ref:t})}):null});EM.displayName=Vp;var c5=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Ps(Vp,n);return i.jsx(Lh,{as:No,allowPinchZoom:!0,shards:[s.contentRef],children:i.jsx(rt.div,{"data-state":vx(s.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),ji="DialogContent",kM=y.forwardRef((e,t)=>{const n=SM(ji,e.__scopeDialog),{forceMount:r=n.forceMount,...s}=e,o=Ps(ji,e.__scopeDialog);return i.jsx(Mr,{present:r||o.open,children:o.modal?i.jsx(u5,{...s,ref:t}):i.jsx(d5,{...s,ref:t})})});kM.displayName=ji;var u5=y.forwardRef((e,t)=>{const n=Ps(ji,e.__scopeDialog),r=y.useRef(null),s=Rt(t,n.contentRef,r);return y.useEffect(()=>{const o=r.current;if(o)return nx(o)},[]),i.jsx(jM,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ue(e.onCloseAutoFocus,o=>{o.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ue(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0;(l.button===2||u)&&o.preventDefault()}),onFocusOutside:Ue(e.onFocusOutside,o=>o.preventDefault())})}),d5=y.forwardRef((e,t)=>{const n=Ps(ji,e.__scopeDialog),r=y.useRef(!1),s=y.useRef(!1);return i.jsx(jM,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(r.current||n.triggerRef.current?.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const l=o.target;n.triggerRef.current?.contains(l)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),jM=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...l}=e,u=Ps(ji,n),d=y.useRef(null),f=Rt(t,d);return Wb(),i.jsxs(i.Fragment,{children:[i.jsx(_h,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:i.jsx(Mh,{role:"dialog",id:u.contentId,"aria-describedby":u.descriptionId,"aria-labelledby":u.titleId,"data-state":vx(u.open),...l,ref:f,onDismiss:()=>u.onOpenChange(!1)})}),i.jsxs(i.Fragment,{children:[i.jsx(f5,{titleId:u.titleId}),i.jsx(h5,{contentRef:d,descriptionId:u.descriptionId})]})]})}),mx="DialogTitle",TM=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Ps(mx,n);return i.jsx(rt.h2,{id:s.titleId,...r,ref:t})});TM.displayName=mx;var NM="DialogDescription",MM=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Ps(NM,n);return i.jsx(rt.p,{id:s.descriptionId,...r,ref:t})});MM.displayName=NM;var _M="DialogClose",RM=y.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,s=Ps(_M,n);return i.jsx(rt.button,{type:"button",...r,ref:t,onClick:Ue(e.onClick,()=>s.onOpenChange(!1))})});RM.displayName=_M;function vx(e){return e?"open":"closed"}var PM="DialogTitleWarning",[Sie,OM]=_B(PM,{contentName:ji,titleName:mx,docsSlug:"dialog"}),f5=({titleId:e})=>{const t=OM(PM),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. + +If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. + +For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return y.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},p5="DialogDescriptionWarning",h5=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${OM(p5).contentName}}.`;return y.useEffect(()=>{const s=e.current?.getAttribute("aria-describedby");t&&s&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},g5=bM,m5=wM,v5=CM,IM=EM,AM=kM,DM=TM,FM=MM,LM=RM;const Pt=g5,Bt=m5,y5=v5,$M=LM,BM=y.forwardRef(({className:e,...t},n)=>i.jsx(IM,{ref:n,className:Ie("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));BM.displayName=IM.displayName;const Nt=y.forwardRef(({className:e,children:t,closeBtn:n=!0,...r},s)=>i.jsx(y5,{children:i.jsx(BM,{className:"fixed inset-0 grid place-items-center overflow-y-auto",children:i.jsxs(AM,{ref:s,className:Ie("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:m-4 sm:rounded-lg md:w-full",e),...r,children:[t,n&&i.jsxs(LM,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[i.jsx(qb,{className:"h-4 w-4"}),i.jsx("span",{className:"sr-only",children:"Close"})]})]})})}));Nt.displayName=AM.displayName;const Mt=({className:e,...t})=>i.jsx("div",{className:Ie("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Mt.displayName="DialogHeader";const Yt=({className:e,...t})=>i.jsx("div",{className:Ie("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Yt.displayName="DialogFooter";const zt=y.forwardRef(({className:e,...t},n)=>i.jsx(DM,{ref:n,className:Ie("text-lg font-semibold leading-none tracking-tight",e),...t}));zt.displayName=DM.displayName;const eo=y.forwardRef(({className:e,...t},n)=>i.jsx(FM,{ref:n,className:Ie("text-sm text-muted-foreground",e),...t}));eo.displayName=FM.displayName;function zM({instanceId:e}){const[t,n]=y.useState(!1),r=dn(),{theme:s}=tc(),o=()=>{Pj(),r("/manager/login")},l=()=>{r("/manager/")},{data:u}=vT({instanceId:e});return i.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[i.jsx(Fu,{to:"/manager",onClick:l,className:"flex h-8 items-center gap-4",children:i.jsx("img",{src:s==="dark"?"https://evolution-api.com/files/evo/evolution-logo-white.svg":"https://evolution-api.com/files/evo/evolution-logo.svg",alt:"Logo",className:"h-full"})}),i.jsxs("div",{className:"flex items-center gap-4",children:[e&&i.jsx(Ei,{className:"h-8 w-8",children:i.jsx(ki,{src:u?.profilePicUrl||"/assets/images/evolution-logo.png",alt:u?.name})}),i.jsx(iM,{}),i.jsx(lM,{}),i.jsx(se,{onClick:()=>n(!0),variant:"destructive",size:"icon",children:i.jsx(eB,{size:"18"})})]}),t&&i.jsx(Pt,{onOpenChange:n,open:t,children:i.jsxs(Nt,{children:[i.jsx($M,{}),i.jsx(Mt,{children:"Deseja realmente sair?"}),i.jsx(Yt,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(se,{onClick:()=>n(!1),size:"sm",variant:"outline",children:"Cancelar"}),i.jsx(se,{onClick:o,variant:"destructive",children:"Sair"})]})})]})})]})}const UM=y.createContext(null),ct=()=>{const e=y.useContext(UM);if(!e)throw new Error("useInstance must be used within an InstanceProvider");return e},VM=({children:e})=>{const t=ls(),[n,r]=y.useState(null),{data:s,refetch:o}=vT({instanceId:n});return y.useEffect(()=>{t.instanceId?r(t.instanceId):r(null)},[t]),i.jsx(UM.Provider,{value:{instance:s??null,reloadInstance:async()=>{await o()}},children:e})};var yx="Collapsible",[b5]=us(yx),[x5,bx]=b5(yx),HM=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:l,...u}=e,[d=!1,f]=ya({prop:r,defaultProp:s,onChange:l});return i.jsx(x5,{scope:n,disabled:o,contentId:Es(),open:d,onOpenToggle:y.useCallback(()=>f(h=>!h),[f]),children:i.jsx(rt.div,{"data-state":wx(d),"data-disabled":o?"":void 0,...u,ref:t})})});HM.displayName=yx;var qM="CollapsibleTrigger",KM=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=bx(qM,n);return i.jsx(rt.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":wx(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ue(e.onClick,s.onOpenToggle)})});KM.displayName=qM;var xx="CollapsibleContent",WM=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=bx(xx,e.__scopeCollapsible);return i.jsx(Mr,{present:n||s.open,children:({present:o})=>i.jsx(w5,{...r,ref:t,present:o})})});WM.displayName=xx;var w5=y.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,l=bx(xx,n),[u,d]=y.useState(r),f=y.useRef(null),h=Rt(t,f),m=y.useRef(0),g=m.current,x=y.useRef(0),b=x.current,w=l.open||u,C=y.useRef(w),k=y.useRef();return y.useEffect(()=>{const j=requestAnimationFrame(()=>C.current=!1);return()=>cancelAnimationFrame(j)},[]),Ln(()=>{const j=f.current;if(j){k.current=k.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const M=j.getBoundingClientRect();m.current=M.height,x.current=M.width,C.current||(j.style.transitionDuration=k.current.transitionDuration,j.style.animationName=k.current.animationName),d(r)}},[l.open,r]),i.jsx(rt.div,{"data-state":wx(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!w,...o,ref:h,style:{"--radix-collapsible-content-height":g?`${g}px`:void 0,"--radix-collapsible-content-width":b?`${b}px`:void 0,...e.style},children:w&&s})});function wx(e){return e?"open":"closed"}var S5=HM;const C5=S5,E5=KM,k5=WM;function j5(){const{t:e}=Ve(),t=y.useMemo(()=>[{id:"dashboard",title:e("sidebar.dashboard"),icon:pB,path:"dashboard"},{id:"chat",title:e("sidebar.chat"),icon:Bl,path:"chat"},{navLabel:!0,title:e("sidebar.configurations"),icon:Oo,children:[{id:"settings",title:e("sidebar.settings"),path:"settings"},{id:"proxy",title:e("sidebar.proxy"),path:"proxy"}]},{title:e("sidebar.events"),icon:dB,children:[{id:"webhook",title:e("sidebar.webhook"),path:"webhook"},{id:"websocket",title:e("sidebar.websocket"),path:"websocket"},{id:"rabbitmq",title:e("sidebar.rabbitmq"),path:"rabbitmq"},{id:"sqs",title:e("sidebar.sqs"),path:"sqs"}]},{title:e("sidebar.integrations"),icon:mT,children:[{id:"evoai",title:e("sidebar.evoai"),path:"evoai"},{id:"n8n",title:e("sidebar.n8n"),path:"n8n"},{id:"evolutionBot",title:e("sidebar.evolutionBot"),path:"evolutionBot"},{id:"chatwoot",title:e("sidebar.chatwoot"),path:"chatwoot"},{id:"typebot",title:e("sidebar.typebot"),path:"typebot"},{id:"openai",title:e("sidebar.openai"),path:"openai"},{id:"dify",title:e("sidebar.dify"),path:"dify"},{id:"flowise",title:e("sidebar.flowise"),path:"flowise"}]},{id:"documentation",title:e("sidebar.documentation"),icon:sB,link:"https://doc.evolution-api.com",divider:!0},{id:"postman",title:e("sidebar.postman"),icon:Q$,link:"https://evolution-api.com/postman"},{id:"discord",title:e("sidebar.discord"),icon:Bl,link:"https://evolution-api.com/discord"},{id:"support-premium",title:e("sidebar.supportPremium"),icon:hB,link:"https://evolution-api.com/suporte-pro"}],[e]),n=dn(),{pathname:r}=Pi(),{instance:s}=ct(),o=u=>{!u||!s||(u.path&&n(`/manager/instance/${s.id}/${u.path}`),u.link&&window.open(u.link,"_blank"))},l=y.useMemo(()=>t.map(u=>({...u,children:"children"in u?u.children?.map(d=>({...d,isActive:"path"in d?r.includes(d.path):!1})):void 0,isActive:"path"in u&&u.path?r.includes(u.path):!1})).map(u=>({...u,isActive:u.isActive||"children"in u&&u.children?.some(d=>d.isActive)})),[t,r]);return i.jsx("ul",{className:"flex h-full w-full flex-col gap-2 border-r border-border px-2",children:l.map(u=>i.jsx("li",{className:"divider"in u?"mt-auto":void 0,children:u.children?i.jsxs(C5,{defaultOpen:u.isActive,children:[i.jsx(E5,{asChild:!0,children:i.jsxs(se,{className:Ie("flex w-full items-center justify-start gap-2"),variant:u.isActive?"secondary":"link",children:[u.icon&&i.jsx(u.icon,{size:"15"}),i.jsx("span",{children:u.title}),i.jsx(Nh,{size:"15",className:"ml-auto"})]})}),i.jsx(k5,{children:i.jsx("ul",{className:"my-4 ml-6 flex flex-col gap-2 text-sm",children:u.children.map(d=>i.jsx("li",{children:i.jsx("button",{onClick:()=>o(d),className:Ie(d.isActive?"text-foreground":"text-muted-foreground"),children:i.jsx("span",{className:"nav-label",children:d.title})})},d.id))})})]}):i.jsxs(se,{className:Ie("relative flex w-full items-center justify-start gap-2",u.isActive&&"pointer-events-none"),variant:u.isActive?"secondary":"link",children:["link"in u&&i.jsx("a",{href:u.link,target:"_blank",rel:"noreferrer",className:"absolute inset-0 h-full w-full"}),"path"in u&&i.jsx(Fu,{to:`/manager/instance/${s?.id}/${u.path}`,className:"absolute inset-0 h-full w-full"}),u.icon&&i.jsx(u.icon,{size:"15"}),i.jsx("span",{children:u.title})]})},u.title))})}function Ky(e,[t,n]){return Math.min(n,Math.max(t,e))}function T5(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Sx="ScrollArea",[GM]=us(Sx),[N5,ds]=GM(Sx),JM=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...l}=e,[u,d]=y.useState(null),[f,h]=y.useState(null),[m,g]=y.useState(null),[x,b]=y.useState(null),[w,C]=y.useState(null),[k,j]=y.useState(0),[M,_]=y.useState(0),[R,N]=y.useState(!1),[O,D]=y.useState(!1),z=Rt(t,pe=>d(pe)),Q=xd(s);return i.jsx(N5,{scope:n,type:r,dir:Q,scrollHideDelay:o,scrollArea:u,viewport:f,onViewportChange:h,content:m,onContentChange:g,scrollbarX:x,onScrollbarXChange:b,scrollbarXEnabled:R,onScrollbarXEnabledChange:N,scrollbarY:w,onScrollbarYChange:C,scrollbarYEnabled:O,onScrollbarYEnabledChange:D,onCornerWidthChange:j,onCornerHeightChange:_,children:i.jsx(rt.div,{dir:Q,...l,ref:z,style:{position:"relative","--radix-scroll-area-corner-width":k+"px","--radix-scroll-area-corner-height":M+"px",...e.style}})})});JM.displayName=Sx;var QM="ScrollAreaViewport",ZM=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,l=ds(QM,n),u=y.useRef(null),d=Rt(t,u,l.onViewportChange);return i.jsxs(i.Fragment,{children:[i.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),i.jsx(rt.div,{"data-radix-scroll-area-viewport":"",...o,ref:d,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...e.style},children:i.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});ZM.displayName=QM;var to="ScrollAreaScrollbar",Cx=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=ds(to,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:l}=s,u=e.orientation==="horizontal";return y.useEffect(()=>(u?o(!0):l(!0),()=>{u?o(!1):l(!1)}),[u,o,l]),s.type==="hover"?i.jsx(M5,{...r,ref:t,forceMount:n}):s.type==="scroll"?i.jsx(_5,{...r,ref:t,forceMount:n}):s.type==="auto"?i.jsx(YM,{...r,ref:t,forceMount:n}):s.type==="always"?i.jsx(Ex,{...r,ref:t}):null});Cx.displayName=to;var M5=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=ds(to,e.__scopeScrollArea),[o,l]=y.useState(!1);return y.useEffect(()=>{const u=s.scrollArea;let d=0;if(u){const f=()=>{window.clearTimeout(d),l(!0)},h=()=>{d=window.setTimeout(()=>l(!1),s.scrollHideDelay)};return u.addEventListener("pointerenter",f),u.addEventListener("pointerleave",h),()=>{window.clearTimeout(d),u.removeEventListener("pointerenter",f),u.removeEventListener("pointerleave",h)}}},[s.scrollArea,s.scrollHideDelay]),i.jsx(Mr,{present:n||o,children:i.jsx(YM,{"data-state":o?"visible":"hidden",...r,ref:t})})}),_5=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=ds(to,e.__scopeScrollArea),o=e.orientation==="horizontal",l=Uh(()=>d("SCROLL_END"),100),[u,d]=T5("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return y.useEffect(()=>{if(u==="idle"){const f=window.setTimeout(()=>d("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(f)}},[u,s.scrollHideDelay,d]),y.useEffect(()=>{const f=s.viewport,h=o?"scrollLeft":"scrollTop";if(f){let m=f[h];const g=()=>{const x=f[h];m!==x&&(d("SCROLL"),l()),m=x};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[s.viewport,o,d,l]),i.jsx(Mr,{present:n||u!=="hidden",children:i.jsx(Ex,{"data-state":u==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ue(e.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Ue(e.onPointerLeave,()=>d("POINTER_LEAVE"))})})}),YM=y.forwardRef((e,t)=>{const n=ds(to,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,l]=y.useState(!1),u=e.orientation==="horizontal",d=Uh(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,s=ds(to,e.__scopeScrollArea),o=y.useRef(null),l=y.useRef(0),[u,d]=y.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=r_(u.viewport,u.content),h={...r,sizes:u,onSizesChange:d,hasThumb:f>0&&f<1,onThumbChange:g=>o.current=g,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:g=>l.current=g};function m(g,x){return D5(g,l.current,u,x)}return n==="horizontal"?i.jsx(R5,{...h,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const g=s.viewport.scrollLeft,x=p1(g,u,s.dir);o.current.style.transform=`translate3d(${x}px, 0, 0)`}},onWheelScroll:g=>{s.viewport&&(s.viewport.scrollLeft=g)},onDragScroll:g=>{s.viewport&&(s.viewport.scrollLeft=m(g,s.dir))}}):n==="vertical"?i.jsx(P5,{...h,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const g=s.viewport.scrollTop,x=p1(g,u);o.current.style.transform=`translate3d(0, ${x}px, 0)`}},onWheelScroll:g=>{s.viewport&&(s.viewport.scrollTop=g)},onDragScroll:g=>{s.viewport&&(s.viewport.scrollTop=m(g))}}):null}),R5=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=ds(to,e.__scopeScrollArea),[l,u]=y.useState(),d=y.useRef(null),f=Rt(t,d,o.onScrollbarXChange);return y.useEffect(()=>{d.current&&u(getComputedStyle(d.current))},[d]),i.jsx(e_,{"data-orientation":"horizontal",...s,ref:f,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":zh(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(o.viewport){const g=o.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),o_(g,m)&&h.preventDefault()}},onResize:()=>{d.current&&o.viewport&&l&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:qp(l.paddingLeft),paddingEnd:qp(l.paddingRight)}})}})}),P5=y.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=ds(to,e.__scopeScrollArea),[l,u]=y.useState(),d=y.useRef(null),f=Rt(t,d,o.onScrollbarYChange);return y.useEffect(()=>{d.current&&u(getComputedStyle(d.current))},[d]),i.jsx(e_,{"data-orientation":"vertical",...s,ref:f,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":zh(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(o.viewport){const g=o.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),o_(g,m)&&h.preventDefault()}},onResize:()=>{d.current&&o.viewport&&l&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:qp(l.paddingTop),paddingEnd:qp(l.paddingBottom)}})}})}),[O5,XM]=GM(to),e_=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:l,onThumbPointerDown:u,onThumbPositionChange:d,onDragScroll:f,onWheelScroll:h,onResize:m,...g}=e,x=ds(to,n),[b,w]=y.useState(null),C=Rt(t,z=>w(z)),k=y.useRef(null),j=y.useRef(""),M=x.viewport,_=r.content-r.viewport,R=Rn(h),N=Rn(d),O=Uh(m,10);function D(z){if(k.current){const Q=z.clientX-k.current.left,pe=z.clientY-k.current.top;f({x:Q,y:pe})}}return y.useEffect(()=>{const z=Q=>{const pe=Q.target;b?.contains(pe)&&R(Q,_)};return document.addEventListener("wheel",z,{passive:!1}),()=>document.removeEventListener("wheel",z,{passive:!1})},[M,b,_,R]),y.useEffect(N,[r,N]),Ul(b,O),Ul(x.content,O),i.jsx(O5,{scope:n,scrollbar:b,hasThumb:s,onThumbChange:Rn(o),onThumbPointerUp:Rn(l),onThumbPositionChange:N,onThumbPointerDown:Rn(u),children:i.jsx(rt.div,{...g,ref:C,style:{position:"absolute",...g.style},onPointerDown:Ue(e.onPointerDown,z=>{z.button===0&&(z.target.setPointerCapture(z.pointerId),k.current=b.getBoundingClientRect(),j.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",x.viewport&&(x.viewport.style.scrollBehavior="auto"),D(z))}),onPointerMove:Ue(e.onPointerMove,D),onPointerUp:Ue(e.onPointerUp,z=>{const Q=z.target;Q.hasPointerCapture(z.pointerId)&&Q.releasePointerCapture(z.pointerId),document.body.style.webkitUserSelect=j.current,x.viewport&&(x.viewport.style.scrollBehavior=""),k.current=null})})})}),Hp="ScrollAreaThumb",t_=y.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=XM(Hp,e.__scopeScrollArea);return i.jsx(Mr,{present:n||s.hasThumb,children:i.jsx(I5,{ref:t,...r})})}),I5=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=ds(Hp,n),l=XM(Hp,n),{onThumbPositionChange:u}=l,d=Rt(t,m=>l.onThumbChange(m)),f=y.useRef(),h=Uh(()=>{f.current&&(f.current(),f.current=void 0)},100);return y.useEffect(()=>{const m=o.viewport;if(m){const g=()=>{if(h(),!f.current){const x=F5(m,u);f.current=x,u()}};return u(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[o.viewport,h,u]),i.jsx(rt.div,{"data-state":l.hasThumb?"visible":"hidden",...s,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ue(e.onPointerDownCapture,m=>{const x=m.target.getBoundingClientRect(),b=m.clientX-x.left,w=m.clientY-x.top;l.onThumbPointerDown({x:b,y:w})}),onPointerUp:Ue(e.onPointerUp,l.onThumbPointerUp)})});t_.displayName=Hp;var kx="ScrollAreaCorner",n_=y.forwardRef((e,t)=>{const n=ds(kx,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?i.jsx(A5,{...e,ref:t}):null});n_.displayName=kx;var A5=y.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=ds(kx,n),[o,l]=y.useState(0),[u,d]=y.useState(0),f=!!(o&&u);return Ul(s.scrollbarX,()=>{const h=s.scrollbarX?.offsetHeight||0;s.onCornerHeightChange(h),d(h)}),Ul(s.scrollbarY,()=>{const h=s.scrollbarY?.offsetWidth||0;s.onCornerWidthChange(h),l(h)}),f?i.jsx(rt.div,{...r,ref:t,style:{width:o,height:u,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function qp(e){return e?parseInt(e,10):0}function r_(e,t){const n=e/t;return isNaN(n)?0:n}function zh(e){const t=r_(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function D5(e,t,n,r="ltr"){const s=zh(n),o=s/2,l=t||o,u=s-l,d=n.scrollbar.paddingStart+l,f=n.scrollbar.size-n.scrollbar.paddingEnd-u,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return s_([d,f],m)(e)}function p1(e,t,n="ltr"){const r=zh(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,l=t.content-t.viewport,u=o-r,d=n==="ltr"?[0,l]:[l*-1,0],f=Ky(e,d);return s_([0,l],[0,u])(f)}function s_(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function o_(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function s(){const o={left:e.scrollLeft,top:e.scrollTop},l=n.left!==o.left,u=n.top!==o.top;(l||u)&&t(),n=o,r=window.requestAnimationFrame(s)})(),()=>window.cancelAnimationFrame(r)};function Uh(e,t){const n=Rn(e),r=y.useRef(0);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),y.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Ul(e,t){const n=Rn(t);Ln(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var a_=JM,L5=ZM,$5=n_;const Wy=y.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(a_,{ref:r,className:Ie("relative overflow-hidden",e),...n,children:[i.jsx(L5,{className:"h-full w-full rounded-[inherit] [&>div[style]]:!block [&>div[style]]:h-full",children:t}),i.jsx(i_,{}),i.jsx($5,{})]}));Wy.displayName=a_.displayName;const i_=y.forwardRef(({className:e,orientation:t="vertical",...n},r)=>i.jsx(Cx,{ref:r,orientation:t,className:Ie("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:i.jsx(t_,{className:Ie("relative rounded-full bg-border",t==="vertical"&&"flex-1")})}));i_.displayName=Cx.displayName;function un({children:e}){const{instanceId:t}=ls();return i.jsx(VM,{children:i.jsxs("div",{className:"flex h-screen flex-col",children:[i.jsx(zM,{instanceId:t}),i.jsxs("div",{className:"flex min-h-[calc(100vh_-_56px)] flex-1 flex-col md:flex-row",children:[i.jsx(Wy,{className:"mr-2 py-6 md:w-64",children:i.jsx("div",{className:"flex h-full",children:i.jsx(j5,{})})}),i.jsx(Wy,{className:"w-full",children:i.jsxs("div",{className:"flex h-full flex-col",children:[i.jsx("div",{className:"my-2 flex flex-1 flex-col gap-2 pl-2 pr-4",children:e}),i.jsx(Vb,{})]})})]})]})})}function B5({children:e}){return i.jsxs("div",{className:"flex h-full min-h-screen flex-col",children:[i.jsx(zM,{}),i.jsx("main",{className:"flex-1",children:e}),i.jsx(Vb,{})]})}const z5=jh("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",warning:"border-transparent bg-amber-600 text-amber-100 hover:bg-amber-600/80"}},defaultVariants:{variant:"default"}});function vu({className:e,variant:t,...n}){return i.jsx("div",{className:Ie(z5({variant:t}),e),...n})}function l_({status:e}){const{t}=Ve();return e?e==="open"?i.jsx(vu,{children:t("status.open")}):e==="connecting"?i.jsx(vu,{variant:"warning",children:t("status.connecting")}):e==="close"||e==="closed"?i.jsx(vu,{variant:"destructive",children:t("status.closed")}):i.jsx(vu,{variant:"secondary",children:e}):null}const U5=e=>{navigator.clipboard.writeText(e),me.success("Copiado para a área de transferência")};function c_({token:e,className:t}){const[n,r]=y.useState(!1);return i.jsxs("div",{className:Ie("flex items-center gap-3 truncate rounded-sm bg-primary/20 px-2 py-1",t),children:[i.jsx("pre",{className:"block truncate text-xs",children:n?e:e?.replace(/\w/g,"*")}),i.jsx(se,{variant:"ghost",size:"icon",onClick:()=>{U5(e)},children:i.jsx(X$,{size:"15"})}),i.jsx(se,{variant:"ghost",size:"icon",onClick:()=>{r(s=>!s)},children:n?i.jsx(tB,{size:"15"}):i.jsx(nB,{size:"15"})})]})}const So=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:Ie("flex flex-col rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));So.displayName="Card";const Co=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:Ie("flex flex-col space-y-1.5 p-6",e),...t}));Co.displayName="CardHeader";const gi=y.forwardRef(({className:e,...t},n)=>i.jsx("h3",{ref:n,className:Ie("text-2xl font-semibold leading-none tracking-tight",e),...t}));gi.displayName="CardTitle";const Kp=y.forwardRef(({className:e,...t},n)=>i.jsx("p",{ref:n,className:Ie("text-sm text-muted-foreground",e),...t}));Kp.displayName="CardDescription";const Eo=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:Ie("p-6 pt-0",e),...t}));Eo.displayName="CardContent";const Vh=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:Ie("flex items-center p-6 pt-0",e),...t}));Vh.displayName="CardFooter";const u_="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",ne=y.forwardRef(({className:e,type:t,...n},r)=>i.jsx("input",{type:t,className:Ie(u_,e),ref:r,...n}));ne.displayName="Input";const V5=["instance","fetchInstances"],H5=async()=>(await bd.get("/instance/fetchInstances")).data,q5=e=>mt({...e,queryKey:V5,queryFn:()=>H5()});function nt(e,t){const n=Ob(),r=cF({mutationFn:e});return(s,o)=>r.mutateAsync(s,{onSuccess:async(l,u,d)=>{t?.invalidateKeys&&await Promise.all(t.invalidateKeys.map(f=>n.invalidateQueries({queryKey:f}))),o?.onSuccess?.(l,u,d)},onError(l,u,d){o?.onError?.(l,u,d)},onSettled(l,u,d,f){o?.onSettled?.(l,u,d,f)}})}const K5=async e=>(await bd.post("/instance/create",e)).data,W5=async e=>(await Ee.post(`/instance/restart/${e}`)).data,G5=async e=>(await Ee.delete(`/instance/logout/${e}`)).data,J5=async e=>(await bd.delete(`/instance/delete/${e}`)).data,Q5=async({instanceName:e,token:t,number:n})=>(await Ee.get(`/instance/connect/${e}`,{headers:{apikey:t},params:{number:n}})).data,Z5=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/settings/set/${e}`,n,{headers:{apikey:t}})).data;function Hh(){const e=nt(Q5,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),t=nt(Z5,{invalidateKeys:[["instance","fetchSettings"]]}),n=nt(J5,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),r=nt(G5,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),s=nt(W5,{invalidateKeys:[["instance","fetchInstance"],["instance","fetchInstances"]]}),o=nt(K5,{invalidateKeys:[["instance","fetchInstances"]]});return{connect:e,updateSettings:t,deleteInstance:n,logout:r,restart:s,createInstance:o}}var Ed=e=>e.type==="checkbox",Tl=e=>e instanceof Date,cr=e=>e==null;const d_=e=>typeof e=="object";var $n=e=>!cr(e)&&!Array.isArray(e)&&d_(e)&&!Tl(e),f_=e=>$n(e)&&e.target?Ed(e.target)?e.target.checked:e.target.value:e,Y5=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,p_=(e,t)=>e.has(Y5(t)),X5=e=>{const t=e.constructor&&e.constructor.prototype;return $n(t)&&t.hasOwnProperty("isPrototypeOf")},jx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Er(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(jx&&(e instanceof Blob||e instanceof FileList))&&(n||$n(e)))if(t=n?[]:{},!n&&!X5(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=Er(e[r]));else return e;return t}var qh=e=>Array.isArray(e)?e.filter(Boolean):[],wn=e=>e===void 0,_e=(e,t,n)=>{if(!t||!$n(e))return n;const r=qh(t.split(/[,[\].]+?/)).reduce((s,o)=>cr(s)?s:s[o],e);return wn(r)||r===e?wn(e[t])?n:e[t]:r},Us=e=>typeof e=="boolean",Tx=e=>/^\w*$/.test(e),h_=e=>qh(e.replace(/["|']|\]/g,"").split(/\.|\[/)),qt=(e,t,n)=>{let r=-1;const s=Tx(t)?[t]:h_(t),o=s.length,l=o-1;for(;++rqe.useContext(g_),Gn=e=>{const{children:t,...n}=e;return qe.createElement(g_.Provider,{value:n},t)};var m_=(e,t,n,r=!0)=>{const s={defaultValues:t._defaultValues};for(const o in e)Object.defineProperty(s,o,{get:()=>{const l=o;return t._proxyFormState[l]!==Ss.all&&(t._proxyFormState[l]=!r||Ss.all),n&&(n[l]=!0),e[l]}});return s},Lr=e=>$n(e)&&!Object.keys(e).length,v_=(e,t,n,r)=>{n(e);const{name:s,...o}=e;return Lr(o)||Object.keys(o).length>=Object.keys(t).length||Object.keys(o).find(l=>t[l]===(!r||Ss.all))},ju=e=>Array.isArray(e)?e:[e],y_=(e,t,n)=>!e||!t||e===t||ju(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Nx(e){const t=qe.useRef(e);t.current=e,qe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function e6(e){const t=Kh(),{control:n=t.control,disabled:r,name:s,exact:o}=e||{},[l,u]=qe.useState(n._formState),d=qe.useRef(!0),f=qe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=qe.useRef(s);return h.current=s,Nx({disabled:r,next:m=>d.current&&y_(h.current,m.name,o)&&v_(m,f.current,n._updateFormState)&&u({...n._formState,...m}),subject:n._subjects.state}),qe.useEffect(()=>(d.current=!0,f.current.isValid&&n._updateValid(!0),()=>{d.current=!1}),[n]),m_(l,n,f.current,!1)}var qs=e=>typeof e=="string",b_=(e,t,n,r,s)=>qs(e)?(r&&t.watch.add(e),_e(n,e,s)):Array.isArray(e)?e.map(o=>(r&&t.watch.add(o),_e(n,o))):(r&&(t.watchAll=!0),n);function t6(e){const t=Kh(),{control:n=t.control,name:r,defaultValue:s,disabled:o,exact:l}=e||{},u=qe.useRef(r);u.current=r,Nx({disabled:o,subject:n._subjects.values,next:h=>{y_(u.current,h.name,l)&&f(Er(b_(u.current,n._names,h.values||n._formValues,!1,s)))}});const[d,f]=qe.useState(n._getWatch(r,s));return qe.useEffect(()=>n._removeUnmounted()),d}function n6(e){const t=Kh(),{name:n,disabled:r,control:s=t.control,shouldUnregister:o}=e,l=p_(s._names.array,n),u=t6({control:s,name:n,defaultValue:_e(s._formValues,n,_e(s._defaultValues,n,e.defaultValue)),exact:!0}),d=e6({control:s,name:n}),f=qe.useRef(s.register(n,{...e.rules,value:u,...Us(e.disabled)?{disabled:e.disabled}:{}}));return qe.useEffect(()=>{const h=s._options.shouldUnregister||o,m=(g,x)=>{const b=_e(s._fields,g);b&&b._f&&(b._f.mount=x)};if(m(n,!0),h){const g=Er(_e(s._options.defaultValues,n));qt(s._defaultValues,n,g),wn(_e(s._formValues,n))&&qt(s._formValues,n,g)}return()=>{(l?h&&!s._state.action:h)?s.unregister(n):m(n,!1)}},[n,s,l,o]),qe.useEffect(()=>{_e(s._fields,n)&&s._updateDisabledField({disabled:r,fields:s._fields,name:n,value:_e(s._fields,n)._f.value})},[r,n,s]),{field:{name:n,value:u,...Us(r)||d.disabled?{disabled:d.disabled||r}:{},onChange:qe.useCallback(h=>f.current.onChange({target:{value:f_(h),name:n},type:Wp.CHANGE}),[n]),onBlur:qe.useCallback(()=>f.current.onBlur({target:{value:_e(s._formValues,n),name:n},type:Wp.BLUR}),[n,s]),ref:h=>{const m=_e(s._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:d,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!_e(d.errors,n)},isDirty:{enumerable:!0,get:()=>!!_e(d.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!_e(d.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!_e(d.validatingFields,n)},error:{enumerable:!0,get:()=>_e(d.errors,n)}})}}const r6=e=>e.render(n6(e));var x_=(e,t,n,r,s)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:s||!0}}:{},h1=e=>({isOnSubmit:!e||e===Ss.onSubmit,isOnBlur:e===Ss.onBlur,isOnChange:e===Ss.onChange,isOnAll:e===Ss.all,isOnTouch:e===Ss.onTouched}),g1=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Tu=(e,t,n,r)=>{for(const s of n||Object.keys(e)){const o=_e(e,s);if(o){const{_f:l,...u}=o;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],s)&&!r)break;if(l.ref&&t(l.ref,l.name)&&!r)break;Tu(u,t)}else $n(u)&&Tu(u,t)}}};var s6=(e,t,n)=>{const r=ju(_e(e,n));return qt(r,"root",t[n]),qt(e,n,r),e},Mx=e=>e.type==="file",ga=e=>typeof e=="function",Gp=e=>{if(!jx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},vp=e=>qs(e),_x=e=>e.type==="radio",Jp=e=>e instanceof RegExp;const m1={value:!1,isValid:!1},v1={value:!0,isValid:!0};var w_=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!wn(e[0].attributes.value)?wn(e[0].value)||e[0].value===""?v1:{value:e[0].value,isValid:!0}:v1:m1}return m1};const y1={isValid:!1,value:null};var S_=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,y1):y1;function b1(e,t,n="validate"){if(vp(e)||Array.isArray(e)&&e.every(vp)||Us(e)&&!e)return{type:n,message:vp(e)?e:"",ref:t}}var ml=e=>$n(e)&&!Jp(e)?e:{value:e,message:""},x1=async(e,t,n,r,s)=>{const{ref:o,refs:l,required:u,maxLength:d,minLength:f,min:h,max:m,pattern:g,validate:x,name:b,valueAsNumber:w,mount:C,disabled:k}=e._f,j=_e(t,b);if(!C||k)return{};const M=l?l[0]:o,_=V=>{r&&M.reportValidity&&(M.setCustomValidity(Us(V)?"":V||""),M.reportValidity())},R={},N=_x(o),O=Ed(o),D=N||O,z=(w||Mx(o))&&wn(o.value)&&wn(j)||Gp(o)&&o.value===""||j===""||Array.isArray(j)&&!j.length,Q=x_.bind(null,b,n,R),pe=(V,G,W,ie=go.maxLength,re=go.minLength)=>{const Y=V?G:W;R[b]={type:V?ie:re,message:Y,ref:o,...Q(V?ie:re,Y)}};if(s?!Array.isArray(j)||!j.length:u&&(!D&&(z||cr(j))||Us(j)&&!j||O&&!w_(l).isValid||N&&!S_(l).isValid)){const{value:V,message:G}=vp(u)?{value:!!u,message:u}:ml(u);if(V&&(R[b]={type:go.required,message:G,ref:M,...Q(go.required,G)},!n))return _(G),R}if(!z&&(!cr(h)||!cr(m))){let V,G;const W=ml(m),ie=ml(h);if(!cr(j)&&!isNaN(j)){const re=o.valueAsNumber||j&&+j;cr(W.value)||(V=re>W.value),cr(ie.value)||(G=renew Date(new Date().toDateString()+" "+he),H=o.type=="time",q=o.type=="week";qs(W.value)&&j&&(V=H?Y(j)>Y(W.value):q?j>W.value:re>new Date(W.value)),qs(ie.value)&&j&&(G=H?Y(j)+V.value,ie=!cr(G.value)&&j.length<+G.value;if((W||ie)&&(pe(W,V.message,G.message),!n))return _(R[b].message),R}if(g&&!z&&qs(j)){const{value:V,message:G}=ml(g);if(Jp(V)&&!j.match(V)&&(R[b]={type:go.pattern,message:G,ref:o,...Q(go.pattern,G)},!n))return _(G),R}if(x){if(ga(x)){const V=await x(j,t),G=b1(V,M);if(G&&(R[b]={...G,...Q(go.validate,G.message)},!n))return _(G.message),R}else if($n(x)){let V={};for(const G in x){if(!Lr(V)&&!n)break;const W=b1(await x[G](j,t),M,G);W&&(V={...W,...Q(G,W.message)},_(W.message),n&&(R[b]=V))}if(!Lr(V)&&(R[b]={ref:M,...V},!n))return R}}return _(!0),R};function o6(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{let e=[];return{get observers(){return e},next:s=>{for(const o of e)o.next&&o.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(o=>o!==s)}}),unsubscribe:()=>{e=[]}}},Qp=e=>cr(e)||!d_(e);function ui(e,t){if(Qp(e)||Qp(t))return e===t;if(Tl(e)&&Tl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n){const o=e[s];if(!r.includes(s))return!1;if(s!=="ref"){const l=t[s];if(Tl(o)&&Tl(l)||$n(o)&&$n(l)||Array.isArray(o)&&Array.isArray(l)?!ui(o,l):o!==l)return!1}}return!0}var C_=e=>e.type==="select-multiple",i6=e=>_x(e)||Ed(e),_v=e=>Gp(e)&&e.isConnected,E_=e=>{for(const t in e)if(ga(e[t]))return!0;return!1};function Zp(e,t={}){const n=Array.isArray(e);if($n(e)||n)for(const r in e)Array.isArray(e[r])||$n(e[r])&&!E_(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Zp(e[r],t[r])):cr(e[r])||(t[r]=!0);return t}function k_(e,t,n){const r=Array.isArray(e);if($n(e)||r)for(const s in e)Array.isArray(e[s])||$n(e[s])&&!E_(e[s])?wn(t)||Qp(n[s])?n[s]=Array.isArray(e[s])?Zp(e[s],[]):{...Zp(e[s])}:k_(e[s],cr(t)?{}:t[s],n[s]):n[s]=!ui(e[s],t[s]);return n}var Gf=(e,t)=>k_(e,t,Zp(t)),j_=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>wn(e)?e:t?e===""?NaN:e&&+e:n&&qs(e)?new Date(e):r?r(e):e;function Rv(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Mx(t)?t.files:_x(t)?S_(e.refs).value:C_(t)?[...t.selectedOptions].map(({value:n})=>n):Ed(t)?w_(e.refs).value:j_(wn(t.value)?e.ref.value:t.value,e)}var l6=(e,t,n,r)=>{const s={};for(const o of e){const l=_e(t,o);l&&qt(s,o,l._f)}return{criteriaMode:n,names:[...e],fields:s,shouldUseNativeValidation:r}},au=e=>wn(e)?e:Jp(e)?e.source:$n(e)?Jp(e.value)?e.value.source:e.value:e,c6=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function w1(e,t,n){const r=_e(e,n);if(r||Tx(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const o=s.join("."),l=_e(t,o),u=_e(e,o);if(l&&!Array.isArray(l)&&n!==o)return{name:n};if(u&&u.type)return{name:o,error:u};s.pop()}return{name:n}}var u6=(e,t,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(t||e):(n?r.isOnBlur:s.isOnBlur)?!e:(n?r.isOnChange:s.isOnChange)?e:!0,d6=(e,t)=>!qh(_e(e,t)).length&&Dn(e,t);const f6={mode:Ss.onSubmit,reValidateMode:Ss.onChange,shouldFocusError:!0};function p6(e={}){let t={...f6,...e},n={submitCount:0,isDirty:!1,isLoading:ga(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},s=$n(t.defaultValues)||$n(t.values)?Er(t.defaultValues||t.values)||{}:{},o=t.shouldUnregister?{}:Er(s),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,f=0;const h={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},m={values:Mv(),array:Mv(),state:Mv()},g=h1(t.mode),x=h1(t.reValidateMode),b=t.criteriaMode===Ss.all,w=L=>X=>{clearTimeout(f),f=setTimeout(L,X)},C=async L=>{if(h.isValid||L){const X=t.resolver?Lr((await D()).errors):await Q(r,!0);X!==n.isValid&&m.state.next({isValid:X})}},k=(L,X)=>{(h.isValidating||h.validatingFields)&&((L||Array.from(u.mount)).forEach(ue=>{ue&&(X?qt(n.validatingFields,ue,X):Dn(n.validatingFields,ue))}),m.state.next({validatingFields:n.validatingFields,isValidating:!Lr(n.validatingFields)}))},j=(L,X=[],ue,Ne,je=!0,Se=!0)=>{if(Ne&&ue){if(l.action=!0,Se&&Array.isArray(_e(r,L))){const Be=ue(_e(r,L),Ne.argA,Ne.argB);je&&qt(r,L,Be)}if(Se&&Array.isArray(_e(n.errors,L))){const Be=ue(_e(n.errors,L),Ne.argA,Ne.argB);je&&qt(n.errors,L,Be),d6(n.errors,L)}if(h.touchedFields&&Se&&Array.isArray(_e(n.touchedFields,L))){const Be=ue(_e(n.touchedFields,L),Ne.argA,Ne.argB);je&&qt(n.touchedFields,L,Be)}h.dirtyFields&&(n.dirtyFields=Gf(s,o)),m.state.next({name:L,isDirty:V(L,X),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else qt(o,L,X)},M=(L,X)=>{qt(n.errors,L,X),m.state.next({errors:n.errors})},_=L=>{n.errors=L,m.state.next({errors:n.errors,isValid:!1})},R=(L,X,ue,Ne)=>{const je=_e(r,L);if(je){const Se=_e(o,L,wn(ue)?_e(s,L):ue);wn(Se)||Ne&&Ne.defaultChecked||X?qt(o,L,X?Se:Rv(je._f)):ie(L,Se),l.mount&&C()}},N=(L,X,ue,Ne,je)=>{let Se=!1,Be=!1;const bt={name:L},Wt=!!(_e(r,L)&&_e(r,L)._f&&_e(r,L)._f.disabled);if(!ue||Ne){h.isDirty&&(Be=n.isDirty,n.isDirty=bt.isDirty=V(),Se=Be!==bt.isDirty);const yn=Wt||ui(_e(s,L),X);Be=!!(!Wt&&_e(n.dirtyFields,L)),yn||Wt?Dn(n.dirtyFields,L):qt(n.dirtyFields,L,!0),bt.dirtyFields=n.dirtyFields,Se=Se||h.dirtyFields&&Be!==!yn}if(ue){const yn=_e(n.touchedFields,L);yn||(qt(n.touchedFields,L,ue),bt.touchedFields=n.touchedFields,Se=Se||h.touchedFields&&yn!==ue)}return Se&&je&&m.state.next(bt),Se?bt:{}},O=(L,X,ue,Ne)=>{const je=_e(n.errors,L),Se=h.isValid&&Us(X)&&n.isValid!==X;if(e.delayError&&ue?(d=w(()=>M(L,ue)),d(e.delayError)):(clearTimeout(f),d=null,ue?qt(n.errors,L,ue):Dn(n.errors,L)),(ue?!ui(je,ue):je)||!Lr(Ne)||Se){const Be={...Ne,...Se&&Us(X)?{isValid:X}:{},errors:n.errors,name:L};n={...n,...Be},m.state.next(Be)}},D=async L=>{k(L,!0);const X=await t.resolver(o,t.context,l6(L||u.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return k(L),X},z=async L=>{const{errors:X}=await D(L);if(L)for(const ue of L){const Ne=_e(X,ue);Ne?qt(n.errors,ue,Ne):Dn(n.errors,ue)}else n.errors=X;return X},Q=async(L,X,ue={valid:!0})=>{for(const Ne in L){const je=L[Ne];if(je){const{_f:Se,...Be}=je;if(Se){const bt=u.array.has(Se.name);k([Ne],!0);const Wt=await x1(je,o,b,t.shouldUseNativeValidation&&!X,bt);if(k([Ne]),Wt[Se.name]&&(ue.valid=!1,X))break;!X&&(_e(Wt,Se.name)?bt?s6(n.errors,Wt,Se.name):qt(n.errors,Se.name,Wt[Se.name]):Dn(n.errors,Se.name))}Be&&await Q(Be,X,ue)}}return ue.valid},pe=()=>{for(const L of u.unMount){const X=_e(r,L);X&&(X._f.refs?X._f.refs.every(ue=>!_v(ue)):!_v(X._f.ref))&&ge(L)}u.unMount=new Set},V=(L,X)=>(L&&X&&qt(o,L,X),!ui(A(),s)),G=(L,X,ue)=>b_(L,u,{...l.mount?o:wn(X)?s:qs(L)?{[L]:X}:X},ue,X),W=L=>qh(_e(l.mount?o:s,L,e.shouldUnregister?_e(s,L,[]):[])),ie=(L,X,ue={})=>{const Ne=_e(r,L);let je=X;if(Ne){const Se=Ne._f;Se&&(!Se.disabled&&qt(o,L,j_(X,Se)),je=Gp(Se.ref)&&cr(X)?"":X,C_(Se.ref)?[...Se.ref.options].forEach(Be=>Be.selected=je.includes(Be.value)):Se.refs?Ed(Se.ref)?Se.refs.length>1?Se.refs.forEach(Be=>(!Be.defaultChecked||!Be.disabled)&&(Be.checked=Array.isArray(je)?!!je.find(bt=>bt===Be.value):je===Be.value)):Se.refs[0]&&(Se.refs[0].checked=!!je):Se.refs.forEach(Be=>Be.checked=Be.value===je):Mx(Se.ref)?Se.ref.value="":(Se.ref.value=je,Se.ref.type||m.values.next({name:L,values:{...o}})))}(ue.shouldDirty||ue.shouldTouch)&&N(L,je,ue.shouldTouch,ue.shouldDirty,!0),ue.shouldValidate&&he(L)},re=(L,X,ue)=>{for(const Ne in X){const je=X[Ne],Se=`${L}.${Ne}`,Be=_e(r,Se);(u.array.has(L)||!Qp(je)||Be&&!Be._f)&&!Tl(je)?re(Se,je,ue):ie(Se,je,ue)}},Y=(L,X,ue={})=>{const Ne=_e(r,L),je=u.array.has(L),Se=Er(X);qt(o,L,Se),je?(m.array.next({name:L,values:{...o}}),(h.isDirty||h.dirtyFields)&&ue.shouldDirty&&m.state.next({name:L,dirtyFields:Gf(s,o),isDirty:V(L,Se)})):Ne&&!Ne._f&&!cr(Se)?re(L,Se,ue):ie(L,Se,ue),g1(L,u)&&m.state.next({...n}),m.values.next({name:l.mount?L:void 0,values:{...o}})},H=async L=>{l.mount=!0;const X=L.target;let ue=X.name,Ne=!0;const je=_e(r,ue),Se=()=>X.type?Rv(je._f):f_(L),Be=bt=>{Ne=Number.isNaN(bt)||bt===_e(o,ue,bt)};if(je){let bt,Wt;const yn=Se(),bn=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,En=!c6(je._f)&&!t.resolver&&!_e(n.errors,ue)&&!je._f.deps||u6(bn,_e(n.touchedFields,ue),n.isSubmitted,x,g),gr=g1(ue,u,bn);qt(o,ue,yn),bn?(je._f.onBlur&&je._f.onBlur(L),d&&d(0)):je._f.onChange&&je._f.onChange(L);const Qn=N(ue,yn,bn,!1),ro=!Lr(Qn)||gr;if(!bn&&m.values.next({name:ue,type:L.type,values:{...o}}),En)return h.isValid&&C(),ro&&m.state.next({name:ue,...gr?{}:Qn});if(!bn&&gr&&m.state.next({...n}),t.resolver){const{errors:Bn}=await D([ue]);if(Be(yn),Ne){const Te=w1(n.errors,r,ue),ut=w1(Bn,r,Te.name||ue);bt=ut.error,ue=ut.name,Wt=Lr(Bn)}}else k([ue],!0),bt=(await x1(je,o,b,t.shouldUseNativeValidation))[ue],k([ue]),Be(yn),Ne&&(bt?Wt=!1:h.isValid&&(Wt=await Q(r,!0)));Ne&&(je._f.deps&&he(je._f.deps),O(ue,Wt,bt,Qn))}},q=(L,X)=>{if(_e(n.errors,X)&&L.focus)return L.focus(),1},he=async(L,X={})=>{let ue,Ne;const je=ju(L);if(t.resolver){const Se=await z(wn(L)?L:je);ue=Lr(Se),Ne=L?!je.some(Be=>_e(Se,Be)):ue}else L?(Ne=(await Promise.all(je.map(async Se=>{const Be=_e(r,Se);return await Q(Be&&Be._f?{[Se]:Be}:Be)}))).every(Boolean),!(!Ne&&!n.isValid)&&C()):Ne=ue=await Q(r);return m.state.next({...!qs(L)||h.isValid&&ue!==n.isValid?{}:{name:L},...t.resolver||!L?{isValid:ue}:{},errors:n.errors}),X.shouldFocus&&!Ne&&Tu(r,q,L?je:u.mount),Ne},A=L=>{const X={...l.mount?o:s};return wn(L)?X:qs(L)?_e(X,L):L.map(ue=>_e(X,ue))},F=(L,X)=>({invalid:!!_e((X||n).errors,L),isDirty:!!_e((X||n).dirtyFields,L),error:_e((X||n).errors,L),isValidating:!!_e(n.validatingFields,L),isTouched:!!_e((X||n).touchedFields,L)}),fe=L=>{L&&ju(L).forEach(X=>Dn(n.errors,X)),m.state.next({errors:L?n.errors:{}})},te=(L,X,ue)=>{const Ne=(_e(r,L,{_f:{}})._f||{}).ref,je=_e(n.errors,L)||{},{ref:Se,message:Be,type:bt,...Wt}=je;qt(n.errors,L,{...Wt,...X,ref:Ne}),m.state.next({name:L,errors:n.errors,isValid:!1}),ue&&ue.shouldFocus&&Ne&&Ne.focus&&Ne.focus()},de=(L,X)=>ga(L)?m.values.subscribe({next:ue=>L(G(void 0,X),ue)}):G(L,X,!0),ge=(L,X={})=>{for(const ue of L?ju(L):u.mount)u.mount.delete(ue),u.array.delete(ue),X.keepValue||(Dn(r,ue),Dn(o,ue)),!X.keepError&&Dn(n.errors,ue),!X.keepDirty&&Dn(n.dirtyFields,ue),!X.keepTouched&&Dn(n.touchedFields,ue),!X.keepIsValidating&&Dn(n.validatingFields,ue),!t.shouldUnregister&&!X.keepDefaultValue&&Dn(s,ue);m.values.next({values:{...o}}),m.state.next({...n,...X.keepDirty?{isDirty:V()}:{}}),!X.keepIsValid&&C()},Z=({disabled:L,name:X,field:ue,fields:Ne,value:je})=>{if(Us(L)&&l.mount||L){const Se=L?void 0:wn(je)?Rv(ue?ue._f:_e(Ne,X)._f):je;qt(o,X,Se),N(X,Se,!1,!1,!0)}},ye=(L,X={})=>{let ue=_e(r,L);const Ne=Us(X.disabled);return qt(r,L,{...ue||{},_f:{...ue&&ue._f?ue._f:{ref:{name:L}},name:L,mount:!0,...X}}),u.mount.add(L),ue?Z({field:ue,disabled:X.disabled,name:L,value:X.value}):R(L,!0,X.value),{...Ne?{disabled:X.disabled}:{},...t.progressive?{required:!!X.required,min:au(X.min),max:au(X.max),minLength:au(X.minLength),maxLength:au(X.maxLength),pattern:au(X.pattern)}:{},name:L,onChange:H,onBlur:H,ref:je=>{if(je){ye(L,X),ue=_e(r,L);const Se=wn(je.value)&&je.querySelectorAll&&je.querySelectorAll("input,select,textarea")[0]||je,Be=i6(Se),bt=ue._f.refs||[];if(Be?bt.find(Wt=>Wt===Se):Se===ue._f.ref)return;qt(r,L,{_f:{...ue._f,...Be?{refs:[...bt.filter(_v),Se,...Array.isArray(_e(s,L))?[{}]:[]],ref:{type:Se.type,name:L}}:{ref:Se}}}),R(L,!1,void 0,Se)}else ue=_e(r,L,{}),ue._f&&(ue._f.mount=!1),(t.shouldUnregister||X.shouldUnregister)&&!(p_(u.array,L)&&l.action)&&u.unMount.add(L)}}},Re=()=>t.shouldFocusError&&Tu(r,q,u.mount),$e=L=>{Us(L)&&(m.state.next({disabled:L}),Tu(r,(X,ue)=>{const Ne=_e(r,ue);Ne&&(X.disabled=Ne._f.disabled||L,Array.isArray(Ne._f.refs)&&Ne._f.refs.forEach(je=>{je.disabled=Ne._f.disabled||L}))},0,!1))},Ye=(L,X)=>async ue=>{let Ne;ue&&(ue.preventDefault&&ue.preventDefault(),ue.persist&&ue.persist());let je=Er(o);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:Se,values:Be}=await D();n.errors=Se,je=Be}else await Q(r);if(Dn(n.errors,"root"),Lr(n.errors)){m.state.next({errors:{}});try{await L(je,ue)}catch(Se){Ne=Se}}else X&&await X({...n.errors},ue),Re(),setTimeout(Re);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Lr(n.errors)&&!Ne,submitCount:n.submitCount+1,errors:n.errors}),Ne)throw Ne},Fe=(L,X={})=>{_e(r,L)&&(wn(X.defaultValue)?Y(L,Er(_e(s,L))):(Y(L,X.defaultValue),qt(s,L,Er(X.defaultValue))),X.keepTouched||Dn(n.touchedFields,L),X.keepDirty||(Dn(n.dirtyFields,L),n.isDirty=X.defaultValue?V(L,Er(_e(s,L))):V()),X.keepError||(Dn(n.errors,L),h.isValid&&C()),m.state.next({...n}))},ft=(L,X={})=>{const ue=L?Er(L):s,Ne=Er(ue),je=Lr(L),Se=je?s:Ne;if(X.keepDefaultValues||(s=ue),!X.keepValues){if(X.keepDirtyValues)for(const Be of u.mount)_e(n.dirtyFields,Be)?qt(Se,Be,_e(o,Be)):Y(Be,_e(Se,Be));else{if(jx&&wn(L))for(const Be of u.mount){const bt=_e(r,Be);if(bt&&bt._f){const Wt=Array.isArray(bt._f.refs)?bt._f.refs[0]:bt._f.ref;if(Gp(Wt)){const yn=Wt.closest("form");if(yn){yn.reset();break}}}}r={}}o=e.shouldUnregister?X.keepDefaultValues?Er(s):{}:Er(Se),m.array.next({values:{...Se}}),m.values.next({values:{...Se}})}u={mount:X.keepDirtyValues?u.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!X.keepIsValid||!!X.keepDirtyValues,l.watch=!!e.shouldUnregister,m.state.next({submitCount:X.keepSubmitCount?n.submitCount:0,isDirty:je?!1:X.keepDirty?n.isDirty:!!(X.keepDefaultValues&&!ui(L,s)),isSubmitted:X.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:je?{}:X.keepDirtyValues?X.keepDefaultValues&&o?Gf(s,o):n.dirtyFields:X.keepDefaultValues&&L?Gf(s,L):X.keepDirty?n.dirtyFields:{},touchedFields:X.keepTouched?n.touchedFields:{},errors:X.keepErrors?n.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},ln=(L,X)=>ft(ga(L)?L(o):L,X);return{control:{register:ye,unregister:ge,getFieldState:F,handleSubmit:Ye,setError:te,_executeSchema:D,_getWatch:G,_getDirty:V,_updateValid:C,_removeUnmounted:pe,_updateFieldArray:j,_updateDisabledField:Z,_getFieldArray:W,_reset:ft,_resetDefaultValues:()=>ga(t.defaultValues)&&t.defaultValues().then(L=>{ln(L,t.resetOptions),m.state.next({isLoading:!1})}),_updateFormState:L=>{n={...n,...L}},_disableForm:$e,_subjects:m,_proxyFormState:h,_setErrors:_,get _fields(){return r},get _formValues(){return o},get _state(){return l},set _state(L){l=L},get _defaultValues(){return s},get _names(){return u},set _names(L){u=L},get _formState(){return n},set _formState(L){n=L},get _options(){return t},set _options(L){t={...t,...L}}},trigger:he,register:ye,handleSubmit:Ye,watch:de,setValue:Y,getValues:A,reset:ln,resetField:Fe,clearErrors:fe,unregister:ge,setError:te,setFocus:(L,X={})=>{const ue=_e(r,L),Ne=ue&&ue._f;if(Ne){const je=Ne.refs?Ne.refs[0]:Ne.ref;je.focus&&(je.focus(),X.shouldSelect&&je.select())}},getFieldState:F}}function on(e={}){const t=qe.useRef(),n=qe.useRef(),[r,s]=qe.useState({isDirty:!1,isValidating:!1,isLoading:ga(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,defaultValues:ga(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...p6(e),formState:r});const o=t.current.control;return o._options=e,Nx({subject:o._subjects.state,next:l=>{v_(l,o._proxyFormState,o._updateFormState,!0)&&s({...o._formState})}}),qe.useEffect(()=>o._disableForm(e.disabled),[o,e.disabled]),qe.useEffect(()=>{if(o._proxyFormState.isDirty){const l=o._getDirty();l!==r.isDirty&&o._subjects.state.next({isDirty:l})}},[o,r.isDirty]),qe.useEffect(()=>{e.values&&!ui(e.values,n.current)?(o._reset(e.values,o._options.resetOptions),n.current=e.values,s(l=>({...l}))):o._resetDefaultValues()},[e.values,o]),qe.useEffect(()=>{e.errors&&o._setErrors(e.errors)},[e.errors,o]),qe.useEffect(()=>{o._state.mount||(o._updateValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),qe.useEffect(()=>{e.shouldUnregister&&o._subjects.values.next({values:o._getWatch()})},[e.shouldUnregister,o]),t.current.formState=m_(r,o),t.current}const S1=(e,t,n)=>{if(e&&"reportValidity"in e){const r=_e(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},T_=(e,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?S1(r.ref,n,e):r.refs&&r.refs.forEach(s=>S1(s,n,e))}},h6=(e,t)=>{t.shouldUseNativeValidation&&T_(e,t);const n={};for(const r in e){const s=_e(t.fields,r),o=Object.assign(e[r]||{},{ref:s&&s.ref});if(g6(t.names||Object.keys(e),r)){const l=Object.assign({},_e(n,r));qt(l,"root",o),qt(n,r,l)}else qt(n,r,o)}return n},g6=(e,t)=>e.some(n=>n.startsWith(t+"."));var m6=function(e,t){for(var n={};e.length;){var r=e[0],s=r.code,o=r.message,l=r.path.join(".");if(!n[l])if("unionErrors"in r){var u=r.unionErrors[0].errors[0];n[l]={message:u.message,type:u.code}}else n[l]={message:o,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var d=n[l].types,f=d&&d[r.code];n[l]=x_(l,t,n,s,f?[].concat(f,r.message):r.message)}e.shift()}return n},an=function(e,t,n){return n===void 0&&(n={}),function(r,s,o){try{return Promise.resolve((function(l,u){try{var d=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return o.shouldUseNativeValidation&&T_({},o),{errors:{},values:n.raw?r:f}})}catch(f){return u(f)}return d&&d.then?d.then(void 0,u):d})(0,function(l){if((function(u){return Array.isArray(u?.errors)})(l))return{values:{},errors:h6(m6(l.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw l}))}catch(l){return Promise.reject(l)}}},Wn=[];for(var Pv=0;Pv<256;++Pv)Wn.push((Pv+256).toString(16).slice(1));function v6(e,t=0){return(Wn[e[t+0]]+Wn[e[t+1]]+Wn[e[t+2]]+Wn[e[t+3]]+"-"+Wn[e[t+4]]+Wn[e[t+5]]+"-"+Wn[e[t+6]]+Wn[e[t+7]]+"-"+Wn[e[t+8]]+Wn[e[t+9]]+"-"+Wn[e[t+10]]+Wn[e[t+11]]+Wn[e[t+12]]+Wn[e[t+13]]+Wn[e[t+14]]+Wn[e[t+15]]).toLowerCase()}var Jf,y6=new Uint8Array(16);function b6(){if(!Jf&&(Jf=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Jf))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Jf(y6)}var x6=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const C1={randomUUID:x6};function E1(e,t,n){if(C1.randomUUID&&!e)return C1.randomUUID();e=e||{};var r=e.random||(e.rng||b6)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,v6(r)}var Ot;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const o={};for(const l of s)o[l]=l;return o},e.getValidEnumValues=s=>{const o=e.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of o)l[u]=s[u];return e.objectValues(l)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&o.push(l);return o},e.find=(s,o)=>{for(const l of s)if(o(l))return l},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Ot||(Ot={}));var Gy;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Gy||(Gy={}));const Le=Ot.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pa=e=>{switch(typeof e){case"undefined":return Le.undefined;case"string":return Le.string;case"number":return isNaN(e)?Le.nan:Le.number;case"boolean":return Le.boolean;case"function":return Le.function;case"bigint":return Le.bigint;case"symbol":return Le.symbol;case"object":return Array.isArray(e)?Le.array:e===null?Le.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Le.promise:typeof Map<"u"&&e instanceof Map?Le.map:typeof Set<"u"&&e instanceof Set?Le.set:typeof Date<"u"&&e instanceof Date?Le.date:Le.object;default:return Le.unknown}},Ce=Ot.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),w6=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Hr extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(const l of o.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)r._errors.push(n(l));else{let u=r,d=0;for(;dn.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Hr.create=e=>new Hr(e);const Vl=(e,t)=>{let n;switch(e.code){case Ce.invalid_type:e.received===Le.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Ce.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ot.jsonStringifyReplacer)}`;break;case Ce.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ot.joinValues(e.keys,", ")}`;break;case Ce.invalid_union:n="Invalid input";break;case Ce.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ot.joinValues(e.options)}`;break;case Ce.invalid_enum_value:n=`Invalid enum value. Expected ${Ot.joinValues(e.options)}, received '${e.received}'`;break;case Ce.invalid_arguments:n="Invalid function arguments";break;case Ce.invalid_return_type:n="Invalid function return type";break;case Ce.invalid_date:n="Invalid date";break;case Ce.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Ot.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Ce.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case Ce.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case Ce.custom:n="Invalid input";break;case Ce.invalid_intersection_types:n="Intersection results could not be merged";break;case Ce.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Ce.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ot.assertNever(e)}return{message:n}};let N_=Vl;function S6(e){N_=e}function Yp(){return N_}const Xp=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],l={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let u="";const d=r.filter(f=>!!f).slice().reverse();for(const f of d)u=f(l,{data:t,defaultError:u}).message;return{...s,path:o,message:u}},C6=[];function Ae(e,t){const n=Yp(),r=Xp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Vl?void 0:Vl].filter(s=>!!s)});e.common.issues.push(r)}class sr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return lt;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const o=await s.key,l=await s.value;r.push({key:o,value:l})}return sr.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:o,value:l}=s;if(o.status==="aborted"||l.status==="aborted")return lt;o.status==="dirty"&&t.dirty(),l.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(r[o.value]=l.value)}return{status:t.value,value:r}}}const lt=Object.freeze({status:"aborted"}),Nl=e=>({status:"dirty",value:e}),fr=e=>({status:"valid",value:e}),Jy=e=>e.status==="aborted",Qy=e=>e.status==="dirty",Hu=e=>e.status==="valid",qu=e=>typeof Promise<"u"&&e instanceof Promise;function eh(e,t,n,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function M_(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var Ze;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Ze||(Ze={}));var yu,bu;class Qs{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const k1=(e,t)=>{if(Hu(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Hr(e.common.issues);return this._error=n,this._error}}};function yt(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(l,u)=>{var d,f;const{message:h}=e;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:(d=h??r)!==null&&d!==void 0?d:u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:(f=h??n)!==null&&f!==void 0?f:u.defaultError}},description:s}}class St{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return pa(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:pa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sr,ctx:{common:t.parent.common,data:t.data,parsedType:pa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(qu(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:pa(t)},o=this._parseSync({data:t,path:s.path,parent:s});return k1(s,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:pa(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(qu(s)?s:Promise.resolve(s));return k1(r,o)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{const l=t(s),u=()=>o.addIssue({code:Ce.custom,...r(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(d=>d?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Ms({schema:this,typeName:it.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Ws.create(this,this._def)}nullable(){return ka.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ks.create(this,this._def)}promise(){return ql.create(this,this._def)}or(t){return Ju.create([this,t],this._def)}and(t){return Qu.create(this,t,this._def)}transform(t){return new Ms({...yt(this._def),schema:this,typeName:it.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new td({...yt(this._def),innerType:this,defaultValue:n,typeName:it.ZodDefault})}brand(){return new Rx({typeName:it.ZodBranded,type:this,...yt(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new nd({...yt(this._def),innerType:this,catchValue:n,typeName:it.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return kd.create(this,t)}readonly(){return rd.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const E6=/^c[^\s-]{8,}$/i,k6=/^[0-9a-z]+$/,j6=/^[0-9A-HJKMNP-TV-Z]{26}$/,T6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,N6=/^[a-z0-9_-]{21}$/i,M6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,_6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,R6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ov;const P6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,O6=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,I6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,__="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",A6=new RegExp(`^${__}$`);function R_(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function D6(e){return new RegExp(`^${R_(e)}$`)}function P_(e){let t=`${__}T${R_(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function F6(e,t){return!!((t==="v4"||!t)&&P6.test(e)||(t==="v6"||!t)&&O6.test(e))}class Cs extends St{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Le.string){const o=this._getOrReturnCtx(t);return Ae(o,{code:Ce.invalid_type,expected:Le.string,received:o.parsedType}),lt}const r=new sr;let s;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(s=this._getOrReturnCtx(t,s),Ae(s,{code:Ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const l=t.data.length>o.value,u=t.data.lengtht.test(s),{validation:n,code:Ce.invalid_string,...Ze.errToObj(r)})}_addCheck(t){return new Cs({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ze.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ze.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ze.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ze.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ze.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ze.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ze.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ze.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ze.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ze.errToObj(t)})}datetime(t){var n,r;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(r=t?.local)!==null&&r!==void 0?r:!1,...Ze.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Ze.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Ze.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ze.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...Ze.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ze.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ze.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ze.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ze.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ze.errToObj(n)})}nonempty(t){return this.min(1,Ze.errToObj(t))}trim(){return new Cs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Cs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Cs({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Cs({checks:[],typeName:it.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...yt(e)})};function L6(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=parseInt(e.toFixed(s).replace(".","")),l=parseInt(t.toFixed(s).replace(".",""));return o%l/Math.pow(10,s)}class Sa extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Le.number){const o=this._getOrReturnCtx(t);return Ae(o,{code:Ce.invalid_type,expected:Le.number,received:o.parsedType}),lt}let r;const s=new sr;for(const o of this._def.checks)o.kind==="int"?Ot.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?L6(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.not_finite,message:o.message}),s.dirty()):Ot.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ze.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ze.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ze.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ze.toString(n))}setLimit(t,n,r,s){return new Sa({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(t){return new Sa({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ze.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ze.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ze.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ze.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ze.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ze.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ze.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ze.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ze.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&Ot.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew Sa({checks:[],typeName:it.ZodNumber,coerce:e?.coerce||!1,...yt(e)});class Ca extends St{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==Le.bigint){const o=this._getOrReturnCtx(t);return Ae(o,{code:Ce.invalid_type,expected:Le.bigint,received:o.parsedType}),lt}let r;const s=new sr;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ae(r,{code:Ce.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Ot.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ze.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ze.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ze.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ze.toString(n))}setLimit(t,n,r,s){return new Ca({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ze.toString(s)}]})}_addCheck(t){return new Ca({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ze.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ze.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ze.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ze.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ze.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Ca({checks:[],typeName:it.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...yt(e)})};class Ku extends St{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Le.boolean){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.boolean,received:r.parsedType}),lt}return fr(t.data)}}Ku.create=e=>new Ku({typeName:it.ZodBoolean,coerce:e?.coerce||!1,...yt(e)});class Ti extends St{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Le.date){const o=this._getOrReturnCtx(t);return Ae(o,{code:Ce.invalid_type,expected:Le.date,received:o.parsedType}),lt}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return Ae(o,{code:Ce.invalid_date}),lt}const r=new sr;let s;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(s=this._getOrReturnCtx(t,s),Ae(s,{code:Ce.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Ot.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ti({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ze.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ze.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Ti({checks:[],coerce:e?.coerce||!1,typeName:it.ZodDate,...yt(e)});class th extends St{_parse(t){if(this._getType(t)!==Le.symbol){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.symbol,received:r.parsedType}),lt}return fr(t.data)}}th.create=e=>new th({typeName:it.ZodSymbol,...yt(e)});class Wu extends St{_parse(t){if(this._getType(t)!==Le.undefined){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.undefined,received:r.parsedType}),lt}return fr(t.data)}}Wu.create=e=>new Wu({typeName:it.ZodUndefined,...yt(e)});class Gu extends St{_parse(t){if(this._getType(t)!==Le.null){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.null,received:r.parsedType}),lt}return fr(t.data)}}Gu.create=e=>new Gu({typeName:it.ZodNull,...yt(e)});class Hl extends St{constructor(){super(...arguments),this._any=!0}_parse(t){return fr(t.data)}}Hl.create=e=>new Hl({typeName:it.ZodAny,...yt(e)});class mi extends St{constructor(){super(...arguments),this._unknown=!0}_parse(t){return fr(t.data)}}mi.create=e=>new mi({typeName:it.ZodUnknown,...yt(e)});class Ro extends St{_parse(t){const n=this._getOrReturnCtx(t);return Ae(n,{code:Ce.invalid_type,expected:Le.never,received:n.parsedType}),lt}}Ro.create=e=>new Ro({typeName:it.ZodNever,...yt(e)});class nh extends St{_parse(t){if(this._getType(t)!==Le.undefined){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.void,received:r.parsedType}),lt}return fr(t.data)}}nh.create=e=>new nh({typeName:it.ZodVoid,...yt(e)});class ks extends St{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==Le.array)return Ae(n,{code:Ce.invalid_type,expected:Le.array,received:n.parsedType}),lt;if(s.exactLength!==null){const l=n.data.length>s.exactLength.value,u=n.data.lengths.maxLength.value&&(Ae(n,{code:Ce.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((l,u)=>s.type._parseAsync(new Qs(n,l,n.path,u)))).then(l=>sr.mergeArray(r,l));const o=[...n.data].map((l,u)=>s.type._parseSync(new Qs(n,l,n.path,u)));return sr.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new ks({...this._def,minLength:{value:t,message:Ze.toString(n)}})}max(t,n){return new ks({...this._def,maxLength:{value:t,message:Ze.toString(n)}})}length(t,n){return new ks({...this._def,exactLength:{value:t,message:Ze.toString(n)}})}nonempty(t){return this.min(1,t)}}ks.create=(e,t)=>new ks({type:e,minLength:null,maxLength:null,exactLength:null,typeName:it.ZodArray,...yt(t)});function El(e){if(e instanceof gn){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ws.create(El(r))}return new gn({...e._def,shape:()=>t})}else return e instanceof ks?new ks({...e._def,type:El(e.element)}):e instanceof Ws?Ws.create(El(e.unwrap())):e instanceof ka?ka.create(El(e.unwrap())):e instanceof Zs?Zs.create(e.items.map(t=>El(t))):e}class gn extends St{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=Ot.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==Le.object){const f=this._getOrReturnCtx(t);return Ae(f,{code:Ce.invalid_type,expected:Le.object,received:f.parsedType}),lt}const{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof Ro&&this._def.unknownKeys==="strip"))for(const f in s.data)l.includes(f)||u.push(f);const d=[];for(const f of l){const h=o[f],m=s.data[f];d.push({key:{status:"valid",value:f},value:h._parse(new Qs(s,m,s.path,f)),alwaysSet:f in s.data})}if(this._def.catchall instanceof Ro){const f=this._def.unknownKeys;if(f==="passthrough")for(const h of u)d.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(f==="strict")u.length>0&&(Ae(s,{code:Ce.unrecognized_keys,keys:u}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const h of u){const m=s.data[h];d.push({key:{status:"valid",value:h},value:f._parse(new Qs(s,m,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const f=[];for(const h of d){const m=await h.key,g=await h.value;f.push({key:m,value:g,alwaysSet:h.alwaysSet})}return f}).then(f=>sr.mergeObjectSync(r,f)):sr.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(t){return Ze.errToObj,new gn({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o,l,u;const d=(l=(o=(s=this._def).errorMap)===null||o===void 0?void 0:o.call(s,n,r).message)!==null&&l!==void 0?l:r.defaultError;return n.code==="unrecognized_keys"?{message:(u=Ze.errToObj(t).message)!==null&&u!==void 0?u:d}:{message:d}}}:{}})}strip(){return new gn({...this._def,unknownKeys:"strip"})}passthrough(){return new gn({...this._def,unknownKeys:"passthrough"})}extend(t){return new gn({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new gn({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:it.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new gn({...this._def,catchall:t})}pick(t){const n={};return Ot.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new gn({...this._def,shape:()=>n})}omit(t){const n={};return Ot.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new gn({...this._def,shape:()=>n})}deepPartial(){return El(this)}partial(t){const n={};return Ot.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new gn({...this._def,shape:()=>n})}required(t){const n={};return Ot.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ws;)o=o._def.innerType;n[r]=o}}),new gn({...this._def,shape:()=>n})}keyof(){return O_(Ot.objectKeys(this.shape))}}gn.create=(e,t)=>new gn({shape:()=>e,unknownKeys:"strip",catchall:Ro.create(),typeName:it.ZodObject,...yt(t)});gn.strictCreate=(e,t)=>new gn({shape:()=>e,unknownKeys:"strict",catchall:Ro.create(),typeName:it.ZodObject,...yt(t)});gn.lazycreate=(e,t)=>new gn({shape:e,unknownKeys:"strip",catchall:Ro.create(),typeName:it.ZodObject,...yt(t)});class Ju extends St{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(const u of o)if(u.result.status==="valid")return u.result;for(const u of o)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const l=o.map(u=>new Hr(u.ctx.common.issues));return Ae(n,{code:Ce.invalid_union,unionErrors:l}),lt}if(n.common.async)return Promise.all(r.map(async o=>{const l={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:l}),ctx:l}})).then(s);{let o;const l=[];for(const d of r){const f={...n,common:{...n.common,issues:[]},parent:null},h=d._parseSync({data:n.data,path:n.path,parent:f});if(h.status==="valid")return h;h.status==="dirty"&&!o&&(o={result:h,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const u=l.map(d=>new Hr(d));return Ae(n,{code:Ce.invalid_union,unionErrors:u}),lt}}get options(){return this._def.options}}Ju.create=(e,t)=>new Ju({options:e,typeName:it.ZodUnion,...yt(t)});const mo=e=>e instanceof Yu?mo(e.schema):e instanceof Ms?mo(e.innerType()):e instanceof Xu?[e.value]:e instanceof Ea?e.options:e instanceof ed?Ot.objectValues(e.enum):e instanceof td?mo(e._def.innerType):e instanceof Wu?[void 0]:e instanceof Gu?[null]:e instanceof Ws?[void 0,...mo(e.unwrap())]:e instanceof ka?[null,...mo(e.unwrap())]:e instanceof Rx||e instanceof rd?mo(e.unwrap()):e instanceof nd?mo(e._def.innerType):[];class Wh extends St{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Le.object)return Ae(n,{code:Ce.invalid_type,expected:Le.object,received:n.parsedType}),lt;const r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(Ae(n,{code:Ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),lt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const o of n){const l=mo(o.shape[t]);if(!l.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const u of l){if(s.has(u))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(u)}`);s.set(u,o)}}return new Wh({typeName:it.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...yt(r)})}}function Zy(e,t){const n=pa(e),r=pa(t);if(e===t)return{valid:!0,data:e};if(n===Le.object&&r===Le.object){const s=Ot.objectKeys(t),o=Ot.objectKeys(e).filter(u=>s.indexOf(u)!==-1),l={...e,...t};for(const u of o){const d=Zy(e[u],t[u]);if(!d.valid)return{valid:!1};l[u]=d.data}return{valid:!0,data:l}}else if(n===Le.array&&r===Le.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let o=0;o{if(Jy(o)||Jy(l))return lt;const u=Zy(o.value,l.value);return u.valid?((Qy(o)||Qy(l))&&n.dirty(),{status:n.value,value:u.data}):(Ae(r,{code:Ce.invalid_intersection_types}),lt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,l])=>s(o,l)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Qu.create=(e,t,n)=>new Qu({left:e,right:t,typeName:it.ZodIntersection,...yt(n)});class Zs extends St{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Le.array)return Ae(r,{code:Ce.invalid_type,expected:Le.array,received:r.parsedType}),lt;if(r.data.lengththis._def.items.length&&(Ae(r,{code:Ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((l,u)=>{const d=this._def.items[u]||this._def.rest;return d?d._parse(new Qs(r,l,r.path,u)):null}).filter(l=>!!l);return r.common.async?Promise.all(o).then(l=>sr.mergeArray(n,l)):sr.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Zs({...this._def,rest:t})}}Zs.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zs({items:e,typeName:it.ZodTuple,rest:null,...yt(t)})};class Zu extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Le.object)return Ae(r,{code:Ce.invalid_type,expected:Le.object,received:r.parsedType}),lt;const s=[],o=this._def.keyType,l=this._def.valueType;for(const u in r.data)s.push({key:o._parse(new Qs(r,u,r.path,u)),value:l._parse(new Qs(r,r.data[u],r.path,u)),alwaysSet:u in r.data});return r.common.async?sr.mergeObjectAsync(n,s):sr.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof St?new Zu({keyType:t,valueType:n,typeName:it.ZodRecord,...yt(r)}):new Zu({keyType:Cs.create(),valueType:t,typeName:it.ZodRecord,...yt(n)})}}class rh extends St{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Le.map)return Ae(r,{code:Ce.invalid_type,expected:Le.map,received:r.parsedType}),lt;const s=this._def.keyType,o=this._def.valueType,l=[...r.data.entries()].map(([u,d],f)=>({key:s._parse(new Qs(r,u,r.path,[f,"key"])),value:o._parse(new Qs(r,d,r.path,[f,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const d of l){const f=await d.key,h=await d.value;if(f.status==="aborted"||h.status==="aborted")return lt;(f.status==="dirty"||h.status==="dirty")&&n.dirty(),u.set(f.value,h.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const d of l){const f=d.key,h=d.value;if(f.status==="aborted"||h.status==="aborted")return lt;(f.status==="dirty"||h.status==="dirty")&&n.dirty(),u.set(f.value,h.value)}return{status:n.value,value:u}}}}rh.create=(e,t,n)=>new rh({valueType:t,keyType:e,typeName:it.ZodMap,...yt(n)});class Ni extends St{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Le.set)return Ae(r,{code:Ce.invalid_type,expected:Le.set,received:r.parsedType}),lt;const s=this._def;s.minSize!==null&&r.data.sizes.maxSize.value&&(Ae(r,{code:Ce.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const o=this._def.valueType;function l(d){const f=new Set;for(const h of d){if(h.status==="aborted")return lt;h.status==="dirty"&&n.dirty(),f.add(h.value)}return{status:n.value,value:f}}const u=[...r.data.values()].map((d,f)=>o._parse(new Qs(r,d,r.path,f)));return r.common.async?Promise.all(u).then(d=>l(d)):l(u)}min(t,n){return new Ni({...this._def,minSize:{value:t,message:Ze.toString(n)}})}max(t,n){return new Ni({...this._def,maxSize:{value:t,message:Ze.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Ni.create=(e,t)=>new Ni({valueType:e,minSize:null,maxSize:null,typeName:it.ZodSet,...yt(t)});class Ol extends St{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Le.function)return Ae(n,{code:Ce.invalid_type,expected:Le.function,received:n.parsedType}),lt;function r(u,d){return Xp({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yp(),Vl].filter(f=>!!f),issueData:{code:Ce.invalid_arguments,argumentsError:d}})}function s(u,d){return Xp({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yp(),Vl].filter(f=>!!f),issueData:{code:Ce.invalid_return_type,returnTypeError:d}})}const o={errorMap:n.common.contextualErrorMap},l=n.data;if(this._def.returns instanceof ql){const u=this;return fr(async function(...d){const f=new Hr([]),h=await u._def.args.parseAsync(d,o).catch(x=>{throw f.addIssue(r(d,x)),f}),m=await Reflect.apply(l,this,h);return await u._def.returns._def.type.parseAsync(m,o).catch(x=>{throw f.addIssue(s(m,x)),f})})}else{const u=this;return fr(function(...d){const f=u._def.args.safeParse(d,o);if(!f.success)throw new Hr([r(d,f.error)]);const h=Reflect.apply(l,this,f.data),m=u._def.returns.safeParse(h,o);if(!m.success)throw new Hr([s(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Ol({...this._def,args:Zs.create(t).rest(mi.create())})}returns(t){return new Ol({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Ol({args:t||Zs.create([]).rest(mi.create()),returns:n||mi.create(),typeName:it.ZodFunction,...yt(r)})}}class Yu extends St{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Yu.create=(e,t)=>new Yu({getter:e,typeName:it.ZodLazy,...yt(t)});class Xu extends St{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ae(n,{received:n.data,code:Ce.invalid_literal,expected:this._def.value}),lt}return{status:"valid",value:t.data}}get value(){return this._def.value}}Xu.create=(e,t)=>new Xu({value:e,typeName:it.ZodLiteral,...yt(t)});function O_(e,t){return new Ea({values:e,typeName:it.ZodEnum,...yt(t)})}class Ea extends St{constructor(){super(...arguments),yu.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ae(n,{expected:Ot.joinValues(r),received:n.parsedType,code:Ce.invalid_type}),lt}if(eh(this,yu)||M_(this,yu,new Set(this._def.values)),!eh(this,yu).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return Ae(n,{received:n.data,code:Ce.invalid_enum_value,options:r}),lt}return fr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Ea.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ea.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}yu=new WeakMap;Ea.create=O_;class ed extends St{constructor(){super(...arguments),bu.set(this,void 0)}_parse(t){const n=Ot.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==Le.string&&r.parsedType!==Le.number){const s=Ot.objectValues(n);return Ae(r,{expected:Ot.joinValues(s),received:r.parsedType,code:Ce.invalid_type}),lt}if(eh(this,bu)||M_(this,bu,new Set(Ot.getValidEnumValues(this._def.values))),!eh(this,bu).has(t.data)){const s=Ot.objectValues(n);return Ae(r,{received:r.data,code:Ce.invalid_enum_value,options:s}),lt}return fr(t.data)}get enum(){return this._def.values}}bu=new WeakMap;ed.create=(e,t)=>new ed({values:e,typeName:it.ZodNativeEnum,...yt(t)});class ql extends St{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Le.promise&&n.common.async===!1)return Ae(n,{code:Ce.invalid_type,expected:Le.promise,received:n.parsedType}),lt;const r=n.parsedType===Le.promise?n.data:Promise.resolve(n.data);return fr(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ql.create=(e,t)=>new ql({type:e,typeName:it.ZodPromise,...yt(t)});class Ms extends St{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===it.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:l=>{Ae(r,l),l.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const l=s.transform(r.data,o);if(r.common.async)return Promise.resolve(l).then(async u=>{if(n.value==="aborted")return lt;const d=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return d.status==="aborted"?lt:d.status==="dirty"||n.value==="dirty"?Nl(d.value):d});{if(n.value==="aborted")return lt;const u=this._def.schema._parseSync({data:l,path:r.path,parent:r});return u.status==="aborted"?lt:u.status==="dirty"||n.value==="dirty"?Nl(u.value):u}}if(s.type==="refinement"){const l=u=>{const d=s.refinement(u,o);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?lt:(u.status==="dirty"&&n.dirty(),l(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?lt:(u.status==="dirty"&&n.dirty(),l(u.value).then(()=>({status:n.value,value:u.value}))))}if(s.type==="transform")if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Hu(l))return l;const u=s.transform(l.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>Hu(l)?Promise.resolve(s.transform(l.value,o)).then(u=>({status:n.value,value:u})):l);Ot.assertNever(s)}}Ms.create=(e,t,n)=>new Ms({schema:e,typeName:it.ZodEffects,effect:t,...yt(n)});Ms.createWithPreprocess=(e,t,n)=>new Ms({schema:t,effect:{type:"preprocess",transform:e},typeName:it.ZodEffects,...yt(n)});class Ws extends St{_parse(t){return this._getType(t)===Le.undefined?fr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ws.create=(e,t)=>new Ws({innerType:e,typeName:it.ZodOptional,...yt(t)});class ka extends St{_parse(t){return this._getType(t)===Le.null?fr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ka.create=(e,t)=>new ka({innerType:e,typeName:it.ZodNullable,...yt(t)});class td extends St{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===Le.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}td.create=(e,t)=>new td({innerType:e,typeName:it.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...yt(t)});class nd extends St{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return qu(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Hr(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Hr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}nd.create=(e,t)=>new nd({innerType:e,typeName:it.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...yt(t)});class sh extends St{_parse(t){if(this._getType(t)!==Le.nan){const r=this._getOrReturnCtx(t);return Ae(r,{code:Ce.invalid_type,expected:Le.nan,received:r.parsedType}),lt}return{status:"valid",value:t.data}}}sh.create=e=>new sh({typeName:it.ZodNaN,...yt(e)});const $6=Symbol("zod_brand");class Rx extends St{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class kd extends St{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?lt:o.status==="dirty"?(n.dirty(),Nl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?lt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new kd({in:t,out:n,typeName:it.ZodPipeline})}}class rd extends St{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Hu(s)&&(s.value=Object.freeze(s.value)),s);return qu(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}rd.create=(e,t)=>new rd({innerType:e,typeName:it.ZodReadonly,...yt(t)});function I_(e,t={},n){return e?Hl.create().superRefine((r,s)=>{var o,l;if(!e(r)){const u=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,d=(l=(o=u.fatal)!==null&&o!==void 0?o:n)!==null&&l!==void 0?l:!0,f=typeof u=="string"?{message:u}:u;s.addIssue({code:"custom",...f,fatal:d})}}):Hl.create()}const B6={object:gn.lazycreate};var it;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(it||(it={}));const z6=(e,t={message:`Input not instance of ${e.name}`})=>I_(n=>n instanceof e,t),A_=Cs.create,D_=Sa.create,U6=sh.create,V6=Ca.create,F_=Ku.create,H6=Ti.create,q6=th.create,K6=Wu.create,W6=Gu.create,G6=Hl.create,J6=mi.create,Q6=Ro.create,Z6=nh.create,Y6=ks.create,X6=gn.create,e8=gn.strictCreate,t8=Ju.create,n8=Wh.create,r8=Qu.create,s8=Zs.create,o8=Zu.create,a8=rh.create,i8=Ni.create,l8=Ol.create,c8=Yu.create,u8=Xu.create,d8=Ea.create,f8=ed.create,p8=ql.create,j1=Ms.create,h8=Ws.create,g8=ka.create,m8=Ms.createWithPreprocess,v8=kd.create,y8=()=>A_().optional(),b8=()=>D_().optional(),x8=()=>F_().optional(),w8={string:(e=>Cs.create({...e,coerce:!0})),number:(e=>Sa.create({...e,coerce:!0})),boolean:(e=>Ku.create({...e,coerce:!0})),bigint:(e=>Ca.create({...e,coerce:!0})),date:(e=>Ti.create({...e,coerce:!0}))},S8=lt;var P=Object.freeze({__proto__:null,defaultErrorMap:Vl,setErrorMap:S6,getErrorMap:Yp,makeIssue:Xp,EMPTY_PATH:C6,addIssueToContext:Ae,ParseStatus:sr,INVALID:lt,DIRTY:Nl,OK:fr,isAborted:Jy,isDirty:Qy,isValid:Hu,isAsync:qu,get util(){return Ot},get objectUtil(){return Gy},ZodParsedType:Le,getParsedType:pa,ZodType:St,datetimeRegex:P_,ZodString:Cs,ZodNumber:Sa,ZodBigInt:Ca,ZodBoolean:Ku,ZodDate:Ti,ZodSymbol:th,ZodUndefined:Wu,ZodNull:Gu,ZodAny:Hl,ZodUnknown:mi,ZodNever:Ro,ZodVoid:nh,ZodArray:ks,ZodObject:gn,ZodUnion:Ju,ZodDiscriminatedUnion:Wh,ZodIntersection:Qu,ZodTuple:Zs,ZodRecord:Zu,ZodMap:rh,ZodSet:Ni,ZodFunction:Ol,ZodLazy:Yu,ZodLiteral:Xu,ZodEnum:Ea,ZodNativeEnum:ed,ZodPromise:ql,ZodEffects:Ms,ZodTransformer:Ms,ZodOptional:Ws,ZodNullable:ka,ZodDefault:td,ZodCatch:nd,ZodNaN:sh,BRAND:$6,ZodBranded:Rx,ZodPipeline:kd,ZodReadonly:rd,custom:I_,Schema:St,ZodSchema:St,late:B6,get ZodFirstPartyTypeKind(){return it},coerce:w8,any:G6,array:Y6,bigint:V6,boolean:F_,date:H6,discriminatedUnion:n8,effect:j1,enum:d8,function:l8,instanceof:z6,intersection:r8,lazy:c8,literal:u8,map:a8,nan:U6,nativeEnum:f8,never:Q6,null:W6,nullable:g8,number:D_,object:X6,oboolean:x8,onumber:b8,optional:h8,ostring:y8,pipeline:v8,preprocess:m8,promise:p8,record:o8,set:i8,strictObject:e8,string:A_,symbol:q6,transformer:j1,tuple:s8,undefined:K6,union:t8,unknown:J6,void:Z6,NEVER:S8,ZodIssueCode:Ce,quotelessJson:w6,ZodError:Hr}),L_=y.createContext({dragDropManager:void 0}),os;(function(e){e.SOURCE="SOURCE",e.TARGET="TARGET"})(os||(os={}));function gt(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s-1})}var T8={type:Px,payload:{clientOffset:null,sourceClientOffset:null}};function N8(e){return function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{publishSource:!0},s=r.publishSource,o=s===void 0?!0:s,l=r.clientOffset,u=r.getSourceClientOffset,d=e.getMonitor(),f=e.getRegistry();e.dispatch(T1(l)),M8(n,d,f);var h=P8(n,d);if(h===null){e.dispatch(T8);return}var m=null;if(l){if(!u)throw new Error("getSourceClientOffset must be defined");_8(u),m=u(h)}e.dispatch(T1(l,m));var g=f.getSource(h),x=g.beginDrag(d,h);if(x!=null){R8(x),f.pinSource(h);var b=f.getSourceType(h);return{type:Gh,payload:{itemType:b,item:x,sourceId:h,clientOffset:l||null,sourceClientOffset:m||null,isSourcePublic:!!o}}}}}function M8(e,t,n){gt(!t.isDragging(),"Cannot call beginDrag while dragging."),e.forEach(function(r){gt(n.getSource(r),"Expected sourceIds to be registered.")})}function _8(e){gt(typeof e=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function R8(e){gt($_(e),"Item must be an object.")}function P8(e,t){for(var n=null,r=e.length-1;r>=0;r--)if(t.canDragSource(e[r])){n=e[r];break}return n}function O8(e){return function(){var n=e.getMonitor();if(n.isDragging())return{type:Ox}}}function Yy(e,t){return t===null?e===null:Array.isArray(e)?e.some(function(n){return n===t}):e===t}function I8(e){return function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=r.clientOffset;A8(n);var o=n.slice(0),l=e.getMonitor(),u=e.getRegistry();D8(o,l,u);var d=l.getItemType();return F8(o,u,d),L8(o,l,u),{type:Jh,payload:{targetIds:o,clientOffset:s||null}}}}function A8(e){gt(Array.isArray(e),"Expected targetIds to be an array.")}function D8(e,t,n){gt(t.isDragging(),"Cannot call hover while not dragging."),gt(!t.didDrop(),"Cannot call hover after drop.");for(var r=0;r=0;r--){var s=e[r],o=t.getTargetType(s);Yy(o,n)||e.splice(r,1)}}function L8(e,t,n){e.forEach(function(r){var s=n.getTarget(r);s.hover(t,r)})}function N1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function M1(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},r=e.getMonitor(),s=e.getRegistry();z8(r);var o=H8(r);o.forEach(function(l,u){var d=U8(l,u,s,r),f={type:Qh,payload:{dropResult:M1(M1({},n),d)}};e.dispatch(f)})}}function z8(e){gt(e.isDragging(),"Cannot call drop while not dragging."),gt(!e.didDrop(),"Cannot call drop twice during one drag operation.")}function U8(e,t,n,r){var s=n.getTarget(e),o=s?s.drop(r,e):void 0;return V8(o),typeof o>"u"&&(o=t===0?{}:r.getDropResult()),o}function V8(e){gt(typeof e>"u"||$_(e),"Drop result must either be an object or undefined.")}function H8(e){var t=e.getTargetIds().filter(e.canDropOnTarget,e);return t.reverse(),t}function q8(e){return function(){var n=e.getMonitor(),r=e.getRegistry();K8(n);var s=n.getSourceId();if(s!=null){var o=r.getSource(s,!0);o.endDrag(n,s),r.unpinSource()}return{type:Zh}}}function K8(e){gt(e.isDragging(),"Cannot call endDrag while not dragging.")}function W8(e){return{beginDrag:N8(e),publishDragSource:O8(e),hover:I8(e),drop:B8(e),endDrag:q8(e)}}function G8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function J8(e,t){for(var n=0;n0;r.backend&&(s&&!r.isSetUp?(r.backend.setup(),r.isSetUp=!0):!s&&r.isSetUp&&(r.backend.teardown(),r.isSetUp=!1))}),this.store=t,this.monitor=n,t.subscribe(this.handleRefCountChange)}return Q8(e,[{key:"receiveBackend",value:function(n){this.backend=n}},{key:"getMonitor",value:function(){return this.monitor}},{key:"getBackend",value:function(){return this.backend}},{key:"getRegistry",value:function(){return this.monitor.registry}},{key:"getActions",value:function(){var n=this,r=this.store.dispatch;function s(l){return function(){for(var u=arguments.length,d=new Array(u),f=0;f"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(ns(1));return n(B_)(e,t)}if(typeof e!="function")throw new Error(ns(2));var s=e,o=t,l=[],u=l,d=!1;function f(){u===l&&(u=l.slice())}function h(){if(d)throw new Error(ns(3));return o}function m(w){if(typeof w!="function")throw new Error(ns(4));if(d)throw new Error(ns(5));var C=!0;return f(),u.push(w),function(){if(C){if(d)throw new Error(ns(6));C=!1,f();var j=u.indexOf(w);u.splice(j,1),l=null}}}function g(w){if(!Y8(w))throw new Error(ns(7));if(typeof w.type>"u")throw new Error(ns(8));if(d)throw new Error(ns(9));try{d=!0,o=s(o,w)}finally{d=!1}for(var C=l=u,k=0;k2&&arguments[2]!==void 0?arguments[2]:X8;if(e.length!==t.length)return!1;for(var r=0;r0&&arguments[0]!==void 0?arguments[0]:A1,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Px:case Gh:return{initialSourceClientOffset:n.sourceClientOffset,initialClientOffset:n.clientOffset,clientOffset:n.clientOffset};case Jh:return eV(e.clientOffset,n.clientOffset)?e:I1(I1({},e),{},{clientOffset:n.clientOffset});case Zh:case Qh:return A1;default:return e}}var Ix="dnd-core/ADD_SOURCE",Ax="dnd-core/ADD_TARGET",Dx="dnd-core/REMOVE_SOURCE",Yh="dnd-core/REMOVE_TARGET";function sV(e){return{type:Ix,payload:{sourceId:e}}}function oV(e){return{type:Ax,payload:{targetId:e}}}function aV(e){return{type:Dx,payload:{sourceId:e}}}function iV(e){return{type:Yh,payload:{targetId:e}}}function D1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:cV,t=arguments.length>1?arguments[1]:void 0,n=t.payload;switch(t.type){case Gh:return rs(rs({},e),{},{itemType:n.itemType,item:n.item,sourceId:n.sourceId,isSourcePublic:n.isSourcePublic,dropResult:null,didDrop:!1});case Ox:return rs(rs({},e),{},{isSourcePublic:!0});case Jh:return rs(rs({},e),{},{targetIds:n.targetIds});case Yh:return e.targetIds.indexOf(n.targetId)===-1?e:rs(rs({},e),{},{targetIds:E8(e.targetIds,n.targetId)});case Qh:return rs(rs({},e),{},{dropResult:n.dropResult,didDrop:!0,targetIds:[]});case Zh:return rs(rs({},e),{},{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}function dV(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case Ix:case Ax:return e+1;case Dx:case Yh:return e-1;default:return e}}var oh=[],Fx=[];oh.__IS_NONE__=!0;Fx.__IS_ALL__=!0;function fV(e,t){if(e===oh)return!1;if(e===Fx||typeof t>"u")return!0;var n=j8(t,e);return n.length>0}function pV(){var e=arguments.length>1?arguments[1]:void 0;switch(e.type){case Jh:break;case Ix:case Ax:case Yh:case Dx:return oh;case Gh:case Ox:case Zh:case Qh:default:return Fx}var t=e.payload,n=t.targetIds,r=n===void 0?[]:n,s=t.prevTargetIds,o=s===void 0?[]:s,l=k8(r,o),u=l.length>0||!tV(r,o);if(!u)return oh;var d=o[o.length-1],f=r[r.length-1];return d!==f&&(d&&l.push(d),f&&l.push(f)),l}function hV(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return e+1}function F1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function L1(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return{dirtyHandlerIds:pV(e.dirtyHandlerIds,{type:t.type,payload:L1(L1({},t.payload),{},{prevTargetIds:C8(e,"dragOperation.targetIds",[])})}),dragOffset:rV(e.dragOffset,t),refCount:dV(e.refCount,t),dragOperation:uV(e.dragOperation,t),stateId:hV(e.stateId)}}function vV(e,t){return{x:e.x+t.x,y:e.y+t.y}}function z_(e,t){return{x:e.x-t.x,y:e.y-t.y}}function yV(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return!t||!n||!r?null:z_(vV(t,r),n)}function bV(e){var t=e.clientOffset,n=e.initialClientOffset;return!t||!n?null:z_(t,n)}function xV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function wV(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{handlerIds:void 0},o=s.handlerIds;gt(typeof n=="function","listener must be a function."),gt(typeof o>"u"||Array.isArray(o),"handlerIds, when specified, must be an array of strings.");var l=this.store.getState().stateId,u=function(){var f=r.store.getState(),h=f.stateId;try{var m=h===l||h===l+1&&!fV(f.dirtyHandlerIds,o);m||n()}finally{l=h}};return this.store.subscribe(u)}},{key:"subscribeToOffsetChange",value:function(n){var r=this;gt(typeof n=="function","listener must be a function.");var s=this.store.getState().dragOffset,o=function(){var u=r.store.getState().dragOffset;u!==s&&(s=u,n())};return this.store.subscribe(o)}},{key:"canDragSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n);return gt(r,"Expected to find a valid source. sourceId=".concat(n)),this.isDragging()?!1:r.canDrag(this,n)}},{key:"canDropOnTarget",value:function(n){if(!n)return!1;var r=this.registry.getTarget(n);if(gt(r,"Expected to find a valid target. targetId=".concat(n)),!this.isDragging()||this.didDrop())return!1;var s=this.registry.getTargetType(n),o=this.getItemType();return Yy(s,o)&&r.canDrop(this,n)}},{key:"isDragging",value:function(){return!!this.getItemType()}},{key:"isDraggingSource",value:function(n){if(!n)return!1;var r=this.registry.getSource(n,!0);if(gt(r,"Expected to find a valid source. sourceId=".concat(n)),!this.isDragging()||!this.isSourcePublic())return!1;var s=this.registry.getSourceType(n),o=this.getItemType();return s!==o?!1:r.isDragging(this,n)}},{key:"isOverTarget",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shallow:!1};if(!n)return!1;var s=r.shallow;if(!this.isDragging())return!1;var o=this.registry.getTargetType(n),l=this.getItemType();if(l&&!Yy(o,l))return!1;var u=this.getTargetIds();if(!u.length)return!1;var d=u.indexOf(n);return s?d===u.length-1:d>-1}},{key:"getItemType",value:function(){return this.store.getState().dragOperation.itemType}},{key:"getItem",value:function(){return this.store.getState().dragOperation.item}},{key:"getSourceId",value:function(){return this.store.getState().dragOperation.sourceId}},{key:"getTargetIds",value:function(){return this.store.getState().dragOperation.targetIds}},{key:"getDropResult",value:function(){return this.store.getState().dragOperation.dropResult}},{key:"didDrop",value:function(){return this.store.getState().dragOperation.didDrop}},{key:"isSourcePublic",value:function(){return!!this.store.getState().dragOperation.isSourcePublic}},{key:"getInitialClientOffset",value:function(){return this.store.getState().dragOffset.initialClientOffset}},{key:"getInitialSourceClientOffset",value:function(){return this.store.getState().dragOffset.initialSourceClientOffset}},{key:"getClientOffset",value:function(){return this.store.getState().dragOffset.clientOffset}},{key:"getSourceClientOffset",value:function(){return yV(this.store.getState().dragOffset)}},{key:"getDifferenceFromInitialOffset",value:function(){return bV(this.store.getState().dragOffset)}}]),e})(),EV=0;function kV(){return EV++}function bp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bp=function(n){return typeof n}:bp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},bp(e)}function jV(e){gt(typeof e.canDrag=="function","Expected canDrag to be a function."),gt(typeof e.beginDrag=="function","Expected beginDrag to be a function."),gt(typeof e.endDrag=="function","Expected endDrag to be a function.")}function TV(e){gt(typeof e.canDrop=="function","Expected canDrop to be a function."),gt(typeof e.hover=="function","Expected hover to be a function."),gt(typeof e.drop=="function","Expected beginDrag to be a function.")}function Xy(e,t){if(t&&Array.isArray(e)){e.forEach(function(n){return Xy(n,!1)});return}gt(typeof e=="string"||bp(e)==="symbol",t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}const B1=typeof global<"u"?global:self,U_=B1.MutationObserver||B1.WebKitMutationObserver;function V_(e){return function(){const n=setTimeout(s,0),r=setInterval(s,50);function s(){clearTimeout(n),clearInterval(r),e()}}}function NV(e){let t=1;const n=new U_(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}const MV=typeof U_=="function"?NV:V_;class _V{enqueueTask(t){const{queue:n,requestFlush:r}=this;n.length||(r(),this.flushing=!0),n[n.length]=t}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:t}=this;for(;this.indexthis.capacity){for(let r=0,s=t.length-this.index;r{this.pendingErrors.push(t),this.requestErrorThrow()},this.requestFlush=MV(this.flush),this.requestErrorThrow=V_(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class RV{call(){try{this.task&&this.task()}catch(t){this.onError(t)}finally{this.task=null,this.release(this)}}constructor(t,n){this.onError=t,this.release=n,this.task=null}}class PV{create(t){const n=this.freeTasks,r=n.length?n.pop():new RV(this.onError,s=>n[n.length]=s);return r.task=t,r}constructor(t){this.onError=t,this.freeTasks=[]}}const H_=new _V,OV=new PV(H_.registerPendingError);function IV(e){H_.enqueueTask(OV.create(e))}function AV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function DV(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:!1;gt(this.isSourceId(n),"Expected a valid source ID.");var s=r&&n===this.pinnedSourceId,o=s?this.pinnedSource:this.dragSources.get(n);return o}},{key:"getTarget",value:function(n){return gt(this.isTargetId(n),"Expected a valid target ID."),this.dropTargets.get(n)}},{key:"getSourceType",value:function(n){return gt(this.isSourceId(n),"Expected a valid source ID."),this.types.get(n)}},{key:"getTargetType",value:function(n){return gt(this.isTargetId(n),"Expected a valid target ID."),this.types.get(n)}},{key:"isSourceId",value:function(n){var r=U1(n);return r===os.SOURCE}},{key:"isTargetId",value:function(n){var r=U1(n);return r===os.TARGET}},{key:"removeSource",value:function(n){var r=this;gt(this.getSource(n),"Expected an existing source."),this.store.dispatch(aV(n)),IV(function(){r.dragSources.delete(n),r.types.delete(n)})}},{key:"removeTarget",value:function(n){gt(this.getTarget(n),"Expected an existing target."),this.store.dispatch(iV(n)),this.dropTargets.delete(n),this.types.delete(n)}},{key:"pinSource",value:function(n){var r=this.getSource(n);gt(r,"Expected an existing source."),this.pinnedSourceId=n,this.pinnedSource=r}},{key:"unpinSource",value:function(){gt(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}},{key:"addHandler",value:function(n,r,s){var o=VV(n);return this.types.set(o,r),n===os.SOURCE?this.dragSources.set(o,s):n===os.TARGET&&this.dropTargets.set(o,s),o}}]),e})();function qV(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=KV(r),o=new CV(s,new HV(s)),l=new Z8(s,o),u=e(l,t,n);return l.receiveBackend(u),l}function KV(e){var t=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__;return B_(mV,e&&t&&t({name:"dnd-core",instanceId:"dnd-core"}))}var WV=["children"];function GV(e,t){return YV(e)||ZV(e,t)||QV(e,t)||JV()}function JV(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function QV(e,t){if(e){if(typeof e=="string")return H1(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return H1(e,t)}}function H1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function eH(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o=0)&&(n[s]=e[s]);return n}var q1=0,xp=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__"),tH=y.memo(function(t){var n=t.children,r=XV(t,WV),s=nH(r),o=GV(s,2),l=o[0],u=o[1];return y.useEffect(function(){if(u){var d=q_();return++q1,function(){--q1===0&&(d[xp]=null)}}},[]),i.jsx(L_.Provider,Object.assign({value:l},{children:n}),void 0)});function nH(e){if("manager"in e){var t={dragDropManager:e.manager};return[t,!1]}var n=rH(e.backend,e.context,e.options,e.debugMode),r=!e.context;return[n,r]}function rH(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:q_(),n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0,s=t;return s[xp]||(s[xp]={dragDropManager:qV(e,t,n,r)}),s[xp]}function q_(){return typeof global<"u"?global:window}function sH(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function oH(e,t){for(var n=0;n, or turn it into a ")+"drag source or a drop target itself.")}}function pH(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!y.isValidElement(t)){var r=t;return e(r,n),r}var s=t;fH(s);var o=n?function(l){return e(l,n)}:e;return hH(s,o)}}function K_(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n];if(n.endsWith("Ref"))t[n]=e[n];else{var s=pH(r);t[n]=function(){return s}}}),t}function G1(e,t){typeof e=="function"?e(t):e.current=t}function hH(e,t){var n=e.ref;return gt(typeof n!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),n?y.cloneElement(e,{ref:function(s){G1(n,s),G1(t,s)}}):y.cloneElement(e,{ref:t})}function wp(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wp=function(n){return typeof n}:wp=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},wp(e)}function eb(e){return e!==null&&wp(e)==="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function tb(e,t,n,r){var s=void 0;if(s!==void 0)return!!s;if(e===t)return!0;if(typeof e!="object"||!e||typeof t!="object"||!t)return!1;var o=Object.keys(e),l=Object.keys(t);if(o.length!==l.length)return!1;for(var u=Object.prototype.hasOwnProperty.bind(t),d=0;de.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n0}},{key:"leave",value:function(n){var r=this.entered.length;return this.entered=Eq(this.entered.filter(this.isNodeInDocument),n),r>0&&this.entered.length===0}},{key:"reset",value:function(){this.entered=[]}}]),e})(),_q=J_(function(){return/firefox/i.test(navigator.userAgent)}),Q_=J_(function(){return!!window.safari});function Rq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Pq(e,t){for(var n=0;nn)h=m-1;else return s[m]}d=Math.max(0,h);var x=n-r[d],b=x*x;return s[d]+o[d]*x+l[d]*b+u[d]*x*b}}]),e})(),Iq=1;function Z_(e){var t=e.nodeType===Iq?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,s=n.left;return{x:s,y:r}}function Qf(e){return{x:e.clientX,y:e.clientY}}function Aq(e){var t;return e.nodeName==="IMG"&&(_q()||!((t=document.documentElement)!==null&&t!==void 0&&t.contains(e)))}function Dq(e,t,n,r){var s=e?t.width:n,o=e?t.height:r;return Q_()&&e&&(o/=window.devicePixelRatio,s/=window.devicePixelRatio),{dragPreviewWidth:s,dragPreviewHeight:o}}function Fq(e,t,n,r,s){var o=Aq(t),l=o?e:t,u=Z_(l),d={x:n.x-u.x,y:n.y-u.y},f=e.offsetWidth,h=e.offsetHeight,m=r.anchorX,g=r.anchorY,x=Dq(o,t,f,h),b=x.dragPreviewWidth,w=x.dragPreviewHeight,C=function(){var O=new nE([0,.5,1],[d.y,d.y/h*w,d.y+w-h]),D=O.interpolate(g);return Q_()&&o&&(D+=(window.devicePixelRatio-1)*w),D},k=function(){var O=new nE([0,.5,1],[d.x,d.x/f*b,d.x+b-f]);return O.interpolate(m)},j=s.offsetX,M=s.offsetY,_=j===0||j,R=M===0||M;return{x:_?j:k(),y:R?M:C()}}var Y_="__NATIVE_FILE__",X_="__NATIVE_URL__",eR="__NATIVE_TEXT__",tR="__NATIVE_HTML__";const rE=Object.freeze(Object.defineProperty({__proto__:null,FILE:Y_,HTML:tR,TEXT:eR,URL:X_},Symbol.toStringTag,{value:"Module"}));function $v(e,t,n){var r=t.reduce(function(s,o){return s||e.getData(o)},"");return r??n}var yl;function Zf(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var rb=(yl={},Zf(yl,Y_,{exposeProperties:{files:function(t){return Array.prototype.slice.call(t.files)},items:function(t){return t.items},dataTransfer:function(t){return t}},matchesTypes:["Files"]}),Zf(yl,tR,{exposeProperties:{html:function(t,n){return $v(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Html","text/html"]}),Zf(yl,X_,{exposeProperties:{urls:function(t,n){return $v(t,n,"").split(` +`)},dataTransfer:function(t){return t}},matchesTypes:["Url","text/uri-list"]}),Zf(yl,eR,{exposeProperties:{text:function(t,n){return $v(t,n,"")},dataTransfer:function(t){return t}},matchesTypes:["Text","text/plain"]}),yl);function Lq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $q(e,t){for(var n=0;n-1})})[0]||null}function Vq(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Hq(e,t){for(var n=0;n0&&s.actions.hover(l,{clientOffset:Qf(o)});var u=l.some(function(d){return s.monitor.canDropOnTarget(d)});u&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect()))}}),jt(this,"handleTopDragOverCapture",function(){s.dragOverTargetIds=[]}),jt(this,"handleTopDragOver",function(o){var l=s.dragOverTargetIds;if(s.dragOverTargetIds=[],!s.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}s.altKeyPressed=o.altKey,s.lastClientOffset=Qf(o),s.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(s.hoverRafId=requestAnimationFrame(function(){s.monitor.isDragging()&&s.actions.hover(l||[],{clientOffset:s.lastClientOffset}),s.hoverRafId=null}));var u=(l||[]).some(function(d){return s.monitor.canDropOnTarget(d)});u?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=s.getCurrentDropEffect())):s.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))}),jt(this,"handleTopDragLeaveCapture",function(o){s.isDraggingNativeItem()&&o.preventDefault();var l=s.enterLeaveCounter.leave(o.target);l&&s.isDraggingNativeItem()&&setTimeout(function(){return s.endDragNativeItem()},0)}),jt(this,"handleTopDropCapture",function(o){if(s.dropTargetIds=[],s.isDraggingNativeItem()){var l;o.preventDefault(),(l=s.currentNativeSource)===null||l===void 0||l.loadDataTransfer(o.dataTransfer)}else Bv(o.dataTransfer)&&o.preventDefault();s.enterLeaveCounter.reset()}),jt(this,"handleTopDrop",function(o){var l=s.dropTargetIds;s.dropTargetIds=[],s.actions.hover(l,{clientOffset:Qf(o)}),s.actions.drop({dropEffect:s.getCurrentDropEffect()}),s.isDraggingNativeItem()?s.endDragNativeItem():s.monitor.isDragging()&&s.actions.endDrag()}),jt(this,"handleSelectStart",function(o){var l=o.target;typeof l.dragDrop=="function"&&(l.tagName==="INPUT"||l.tagName==="SELECT"||l.tagName==="TEXTAREA"||l.isContentEditable||(o.preventDefault(),l.dragDrop()))}),this.options=new Kq(n,r),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.enterLeaveCounter=new Mq(this.isNodeInDocument)}return Jq(e,[{key:"profile",value:function(){var n,r;return{sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,sourceNodeOptions:this.sourceNodeOptions.size,sourceNodes:this.sourceNodes.size,dragStartSourceIds:((n=this.dragStartSourceIds)===null||n===void 0?void 0:n.length)||0,dropTargetIds:this.dropTargetIds.length,dragEnterTargetIds:this.dragEnterTargetIds.length,dragOverTargetIds:((r=this.dragOverTargetIds)===null||r===void 0?void 0:r.length)||0}}},{key:"window",get:function(){return this.options.window}},{key:"document",get:function(){return this.options.document}},{key:"rootElement",get:function(){return this.options.rootElement}},{key:"setup",value:function(){var n=this.rootElement;if(n!==void 0){if(n.__isReactDndBackendSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");n.__isReactDndBackendSetUp=!0,this.addEventListeners(n)}}},{key:"teardown",value:function(){var n=this.rootElement;if(n!==void 0&&(n.__isReactDndBackendSetUp=!1,this.removeEventListeners(this.rootElement),this.clearCurrentDragSourceNode(),this.asyncEndDragFrameId)){var r;(r=this.window)===null||r===void 0||r.cancelAnimationFrame(this.asyncEndDragFrameId)}}},{key:"connectDragPreview",value:function(n,r,s){var o=this;return this.sourcePreviewNodeOptions.set(n,s),this.sourcePreviewNodes.set(n,r),function(){o.sourcePreviewNodes.delete(n),o.sourcePreviewNodeOptions.delete(n)}}},{key:"connectDragSource",value:function(n,r,s){var o=this;this.sourceNodes.set(n,r),this.sourceNodeOptions.set(n,s);var l=function(f){return o.handleDragStart(f,n)},u=function(f){return o.handleSelectStart(f)};return r.setAttribute("draggable","true"),r.addEventListener("dragstart",l),r.addEventListener("selectstart",u),function(){o.sourceNodes.delete(n),o.sourceNodeOptions.delete(n),r.removeEventListener("dragstart",l),r.removeEventListener("selectstart",u),r.setAttribute("draggable","false")}}},{key:"connectDropTarget",value:function(n,r){var s=this,o=function(f){return s.handleDragEnter(f,n)},l=function(f){return s.handleDragOver(f,n)},u=function(f){return s.handleDrop(f,n)};return r.addEventListener("dragenter",o),r.addEventListener("dragover",l),r.addEventListener("drop",u),function(){r.removeEventListener("dragenter",o),r.removeEventListener("dragover",l),r.removeEventListener("drop",u)}}},{key:"addEventListeners",value:function(n){n.addEventListener&&(n.addEventListener("dragstart",this.handleTopDragStart),n.addEventListener("dragstart",this.handleTopDragStartCapture,!0),n.addEventListener("dragend",this.handleTopDragEndCapture,!0),n.addEventListener("dragenter",this.handleTopDragEnter),n.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.addEventListener("dragover",this.handleTopDragOver),n.addEventListener("dragover",this.handleTopDragOverCapture,!0),n.addEventListener("drop",this.handleTopDrop),n.addEventListener("drop",this.handleTopDropCapture,!0))}},{key:"removeEventListeners",value:function(n){n.removeEventListener&&(n.removeEventListener("dragstart",this.handleTopDragStart),n.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),n.removeEventListener("dragend",this.handleTopDragEndCapture,!0),n.removeEventListener("dragenter",this.handleTopDragEnter),n.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),n.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),n.removeEventListener("dragover",this.handleTopDragOver),n.removeEventListener("dragover",this.handleTopDragOverCapture,!0),n.removeEventListener("drop",this.handleTopDrop),n.removeEventListener("drop",this.handleTopDropCapture,!0))}},{key:"getCurrentSourceNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(n);return aE({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}},{key:"getCurrentDropEffect",value:function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}},{key:"getCurrentSourcePreviewNodeOptions",value:function(){var n=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(n);return aE({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}},{key:"isDraggingNativeItem",value:function(){var n=this.monitor.getItemType();return Object.keys(rE).some(function(r){return rE[r]===n})}},{key:"beginDragNativeItem",value:function(n,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=Uq(n,r),this.currentNativeHandle=this.registry.addSource(n,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}},{key:"setCurrentDragSourceNode",value:function(n){var r=this;this.clearCurrentDragSourceNode(),this.currentDragSourceNode=n;var s=1e3;this.mouseMoveTimeoutTimer=setTimeout(function(){var o;return(o=r.rootElement)===null||o===void 0?void 0:o.addEventListener("mousemove",r.endDragIfSourceWasRemovedFromDOM,!0)},s)}},{key:"clearCurrentDragSourceNode",value:function(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var n;(n=this.window)===null||n===void 0||n.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}},{key:"handleDragStart",value:function(n,r){n.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}},{key:"handleDragEnter",value:function(n,r){this.dragEnterTargetIds.unshift(r)}},{key:"handleDragOver",value:function(n,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}},{key:"handleDrop",value:function(n,r){this.dropTargetIds.unshift(r)}}]),e})(),Zq=function(t,n,r){return new Qq(t,n,r)},Yq=Object.create,nR=Object.defineProperty,Xq=Object.getOwnPropertyDescriptor,rR=Object.getOwnPropertyNames,e7=Object.getPrototypeOf,t7=Object.prototype.hasOwnProperty,n7=(e,t)=>function(){return t||(0,e[rR(e)[0]])((t={exports:{}}).exports,t),t.exports},r7=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rR(t))!t7.call(e,s)&&s!==n&&nR(e,s,{get:()=>t[s],enumerable:!(r=Xq(t,s))||r.enumerable});return e},sR=(e,t,n)=>(n=e!=null?Yq(e7(e)):{},r7(nR(n,"default",{value:e,enumerable:!0}),e)),oR=n7({"node_modules/classnames/index.js"(e,t){(function(){var n={}.hasOwnProperty;function r(){for(var s=[],o=0;o-1}var dK=uK,fK=9007199254740991,pK=/^(?:0|[1-9]\d*)$/;function hK(e,t){var n=typeof e;return t=t??fK,!!t&&(n=="number"||n!="symbol"&&pK.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=vK}var fR=yK;function bK(e){return e!=null&&fR(e.length)&&!uR(e)}var xK=bK,wK=Object.prototype;function SK(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||wK;return e===n}var CK=SK;function EK(e,t){for(var n=-1,r=Array(e);++n-1}var t9=e9;function n9(e,t){var n=this.__data__,r=Xh(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var r9=n9;function dc(e){var t=-1,n=e==null?0:e.length;for(this.clear();++tu))return!1;var f=o.get(e),h=o.get(t);if(f&&h)return f==t&&h==e;var m=-1,g=!0,x=n&uG?new bR:void 0;for(o.set(e,t),o.set(t,e);++m":">",'"':""","'":"'"},VG=S9(UG),HG=VG,CR=/[&<>"']/g,qG=RegExp(CR.source);function KG(e){return e=yR(e),e&&qG.test(e)?e.replace(CR,HG):e}var WG=KG,ER=/[\\^$.*+?()[\]{}|]/g,GG=RegExp(ER.source);function JG(e){return e=yR(e),e&&GG.test(e)?e.replace(ER,"\\$&"):e}var QG=JG;function ZG(e,t){return $G(e,t)}var YG=ZG,XG=1/0,eJ=Al&&1/Lx(new Al([,-0]))[1]==XG?function(e){return new Al(e)}:tK,tJ=eJ,nJ=200;function rJ(e,t,n){var r=-1,s=dK,o=e.length,l=!0,u=[],d=u;if(n)l=!1,s=zG;else if(o>=nJ){var f=t?null:tJ(e);if(f)return Lx(f);l=!1,s=xR,d=new bR}else d=t?[]:u;e:for(;++ri.jsx("button",{className:e.classNames.clearAll,onClick:e.onClick,children:"Clear all"}),lJ=iJ,cJ=(e,t)=>{const n=t.offsetHeight,r=e.offsetHeight,s=e.offsetTop-t.scrollTop;s+r>=n?t.scrollTop+=s-n+r:s<0&&(t.scrollTop+=s)},lb=(e,t,n,r)=>typeof r=="function"?r(e):e.length>=t&&n,uJ=e=>{const t=y.createRef(),{labelField:n,minQueryLength:r,isFocused:s,classNames:o,selectedIndex:l,query:u}=e;y.useEffect(()=>{if(!t.current)return;const m=t.current.querySelector(`.${o.activeSuggestion}`);m&&cJ(m,t.current)},[l]);const d=(m,g)=>{const x=g.trim().replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&"),{[n]:b}=m;return{__html:b.replace(RegExp(x,"gi"),w=>`${WG(w)}`)}},f=(m,g)=>typeof e.renderSuggestion=="function"?e.renderSuggestion(m,g):i.jsx("span",{dangerouslySetInnerHTML:d(m,g)}),h=e.suggestions.map((m,g)=>i.jsx("li",{onMouseDown:e.handleClick.bind(null,g),onTouchStart:e.handleClick.bind(null,g),onMouseOver:e.handleHover.bind(null,g),className:g===e.selectedIndex?e.classNames.activeSuggestion:"",children:f(m,e.query)},g));return h.length===0||!lb(u,r||2,s,e.shouldRenderSuggestions)?null:i.jsx("div",{ref:t,className:o.suggestions,"data-testid":"suggestions",children:i.jsxs("ul",{children:[" ",h," "]})})},dJ=(e,t)=>{const{query:n,minQueryLength:r=2,isFocused:s,suggestions:o}=t;return!!(e.isFocused===s&&YG(e.suggestions,o)&&lb(n,r,s,t.shouldRenderSuggestions)===lb(e.query,e.minQueryLength??2,e.isFocused,e.shouldRenderSuggestions)&&e.selectedIndex===t.selectedIndex)},fJ=y.memo(uJ,dJ),pJ=fJ,hJ=sR(oR()),gJ=sR(oR());function mJ(e){const t=e.map(r=>{const s=r-48*Math.floor(r/48);return String.fromCharCode(96<=r?s:r)}).join(""),n=QG(t);return new RegExp(`[${n}]+`)}function vJ(e){switch(e){case Vs.ENTER:return[10,13];case Vs.TAB:return 9;case Vs.COMMA:return 188;case Vs.SPACE:return 32;case Vs.SEMICOLON:return 186;default:return 0}}function PE(e){const{moveTag:t,readOnly:n,allowDragDrop:r}=e;return t!==void 0&&!n&&r}function yJ(e){const{readOnly:t,allowDragDrop:n}=e;return!t&&n}var bJ=e=>{const{readOnly:t,removeComponent:n,onRemove:r,className:s,tag:o,index:l}=e,u=f=>{if(Il.ENTER.includes(f.keyCode)||f.keyCode===Il.SPACE){f.preventDefault(),f.stopPropagation();return}f.keyCode===Il.BACKSPACE&&r(f)};if(t)return i.jsx("span",{});const d=`Tag at index ${l} with value ${o.id} focussed. Press backspace to remove`;if(n){const f=n;return i.jsx(f,{"data-testid":"remove",onRemove:r,onKeyDown:u,className:s,"aria-label":d,tag:o,index:l})}return i.jsx("button",{"data-testid":"remove",onClick:r,onKeyDown:u,className:s,type:"button","aria-label":d,children:i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"12",width:"12",fill:"#fff",children:i.jsx("path",{d:"M376.6 84.5c11.3-13.6 9.5-33.8-4.1-45.1s-33.8-9.5-45.1 4.1L192 206 56.6 43.5C45.3 29.9 25.1 28.1 11.5 39.4S-3.9 70.9 7.4 84.5L150.3 256 7.4 427.5c-11.3 13.6-9.5 33.8 4.1 45.1s33.8 9.5 45.1-4.1L192 306 327.4 468.5c11.3 13.6 31.5 15.4 45.1 4.1s15.4-31.5 4.1-45.1L233.7 256 376.6 84.5z"})})})},xJ=bJ,OE={TAG:"tag"},wJ=e=>{const t=y.useRef(null),{readOnly:n=!1,tag:r,classNames:s,index:o,moveTag:l,allowDragDrop:u=!0,labelField:d="text",tags:f}=e,[{isDragging:h},m]=iq(()=>({type:OE.TAG,collect:C=>({isDragging:!!C.isDragging()}),item:e,canDrag:()=>PE({moveTag:l,readOnly:n,allowDragDrop:u})}),[f]),[,g]=Cq(()=>({accept:OE.TAG,drop:C=>{const k=C.index,j=o;k!==j&&e?.moveTag?.(k,j)},canDrop:C=>yJ(C)}),[f]);m(g(t));const x=e.tag[d],{className:b=""}=r,w=h?0:1;return i.jsxs("span",{ref:t,className:(0,gJ.default)("tag-wrapper",s.tag,b),style:{opacity:w,cursor:PE({moveTag:l,readOnly:n,allowDragDrop:u})?"move":"auto"},"data-testid":"tag",onClick:e.onTagClicked,onTouchStart:e.onTagClicked,children:[x,i.jsx(xJ,{tag:e.tag,className:s.remove,removeComponent:e.removeComponent,onRemove:e.onDelete,readOnly:n,index:o})]})},SJ=e=>{const{autofocus:t,autoFocus:n,readOnly:r,labelField:s,allowDeleteFromEmptyInput:o,allowAdditionFromPaste:l,allowDragDrop:u,minQueryLength:d,shouldRenderSuggestions:f,removeComponent:h,autocomplete:m,inline:g,maxTags:x,allowUnique:b,editable:w,placeholder:C,delimiters:k,separators:j,tags:M,inputFieldPosition:_,inputProps:R,classNames:N,maxLength:O,inputValue:D,clearAll:z}=e,[Q,pe]=y.useState(e.suggestions),[V,G]=y.useState(""),[W,ie]=y.useState(!1),[re,Y]=y.useState(-1),[H,q]=y.useState(!1),[he,A]=y.useState(""),[F,fe]=y.useState(-1),[te,de]=y.useState(""),ge=y.createRef(),Z=y.useRef(null),ye=y.useRef(null);y.useEffect(()=>{k.length&&console.warn("[Deprecation] The delimiters prop is deprecated and will be removed in v7.x.x, please use separators instead. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/960")},[]),y.useEffect(()=>{typeof g<"u"&&console.warn("[Deprecation] The inline attribute is deprecated and will be removed in v7.x.x, please use inputFieldPosition instead.")},[g]),y.useEffect(()=>{typeof t<"u"&&console.warn("[Deprecated] autofocus prop will be removed in 7.x so please migrate to autoFocus prop."),(t||n&&t!==!1)&&!r&&Ye()},[n,n,r]),y.useEffect(()=>{vn()},[V,e.suggestions]);const Re=Te=>{let ut=e.suggestions.slice();if(b){const mr=M.map(vr=>vr.id.trim().toLowerCase());ut=ut.filter(vr=>!mr.includes(vr.id.toLowerCase()))}if(e.handleFilterSuggestions)return e.handleFilterSuggestions(Te,ut);const It=ut.filter(mr=>$e(Te,mr)===0),Tn=ut.filter(mr=>$e(Te,mr)>0);return It.concat(Tn)},$e=(Te,ut)=>ut[s].toLowerCase().indexOf(Te.toLowerCase()),Ye=()=>{G(""),Z.current&&(Z.current.value="",Z.current.focus())},Fe=(Te,ut)=>{ut.preventDefault(),ut.stopPropagation();const It=M.slice();It.length!==0&&(de(""),e?.handleDelete?.(Te,ut),ft(Te,It))},ft=(Te,ut)=>{if(!ge?.current)return;const It=ge.current.querySelectorAll(".ReactTags__remove");let Tn="";Te===0&&ut.length>1?(Tn=`Tag at index ${Te} with value ${ut[Te].id} deleted. Tag at index 0 with value ${ut[1].id} focussed. Press backspace to remove`,It[0].focus()):Te>0?(Tn=`Tag at index ${Te} with value ${ut[Te].id} deleted. Tag at index ${Te-1} with value ${ut[Te-1].id} focussed. Press backspace to remove`,It[Te-1].focus()):(Tn=`Tag at index ${Te} with value ${ut[Te].id} deleted. Input focussed. Press enter to add a new tag`,Z.current?.focus()),A(Tn)},ln=(Te,ut,It)=>{r||(w&&(fe(Te),G(ut[s]),ye.current?.focus()),e.handleTagClick?.(Te,It))},Sn=Te=>{e.handleInputChange&&e.handleInputChange(Te.target.value,Te);const ut=Te.target.value.trim();G(ut)},vn=()=>{const Te=Re(V);pe(Te),Y(re>=Te.length?Te.length-1:re)},Cn=Te=>{const ut=Te.target.value;e.handleInputFocus&&e.handleInputFocus(ut,Te),ie(!0)},L=Te=>{const ut=Te.target.value;e.handleInputBlur&&(e.handleInputBlur(ut,Te),Z.current&&(Z.current.value="")),ie(!1),fe(-1)},X=Te=>{if(Te.key==="Escape"&&(Te.preventDefault(),Te.stopPropagation(),Y(-1),q(!1),pe([]),fe(-1)),(j.indexOf(Te.key)!==-1||k.indexOf(Te.keyCode)!==-1)&&!Te.shiftKey){(Te.keyCode!==Il.TAB||V!=="")&&Te.preventDefault();const ut=H&&re!==-1?Q[re]:{id:V.trim(),[s]:V.trim(),className:""};Object.keys(ut)&&je(ut)}Te.key==="Backspace"&&V===""&&(o||_===cu.INLINE)&&Fe(M.length-1,Te),Te.keyCode===Il.UP_ARROW&&(Te.preventDefault(),Y(re<=0?Q.length-1:re-1),q(!0)),Te.keyCode===Il.DOWN_ARROW&&(Te.preventDefault(),q(!0),Q.length===0?Y(-1):Y((re+1)%Q.length))},ue=()=>x&&M.length>=x,Ne=Te=>{if(!l)return;if(ue()){de(lE.TAG_LIMIT),Ye();return}de(""),Te.preventDefault();const ut=Te.clipboardData||window.clipboardData,It=ut.getData("text"),{maxLength:Tn=It.length}=e,mr=Math.min(Tn,It.length),vr=ut.getData("text").substr(0,mr);let Gr=k;j.length&&(Gr=[],j.forEach(Rr=>{const Uo=vJ(Rr);Array.isArray(Uo)?Gr=[...Gr,...Uo]:Gr.push(Uo)}));const Jr=mJ(Gr),_r=vr.split(Jr).map(Rr=>Rr.trim());aJ(_r).forEach(Rr=>je({id:Rr.trim(),[s]:Rr.trim(),className:""}))},je=Te=>{if(!Te.id||!Te[s])return;if(F===-1){if(ue()){de(lE.TAG_LIMIT),Ye();return}de("")}const ut=M.map(It=>It.id.toLowerCase());if(!(b&&ut.indexOf(Te.id.trim().toLowerCase())>=0)){if(m){const It=Re(Te[s]);console.warn("[Deprecation] The autocomplete prop will be removed in 7.x to simplify the integration and make it more intutive. If you have any concerns regarding this, please share your thoughts in https://github.com/react-tags/react-tags/issues/949"),(m===1&&It.length===1||m===!0&&It.length)&&(Te=It[0])}F!==-1&&e.onTagUpdate?e.onTagUpdate(F,Te):e?.handleAddition?.(Te),G(""),q(!1),Y(-1),fe(-1),Ye()}},Se=Te=>{je(Q[Te])},Be=()=>{e.onClearAll&&e.onClearAll(),de(""),Ye()},bt=Te=>{Y(Te),q(!0)},Wt=(Te,ut)=>{const It=M[Te];e?.handleDrag?.(It,Te,ut)},bn=(()=>{const Te={...iE,...e.classNames};return M.map((ut,It)=>i.jsx(y.Fragment,{children:F===It?i.jsx("div",{className:Te.editTagInput,children:i.jsx("input",{ref:Tn=>{ye.current=Tn},onFocus:Cn,value:V,onChange:Sn,onKeyDown:X,onBlur:L,className:Te.editTagInputField,onPaste:Ne,"data-testid":"tag-edit"})}):i.jsx(wJ,{index:It,tag:ut,tags:M,labelField:s,onDelete:Tn=>Fe(It,Tn),moveTag:u?Wt:void 0,removeComponent:h,onTagClicked:Tn=>ln(It,ut,Tn),readOnly:r,classNames:Te,allowDragDrop:u})},It))})(),En={...iE,...N},{name:gr,id:Qn}=e,ro=g===!1?cu.BOTTOM:_,Bn=r?null:i.jsxs("div",{className:En.tagInput,children:[i.jsx("input",{...R,ref:Te=>{Z.current=Te},className:En.tagInputField,type:"text",placeholder:C,"aria-label":C,onFocus:Cn,onBlur:L,onChange:Sn,onKeyDown:X,onPaste:Ne,name:gr,id:Qn,maxLength:O,value:D,"data-automation":"input","data-testid":"input"}),i.jsx(pJ,{query:V.trim(),suggestions:Q,labelField:s,selectedIndex:re,handleClick:Se,handleHover:bt,minQueryLength:d,shouldRenderSuggestions:f,isFocused:W,classNames:En,renderSuggestion:e.renderSuggestion}),z&&M.length>0&&i.jsx(lJ,{classNames:En,onClick:Be}),te&&i.jsxs("div",{"data-testid":"error",className:"ReactTags__error",children:[i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",height:"24",width:"24",fill:"#e03131",children:i.jsx("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"})}),te]})]});return i.jsxs("div",{className:(0,hJ.default)(En.tags,"react-tags-wrapper"),ref:ge,children:[i.jsx("p",{role:"alert",className:"sr-only",style:{position:"absolute",overflow:"hidden",clip:"rect(0 0 0 0)",margin:"-1px",padding:0,width:"1px",height:"1px",border:0},children:he}),ro===cu.TOP&&Bn,i.jsxs("div",{className:En.selected,children:[bn,ro===cu.INLINE&&Bn]}),ro===cu.BOTTOM&&Bn]})},CJ=SJ,EJ=e=>{const{placeholder:t=s7,labelField:n=o7,suggestions:r=[],delimiters:s=[],separators:o=e.delimiters?.length?[]:[Vs.ENTER,Vs.TAB],autofocus:l,autoFocus:u=!0,inline:d,inputFieldPosition:f="inline",allowDeleteFromEmptyInput:h=!1,allowAdditionFromPaste:m=!0,autocomplete:g=!1,readOnly:x=!1,allowUnique:b=!0,allowDragDrop:w=!0,tags:C=[],inputProps:k={},editable:j=!1,clearAll:M=!1,handleDelete:_,handleAddition:R,onTagUpdate:N,handleDrag:O,handleFilterSuggestions:D,handleTagClick:z,handleInputChange:Q,handleInputFocus:pe,handleInputBlur:V,minQueryLength:G,shouldRenderSuggestions:W,removeComponent:ie,onClearAll:re,classNames:Y,name:H,id:q,maxLength:he,inputValue:A,maxTags:F,renderSuggestion:fe}=e;return i.jsx(CJ,{placeholder:t,labelField:n,suggestions:r,delimiters:s,separators:o,autofocus:l,autoFocus:u,inline:d,inputFieldPosition:f,allowDeleteFromEmptyInput:h,allowAdditionFromPaste:m,autocomplete:g,readOnly:x,allowUnique:b,allowDragDrop:w,tags:C,inputProps:k,editable:j,clearAll:M,handleDelete:_,handleAddition:R,onTagUpdate:N,handleDrag:O,handleFilterSuggestions:D,handleTagClick:z,handleInputChange:Q,handleInputFocus:pe,handleInputBlur:V,minQueryLength:G,shouldRenderSuggestions:W,removeComponent:ie,onClearAll:re,classNames:Y,name:H,id:q,maxLength:he,inputValue:A,maxTags:F,renderSuggestion:fe})},kJ=({...e})=>i.jsx(tH,{backend:Zq,children:i.jsx(EJ,{...e})});/*! Bundled license information: + +classnames/index.js: + (*! + Copyright (c) 2018 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames + *) + +lodash-es/lodash.js: + (** + * @license + * Lodash (Custom Build) + * Build: `lodash modularize exports="es" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) +*/var jJ="Label",kR=y.forwardRef((e,t)=>i.jsx(rt.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));kR.displayName=jJ;var jR=kR;const TJ=jh("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),TR=y.forwardRef(({className:e,...t},n)=>i.jsx(jR,{ref:n,className:Ie(TJ(),e),...t}));TR.displayName=jR.displayName;function NR(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var NJ="VisuallyHidden",MR=y.forwardRef((e,t)=>i.jsx(rt.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));MR.displayName=NJ;var MJ=[" ","Enter","ArrowUp","ArrowDown"],_J=[" ","Enter"],jd="Select",[ng,rg,RJ]=Kb(jd),[hc]=us(jd,[RJ,Oh]),sg=Oh(),[PJ,Ia]=hc(jd),[OJ,IJ]=hc(jd),_R=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:l,defaultValue:u,onValueChange:d,dir:f,name:h,autoComplete:m,disabled:g,required:x}=e,b=sg(t),[w,C]=y.useState(null),[k,j]=y.useState(null),[M,_]=y.useState(!1),R=xd(f),[N=!1,O]=ya({prop:r,defaultProp:s,onChange:o}),[D,z]=ya({prop:l,defaultProp:u,onChange:d}),Q=y.useRef(null),pe=w?!!w.closest("form"):!0,[V,G]=y.useState(new Set),W=Array.from(V).map(ie=>ie.props.value).join(";");return i.jsx(ZT,{...b,children:i.jsxs(PJ,{required:x,scope:t,trigger:w,onTriggerChange:C,valueNode:k,onValueNodeChange:j,valueNodeHasChildren:M,onValueNodeHasChildrenChange:_,contentId:Es(),value:D,onValueChange:z,open:N,onOpenChange:O,dir:R,triggerPointerDownPosRef:Q,disabled:g,children:[i.jsx(ng.Provider,{scope:t,children:i.jsx(OJ,{scope:e.__scopeSelect,onNativeOptionAdd:y.useCallback(ie=>{G(re=>new Set(re).add(ie))},[]),onNativeOptionRemove:y.useCallback(ie=>{G(re=>{const Y=new Set(re);return Y.delete(ie),Y})},[]),children:n})}),pe?i.jsxs(tP,{"aria-hidden":!0,required:x,tabIndex:-1,name:h,autoComplete:m,value:D,onChange:ie=>z(ie.target.value),disabled:g,children:[D===void 0?i.jsx("option",{value:""}):null,Array.from(V)]},W):null]})})};_R.displayName=jd;var RR="SelectTrigger",PR=y.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=sg(n),l=Ia(RR,n),u=l.disabled||r,d=Rt(t,l.onTriggerChange),f=rg(n),[h,m,g]=nP(b=>{const w=f().filter(j=>!j.disabled),C=w.find(j=>j.value===l.value),k=rP(w,b,C);k!==void 0&&l.onValueChange(k.value)}),x=()=>{u||(l.onOpenChange(!0),g())};return i.jsx(YT,{asChild:!0,...o,children:i.jsx(rt.button,{type:"button",role:"combobox","aria-controls":l.contentId,"aria-expanded":l.open,"aria-required":l.required,"aria-autocomplete":"none",dir:l.dir,"data-state":l.open?"open":"closed",disabled:u,"data-disabled":u?"":void 0,"data-placeholder":eP(l.value)?"":void 0,...s,ref:d,onClick:Ue(s.onClick,b=>{b.currentTarget.focus()}),onPointerDown:Ue(s.onPointerDown,b=>{const w=b.target;w.hasPointerCapture(b.pointerId)&&w.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&(x(),l.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)},b.preventDefault())}),onKeyDown:Ue(s.onKeyDown,b=>{const w=h.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&m(b.key),!(w&&b.key===" ")&&MJ.includes(b.key)&&(x(),b.preventDefault())})})})});PR.displayName=RR;var OR="SelectValue",IR=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:l="",...u}=e,d=Ia(OR,n),{onValueNodeHasChildrenChange:f}=d,h=o!==void 0,m=Rt(t,d.onValueNodeChange);return Ln(()=>{f(h)},[f,h]),i.jsx(rt.span,{...u,ref:m,style:{pointerEvents:"none"},children:eP(d.value)?i.jsx(i.Fragment,{children:l}):o})});IR.displayName=OR;var AJ="SelectIcon",AR=y.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return i.jsx(rt.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});AR.displayName=AJ;var DJ="SelectPortal",DR=e=>i.jsx(Ih,{asChild:!0,...e});DR.displayName=DJ;var _i="SelectContent",FR=y.forwardRef((e,t)=>{const n=Ia(_i,e.__scopeSelect),[r,s]=y.useState();if(Ln(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Ma.createPortal(i.jsx(LR,{scope:e.__scopeSelect,children:i.jsx(ng.Slot,{scope:e.__scopeSelect,children:i.jsx("div",{children:e.children})})}),o):null}return i.jsx($R,{...e,ref:t})});FR.displayName=_i;var vo=10,[LR,Aa]=hc(_i),FJ="SelectContentImpl",$R=y.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:l,side:u,sideOffset:d,align:f,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:x,sticky:b,hideWhenDetached:w,avoidCollisions:C,...k}=e,j=Ia(_i,n),[M,_]=y.useState(null),[R,N]=y.useState(null),O=Rt(t,Z=>_(Z)),[D,z]=y.useState(null),[Q,pe]=y.useState(null),V=rg(n),[G,W]=y.useState(!1),ie=y.useRef(!1);y.useEffect(()=>{if(M)return nx(M)},[M]),Wb();const re=y.useCallback(Z=>{const[ye,...Re]=V().map(Fe=>Fe.ref.current),[$e]=Re.slice(-1),Ye=document.activeElement;for(const Fe of Z)if(Fe===Ye||(Fe?.scrollIntoView({block:"nearest"}),Fe===ye&&R&&(R.scrollTop=0),Fe===$e&&R&&(R.scrollTop=R.scrollHeight),Fe?.focus(),document.activeElement!==Ye))return},[V,R]),Y=y.useCallback(()=>re([D,M]),[re,D,M]);y.useEffect(()=>{G&&Y()},[G,Y]);const{onOpenChange:H,triggerPointerDownPosRef:q}=j;y.useEffect(()=>{if(M){let Z={x:0,y:0};const ye=$e=>{Z={x:Math.abs(Math.round($e.pageX)-(q.current?.x??0)),y:Math.abs(Math.round($e.pageY)-(q.current?.y??0))}},Re=$e=>{Z.x<=10&&Z.y<=10?$e.preventDefault():M.contains($e.target)||H(!1),document.removeEventListener("pointermove",ye),q.current=null};return q.current!==null&&(document.addEventListener("pointermove",ye),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ye),document.removeEventListener("pointerup",Re,{capture:!0})}}},[M,H,q]),y.useEffect(()=>{const Z=()=>H(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[H]);const[he,A]=nP(Z=>{const ye=V().filter(Ye=>!Ye.disabled),Re=ye.find(Ye=>Ye.ref.current===document.activeElement),$e=rP(ye,Z,Re);$e&&setTimeout(()=>$e.ref.current.focus())}),F=y.useCallback((Z,ye,Re)=>{const $e=!ie.current&&!Re;(j.value!==void 0&&j.value===ye||$e)&&(z(Z),$e&&(ie.current=!0))},[j.value]),fe=y.useCallback(()=>M?.focus(),[M]),te=y.useCallback((Z,ye,Re)=>{const $e=!ie.current&&!Re;(j.value!==void 0&&j.value===ye||$e)&&pe(Z)},[j.value]),de=r==="popper"?cb:BR,ge=de===cb?{side:u,sideOffset:d,align:f,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:x,sticky:b,hideWhenDetached:w,avoidCollisions:C}:{};return i.jsx(LR,{scope:n,content:M,viewport:R,onViewportChange:N,itemRefCallback:F,selectedItem:D,onItemLeave:fe,itemTextRefCallback:te,focusSelectedItem:Y,selectedItemText:Q,position:r,isPositioned:G,searchRef:he,children:i.jsx(Lh,{as:No,allowPinchZoom:!0,children:i.jsx(_h,{asChild:!0,trapped:j.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:Ue(s,Z=>{j.trigger?.focus({preventScroll:!0}),Z.preventDefault()}),children:i.jsx(Mh,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:i.jsx(de,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:Z=>Z.preventDefault(),...k,...ge,onPlaced:()=>W(!0),ref:O,style:{display:"flex",flexDirection:"column",outline:"none",...k.style},onKeyDown:Ue(k.onKeyDown,Z=>{const ye=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!ye&&Z.key.length===1&&A(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let $e=V().filter(Ye=>!Ye.disabled).map(Ye=>Ye.ref.current);if(["ArrowUp","End"].includes(Z.key)&&($e=$e.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const Ye=Z.target,Fe=$e.indexOf(Ye);$e=$e.slice(Fe+1)}setTimeout(()=>re($e)),Z.preventDefault()}})})})})})})});$R.displayName=FJ;var LJ="SelectItemAlignedPosition",BR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Ia(_i,n),l=Aa(_i,n),[u,d]=y.useState(null),[f,h]=y.useState(null),m=Rt(t,O=>h(O)),g=rg(n),x=y.useRef(!1),b=y.useRef(!0),{viewport:w,selectedItem:C,selectedItemText:k,focusSelectedItem:j}=l,M=y.useCallback(()=>{if(o.trigger&&o.valueNode&&u&&f&&w&&C&&k){const O=o.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),z=o.valueNode.getBoundingClientRect(),Q=k.getBoundingClientRect();if(o.dir!=="rtl"){const Ye=Q.left-D.left,Fe=z.left-Ye,ft=O.left-Fe,ln=O.width+ft,Sn=Math.max(ln,D.width),vn=window.innerWidth-vo,Cn=Ky(Fe,[vo,vn-Sn]);u.style.minWidth=ln+"px",u.style.left=Cn+"px"}else{const Ye=D.right-Q.right,Fe=window.innerWidth-z.right-Ye,ft=window.innerWidth-O.right-Fe,ln=O.width+ft,Sn=Math.max(ln,D.width),vn=window.innerWidth-vo,Cn=Ky(Fe,[vo,vn-Sn]);u.style.minWidth=ln+"px",u.style.right=Cn+"px"}const pe=g(),V=window.innerHeight-vo*2,G=w.scrollHeight,W=window.getComputedStyle(f),ie=parseInt(W.borderTopWidth,10),re=parseInt(W.paddingTop,10),Y=parseInt(W.borderBottomWidth,10),H=parseInt(W.paddingBottom,10),q=ie+re+G+H+Y,he=Math.min(C.offsetHeight*5,q),A=window.getComputedStyle(w),F=parseInt(A.paddingTop,10),fe=parseInt(A.paddingBottom,10),te=O.top+O.height/2-vo,de=V-te,ge=C.offsetHeight/2,Z=C.offsetTop+ge,ye=ie+re+Z,Re=q-ye;if(ye<=te){const Ye=C===pe[pe.length-1].ref.current;u.style.bottom="0px";const Fe=f.clientHeight-w.offsetTop-w.offsetHeight,ft=Math.max(de,ge+(Ye?fe:0)+Fe+Y),ln=ye+ft;u.style.height=ln+"px"}else{const Ye=C===pe[0].ref.current;u.style.top="0px";const ft=Math.max(te,ie+w.offsetTop+(Ye?F:0)+ge)+Re;u.style.height=ft+"px",w.scrollTop=ye-te+w.offsetTop}u.style.margin=`${vo}px 0`,u.style.minHeight=he+"px",u.style.maxHeight=V+"px",r?.(),requestAnimationFrame(()=>x.current=!0)}},[g,o.trigger,o.valueNode,u,f,w,C,k,o.dir,r]);Ln(()=>M(),[M]);const[_,R]=y.useState();Ln(()=>{f&&R(window.getComputedStyle(f).zIndex)},[f]);const N=y.useCallback(O=>{O&&b.current===!0&&(M(),j?.(),b.current=!1)},[M,j]);return i.jsx(BJ,{scope:n,contentWrapper:u,shouldExpandOnScrollRef:x,onScrollButtonChange:N,children:i.jsx("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:_},children:i.jsx(rt.div,{...s,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});BR.displayName=LJ;var $J="SelectPopperPosition",cb=y.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=vo,...o}=e,l=sg(n);return i.jsx(XT,{...l,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});cb.displayName=$J;var[BJ,$x]=hc(_i,{}),ub="SelectViewport",zR=y.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Aa(ub,n),l=$x(ub,n),u=Rt(t,o.onViewportChange),d=y.useRef(0);return i.jsxs(i.Fragment,{children:[i.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),i.jsx(ng.Slot,{scope:n,children:i.jsx(rt.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:u,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:Ue(s.onScroll,f=>{const h=f.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:g}=l;if(g?.current&&m){const x=Math.abs(d.current-h.scrollTop);if(x>0){const b=window.innerHeight-vo*2,w=parseFloat(m.style.minHeight),C=parseFloat(m.style.height),k=Math.max(w,C);if(k0?_:0,m.style.justifyContent="flex-end")}}}d.current=h.scrollTop})})})]})});zR.displayName=ub;var UR="SelectGroup",[zJ,UJ]=hc(UR),VJ=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Es();return i.jsx(zJ,{scope:n,id:s,children:i.jsx(rt.div,{role:"group","aria-labelledby":s,...r,ref:t})})});VJ.displayName=UR;var VR="SelectLabel",HR=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=UJ(VR,n);return i.jsx(rt.div,{id:s.id,...r,ref:t})});HR.displayName=VR;var ih="SelectItem",[HJ,qR]=hc(ih),KR=y.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...l}=e,u=Ia(ih,n),d=Aa(ih,n),f=u.value===r,[h,m]=y.useState(o??""),[g,x]=y.useState(!1),b=Rt(t,k=>d.itemRefCallback?.(k,r,s)),w=Es(),C=()=>{s||(u.onValueChange(r),u.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return i.jsx(HJ,{scope:n,value:r,disabled:s,textId:w,isSelected:f,onItemTextChange:y.useCallback(k=>{m(j=>j||(k?.textContent??"").trim())},[]),children:i.jsx(ng.ItemSlot,{scope:n,value:r,disabled:s,textValue:h,children:i.jsx(rt.div,{role:"option","aria-labelledby":w,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...l,ref:b,onFocus:Ue(l.onFocus,()=>x(!0)),onBlur:Ue(l.onBlur,()=>x(!1)),onPointerUp:Ue(l.onPointerUp,C),onPointerMove:Ue(l.onPointerMove,k=>{s?d.onItemLeave?.():k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ue(l.onPointerLeave,k=>{k.currentTarget===document.activeElement&&d.onItemLeave?.()}),onKeyDown:Ue(l.onKeyDown,k=>{d.searchRef?.current!==""&&k.key===" "||(_J.includes(k.key)&&C(),k.key===" "&&k.preventDefault())})})})})});KR.displayName=ih;var xu="SelectItemText",WR=y.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,l=Ia(xu,n),u=Aa(xu,n),d=qR(xu,n),f=IJ(xu,n),[h,m]=y.useState(null),g=Rt(t,k=>m(k),d.onItemTextChange,k=>u.itemTextRefCallback?.(k,d.value,d.disabled)),x=h?.textContent,b=y.useMemo(()=>i.jsx("option",{value:d.value,disabled:d.disabled,children:x},d.value),[d.disabled,d.value,x]),{onNativeOptionAdd:w,onNativeOptionRemove:C}=f;return Ln(()=>(w(b),()=>C(b)),[w,C,b]),i.jsxs(i.Fragment,{children:[i.jsx(rt.span,{id:d.textId,...o,ref:g}),d.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Ma.createPortal(o.children,l.valueNode):null]})});WR.displayName=xu;var GR="SelectItemIndicator",JR=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return qR(GR,n).isSelected?i.jsx(rt.span,{"aria-hidden":!0,...r,ref:t}):null});JR.displayName=GR;var db="SelectScrollUpButton",QR=y.forwardRef((e,t)=>{const n=Aa(db,e.__scopeSelect),r=$x(db,e.__scopeSelect),[s,o]=y.useState(!1),l=Rt(t,r.onScrollButtonChange);return Ln(()=>{if(n.viewport&&n.isPositioned){let u=function(){const f=d.scrollTop>0;o(f)};const d=n.viewport;return u(),d.addEventListener("scroll",u),()=>d.removeEventListener("scroll",u)}},[n.viewport,n.isPositioned]),s?i.jsx(YR,{...e,ref:l,onAutoScroll:()=>{const{viewport:u,selectedItem:d}=n;u&&d&&(u.scrollTop=u.scrollTop-d.offsetHeight)}}):null});QR.displayName=db;var fb="SelectScrollDownButton",ZR=y.forwardRef((e,t)=>{const n=Aa(fb,e.__scopeSelect),r=$x(fb,e.__scopeSelect),[s,o]=y.useState(!1),l=Rt(t,r.onScrollButtonChange);return Ln(()=>{if(n.viewport&&n.isPositioned){let u=function(){const f=d.scrollHeight-d.clientHeight,h=Math.ceil(d.scrollTop)d.removeEventListener("scroll",u)}},[n.viewport,n.isPositioned]),s?i.jsx(YR,{...e,ref:l,onAutoScroll:()=>{const{viewport:u,selectedItem:d}=n;u&&d&&(u.scrollTop=u.scrollTop+d.offsetHeight)}}):null});ZR.displayName=fb;var YR=y.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Aa("SelectScrollButton",n),l=y.useRef(null),u=rg(n),d=y.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return y.useEffect(()=>()=>d(),[d]),Ln(()=>{u().find(h=>h.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[u]),i.jsx(rt.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Ue(s.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:Ue(s.onPointerMove,()=>{o.onItemLeave?.(),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:Ue(s.onPointerLeave,()=>{d()})})}),qJ="SelectSeparator",XR=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return i.jsx(rt.div,{"aria-hidden":!0,...r,ref:t})});XR.displayName=qJ;var pb="SelectArrow",KJ=y.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=sg(n),o=Ia(pb,n),l=Aa(pb,n);return o.open&&l.position==="popper"?i.jsx(eN,{...s,...r,ref:t}):null});KJ.displayName=pb;function eP(e){return e===""||e===void 0}var tP=y.forwardRef((e,t)=>{const{value:n,...r}=e,s=y.useRef(null),o=Rt(t,s),l=NR(n);return y.useEffect(()=>{const u=s.current,d=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(d,"value").set;if(l!==n&&h){const m=new Event("change",{bubbles:!0});h.call(u,n),u.dispatchEvent(m)}},[l,n]),i.jsx(MR,{asChild:!0,children:i.jsx("select",{...r,ref:o,defaultValue:n})})});tP.displayName="BubbleSelect";function nP(e){const t=Rn(e),n=y.useRef(""),r=y.useRef(0),s=y.useCallback(l=>{const u=n.current+l;t(u),(function d(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>d(""),1e3))})(u)},[t]),o=y.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return y.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function rP(e,t,n){const s=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let l=WJ(e,Math.max(o,0));s.length===1&&(l=l.filter(f=>f!==n));const d=l.find(f=>f.textValue.toLowerCase().startsWith(s.toLowerCase()));return d!==n?d:void 0}function WJ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var GJ=_R,sP=PR,JJ=IR,QJ=AR,ZJ=DR,oP=FR,YJ=zR,aP=HR,iP=KR,XJ=WR,eQ=JR,lP=QR,cP=ZR,uP=XR;const tQ=GJ,nQ=JJ,dP=y.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(sP,{ref:r,className:Ie("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-default disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,i.jsx(QJ,{asChild:!0,children:i.jsx(Nh,{className:"h-4 w-4 opacity-50"})})]}));dP.displayName=sP.displayName;const fP=y.forwardRef(({className:e,...t},n)=>i.jsx(lP,{ref:n,className:Ie("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(G$,{className:"h-4 w-4"})}));fP.displayName=lP.displayName;const pP=y.forwardRef(({className:e,...t},n)=>i.jsx(cP,{ref:n,className:Ie("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(Nh,{className:"h-4 w-4"})}));pP.displayName=cP.displayName;const hP=y.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>i.jsx(ZJ,{children:i.jsxs(oP,{ref:s,className:Ie("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[i.jsx(fP,{}),i.jsx(YJ,{className:Ie("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),i.jsx(pP,{})]})}));hP.displayName=oP.displayName;const rQ=y.forwardRef(({className:e,...t},n)=>i.jsx(aP,{ref:n,className:Ie("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));rQ.displayName=aP.displayName;const gP=y.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(iP,{ref:r,className:Ie("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[i.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:i.jsx(eQ,{children:i.jsx(fT,{className:"h-4 w-4"})})}),i.jsx(XJ,{children:t})]}));gP.displayName=iP.displayName;const sQ=y.forwardRef(({className:e,...t},n)=>i.jsx(uP,{ref:n,className:Ie("-mx-1 my-1 h-px bg-muted",e),...t}));sQ.displayName=uP.displayName;var Bx="Switch",[oQ]=us(Bx),[aQ,iQ]=oQ(Bx),mP=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:l,disabled:u,value:d="on",onCheckedChange:f,...h}=e,[m,g]=y.useState(null),x=Rt(t,j=>g(j)),b=y.useRef(!1),w=m?!!m.closest("form"):!0,[C=!1,k]=ya({prop:s,defaultProp:o,onChange:f});return i.jsxs(aQ,{scope:n,checked:C,disabled:u,children:[i.jsx(rt.button,{type:"button",role:"switch","aria-checked":C,"aria-required":l,"data-state":bP(C),"data-disabled":u?"":void 0,disabled:u,value:d,...h,ref:x,onClick:Ue(e.onClick,j=>{k(M=>!M),w&&(b.current=j.isPropagationStopped(),b.current||j.stopPropagation())})}),w&&i.jsx(lQ,{control:m,bubbles:!b.current,name:r,value:d,checked:C,required:l,disabled:u,style:{transform:"translateX(-100%)"}})]})});mP.displayName=Bx;var vP="SwitchThumb",yP=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=iQ(vP,n);return i.jsx(rt.span,{"data-state":bP(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});yP.displayName=vP;var lQ=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=y.useRef(null),l=NR(n),u=zT(t);return y.useEffect(()=>{const d=o.current,f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&m){const g=new Event("click",{bubbles:r});m.call(d,n),d.dispatchEvent(g)}},[l,n,r]),i.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...u,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function bP(e){return e?"checked":"unchecked"}var xP=mP,cQ=yP;const gc=y.forwardRef(({className:e,...t},n)=>i.jsx(xP,{className:Ie("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:i.jsx(cQ,{className:Ie("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));gc.displayName=xP.displayName;const Fo=Gn,wP=y.createContext({}),Lo=({...e})=>i.jsx(wP.Provider,{value:{name:e.name},children:i.jsx(r6,{...e})}),og=()=>{const e=y.useContext(wP),t=y.useContext(SP),{getFieldState:n,formState:r}=Kh(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},SP=y.createContext({}),no=y.forwardRef(({className:e,...t},n)=>{const r=y.useId();return i.jsx(SP.Provider,{value:{id:r},children:i.jsx("div",{ref:n,className:Ie("space-y-2",e),...t})})});no.displayName="FormItem";const Nr=y.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=og();return i.jsx(TR,{ref:n,className:Ie(r&&"text-rose-600",e),htmlFor:s,...t})});Nr.displayName="FormLabel";const _s=y.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=og();return i.jsx(No,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});_s.displayName="FormControl";const ag=y.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=og();return i.jsx("p",{ref:n,id:r,className:Ie("text-sm text-muted-foreground",e),...t})});ag.displayName="FormDescription";const Td=y.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=og(),l=s?String(s?.message):t;return l?i.jsx("p",{ref:r,id:o,className:Ie("text-sm font-medium text-rose-600",e),...n,children:l}):null});Td.displayName="FormMessage";const le=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...l})=>i.jsx(Lo,{...l,name:e,render:({field:u})=>i.jsxs(no,{className:o,children:[t&&i.jsxs(Nr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(_s,{children:y.isValidElement(n)&&y.cloneElement(n,{...u,value:u.value??"",required:r,readOnly:s,checked:u.value,onCheckedChange:u.onChange})}),i.jsx(Td,{})]})}),Pe=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...l})=>i.jsx(Lo,{...l,name:e,render:({field:u})=>i.jsxs(no,{className:Ie("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[i.jsx("div",{className:"flex flex-col gap-2",children:t&&i.jsxs(Nr,{children:[i.jsxs("p",{className:"break-all",children:[t,n&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&i.jsx(ag,{className:"mt-2",children:s})]})}),i.jsx(_s,{children:i.jsx(gc,{checked:u.value,onCheckedChange:u.onChange,required:n})}),i.jsx(Td,{})]})}),Jt=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,disabled:l,...u})=>i.jsx(Lo,{...u,name:e,render:({field:d})=>i.jsxs(no,{children:[t&&i.jsxs(Nr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(_s,{children:i.jsxs(tQ,{onValueChange:d.onChange,defaultValue:d.value,disabled:l,children:[i.jsx(_s,{children:i.jsx(dP,{children:i.jsx(nQ,{placeholder:o})})}),i.jsx(hP,{children:s.map(f=>i.jsx(gP,{value:f.value,children:f.label},f.value))})]})}),n&&i.jsx(ag,{children:n}),i.jsx(Td,{})]})}),Da=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>i.jsx(Lo,{...o,name:e,render:({field:l})=>{let u=[];return Array.isArray(l.value)&&(u=l.value),i.jsxs(no,{children:[t&&i.jsxs(Nr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(_s,{children:i.jsx(kJ,{tags:u.map(d=>({id:d,text:d,className:""})),handleDelete:d=>l.onChange(u.filter((f,h)=>h!==d)),handleAddition:d=>l.onChange([...u,d.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[Vs.ENTER,Vs.TAB,Vs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:u_,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&i.jsx(ag,{children:n}),i.jsx(Td,{})]})}}),Kv=P.string().optional().transform(e=>e===""?void 0:e),uQ=P.object({name:P.string(),token:Kv,number:Kv,businessId:Kv,integration:P.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","EVOLUTION"])});function dQ({resetTable:e}){const{t}=Ve(),{createInstance:n}=Hh(),[r,s]=y.useState(!1),o=[{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}],l=on({resolver:an(uQ),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:E1().replace("-","").toUpperCase(),number:"",businessId:""}}),u=l.watch("integration"),d=async h=>{try{const m={instanceName:h.name,integration:h.integration,token:h.token===""?null:h.token,number:h.number===""?null:h.number,businessId:h.businessId===""?null:h.businessId};await n(m),me.success(t("toast.instance.created")),s(!1),f(),e()}catch(m){console.error("Error:",m),me.error(`Error : ${m?.response?.data?.response?.message}`)}},f=()=>{l.reset({name:"",integration:"WHATSAPP-BAILEYS",token:E1().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"default",size:"sm",children:[t("instance.button.create")," ",i.jsx(cs,{size:"18"})]})}),i.jsxs(Nt,{className:"sm:max-w-[650px]",onCloseAutoFocus:f,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("instance.modal.title")})}),i.jsx(Gn,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(d),className:"grid gap-4 py-4",children:[i.jsx(le,{required:!0,name:"name",label:t("instance.form.name"),children:i.jsx(ne,{})}),i.jsx(Jt,{name:"integration",label:t("instance.form.integration.label"),options:o}),i.jsx(le,{required:!0,name:"token",label:t("instance.form.token"),children:i.jsx(ne,{})}),i.jsx(le,{name:"number",label:t("instance.form.number"),children:i.jsx(ne,{type:"tel"})}),u==="WHATSAPP-BUSINESS"&&i.jsx(le,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:i.jsx(ne,{})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:t("instance.button.save")})})]})})]})]})}function bo(e,t,{checkForDefaultPrevented:n=!0}={}){return function(s){if(e?.(s),n===!1||!s.defaultPrevented)return t?.(s)}}function IE(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function CP(...e){return t=>{let n=!1;const r=e.map(s=>{const o=IE(s,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let s=0;s{const{scope:g,children:x,...b}=m,w=g?.[e]?.[d]||u,C=y.useMemo(()=>b,Object.values(b));return i.jsx(w.Provider,{value:C,children:x})};f.displayName=o+"Provider";function h(m,g){const x=g?.[e]?.[d]||u,b=y.useContext(x);if(b)return b;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${o}\``)}return[f,h]}const s=()=>{const o=n.map(l=>y.createContext(l));return function(u){const d=u?.[e]||o;return y.useMemo(()=>({[`__scope${e}`]:{...u,[e]:d}}),[u,d])}};return s.scopeName=e,[r,fQ(s,...t)]}function fQ(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const l=r.reduce((u,{useScope:d,scopeName:f})=>{const m=d(o)[`__scope${f}`];return{...u,...m}},{});return y.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function pQ(e){const t=hQ(e),n=y.forwardRef((r,s)=>{const{children:o,...l}=r,u=y.Children.toArray(o),d=u.find(mQ);if(d){const f=d.props.children,h=u.map(m=>m===d?y.Children.count(f)>1?y.Children.only(null):y.isValidElement(f)?f.props.children:null:m);return i.jsx(t,{...l,ref:s,children:y.isValidElement(f)?y.cloneElement(f,void 0,h):null})}return i.jsx(t,{...l,ref:s,children:o})});return n.displayName=`${e}.Slot`,n}function hQ(e){const t=y.forwardRef((n,r)=>{const{children:s,...o}=n;if(y.isValidElement(s)){const l=yQ(s),u=vQ(o,s.props);return s.type!==y.Fragment&&(u.ref=r?CP(r,l):l),y.cloneElement(s,u)}return y.Children.count(s)>1?y.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var kP=Symbol("radix.slottable");function gQ(e){const t=({children:n})=>i.jsx(i.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=kP,t}function mQ(e){return y.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===kP}function vQ(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...u)=>{const d=o(...u);return s(...u),d}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function yQ(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var bQ=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Fa=bQ.reduce((e,t)=>{const n=pQ(`Primitive.${t}`),r=y.forwardRef((s,o)=>{const{asChild:l,...u}=s,d=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(d,{...u,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function xQ(e,t){e&&Ma.flushSync(()=>e.dispatchEvent(t))}function ig(e){const t=y.useRef(e);return y.useEffect(()=>{t.current=e}),y.useMemo(()=>(...n)=>t.current?.(...n),[])}function wQ(e,t=globalThis?.document){const n=ig(e);y.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var SQ="DismissableLayer",hb="dismissableLayer.update",CQ="dismissableLayer.pointerDownOutside",EQ="dismissableLayer.focusOutside",AE,jP=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),TP=y.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:l,onDismiss:u,...d}=e,f=y.useContext(jP),[h,m]=y.useState(null),g=h?.ownerDocument??globalThis?.document,[,x]=y.useState({}),b=Ui(t,O=>m(O)),w=Array.from(f.layers),[C]=[...f.layersWithOutsidePointerEventsDisabled].slice(-1),k=w.indexOf(C),j=h?w.indexOf(h):-1,M=f.layersWithOutsidePointerEventsDisabled.size>0,_=j>=k,R=TQ(O=>{const D=O.target,z=[...f.branches].some(Q=>Q.contains(D));!_||z||(s?.(O),l?.(O),O.defaultPrevented||u?.())},g),N=NQ(O=>{const D=O.target;[...f.branches].some(Q=>Q.contains(D))||(o?.(O),l?.(O),O.defaultPrevented||u?.())},g);return wQ(O=>{j===f.layers.size-1&&(r?.(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},g),y.useEffect(()=>{if(h)return n&&(f.layersWithOutsidePointerEventsDisabled.size===0&&(AE=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),f.layersWithOutsidePointerEventsDisabled.add(h)),f.layers.add(h),DE(),()=>{n&&f.layersWithOutsidePointerEventsDisabled.size===1&&(g.body.style.pointerEvents=AE)}},[h,g,n,f]),y.useEffect(()=>()=>{h&&(f.layers.delete(h),f.layersWithOutsidePointerEventsDisabled.delete(h),DE())},[h,f]),y.useEffect(()=>{const O=()=>x({});return document.addEventListener(hb,O),()=>document.removeEventListener(hb,O)},[]),i.jsx(Fa.div,{...d,ref:b,style:{pointerEvents:M?_?"auto":"none":void 0,...e.style},onFocusCapture:bo(e.onFocusCapture,N.onFocusCapture),onBlurCapture:bo(e.onBlurCapture,N.onBlurCapture),onPointerDownCapture:bo(e.onPointerDownCapture,R.onPointerDownCapture)})});TP.displayName=SQ;var kQ="DismissableLayerBranch",jQ=y.forwardRef((e,t)=>{const n=y.useContext(jP),r=y.useRef(null),s=Ui(t,r);return y.useEffect(()=>{const o=r.current;if(o)return n.branches.add(o),()=>{n.branches.delete(o)}},[n.branches]),i.jsx(Fa.div,{...e,ref:s})});jQ.displayName=kQ;function TQ(e,t=globalThis?.document){const n=ig(e),r=y.useRef(!1),s=y.useRef(()=>{});return y.useEffect(()=>{const o=u=>{if(u.target&&!r.current){let d=function(){NP(CQ,n,f,{discrete:!0})};const f={originalEvent:u};u.pointerType==="touch"?(t.removeEventListener("click",s.current),s.current=d,t.addEventListener("click",s.current,{once:!0})):d()}else t.removeEventListener("click",s.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",o),t.removeEventListener("click",s.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function NQ(e,t=globalThis?.document){const n=ig(e),r=y.useRef(!1);return y.useEffect(()=>{const s=o=>{o.target&&!r.current&&NP(EQ,n,{originalEvent:o},{discrete:!1})};return t.addEventListener("focusin",s),()=>t.removeEventListener("focusin",s)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function DE(){const e=new CustomEvent(hb);document.dispatchEvent(e)}function NP(e,t,n,{discrete:r}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),r?xQ(s,o):s.dispatchEvent(o)}var Ta=globalThis?.document?y.useLayoutEffect:()=>{},MQ=Yl[" useId ".trim().toString()]||(()=>{}),_Q=0;function RQ(e){const[t,n]=y.useState(MQ());return Ta(()=>{n(r=>r??String(_Q++))},[e]),t?`radix-${t}`:""}var PQ="Arrow",MP=y.forwardRef((e,t)=>{const{children:n,width:r=10,height:s=5,...o}=e;return i.jsx(Fa.svg,{...o,ref:t,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:i.jsx("polygon",{points:"0,0 30,0 15,10"})})});MP.displayName=PQ;var OQ=MP;function IQ(e){const[t,n]=y.useState(void 0);return Ta(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let l,u;if("borderBoxSize"in o){const d=o.borderBoxSize,f=Array.isArray(d)?d[0]:d;l=f.inlineSize,u=f.blockSize}else l=e.offsetWidth,u=e.offsetHeight;n({width:l,height:u})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var zx="Popper",[_P,RP]=EP(zx),[AQ,PP]=_P(zx),OP=e=>{const{__scopePopper:t,children:n}=e,[r,s]=y.useState(null);return i.jsx(AQ,{scope:t,anchor:r,onAnchorChange:s,children:n})};OP.displayName=zx;var IP="PopperAnchor",AP=y.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...s}=e,o=PP(IP,n),l=y.useRef(null),u=Ui(t,l),d=y.useRef(null);return y.useEffect(()=>{const f=d.current;d.current=r?.current||l.current,f!==d.current&&o.onAnchorChange(d.current)}),r?null:i.jsx(Fa.div,{...s,ref:u})});AP.displayName=IP;var Ux="PopperContent",[DQ,FQ]=_P(Ux),DP=y.forwardRef((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:l=0,arrowPadding:u=0,avoidCollisions:d=!0,collisionBoundary:f=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:g=!1,updatePositionStrategy:x="optimized",onPlaced:b,...w}=e,C=PP(Ux,n),[k,j]=y.useState(null),M=Ui(t,Z=>j(Z)),[_,R]=y.useState(null),N=IQ(_),O=N?.width??0,D=N?.height??0,z=r+(o!=="center"?"-"+o:""),Q=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},pe=Array.isArray(f)?f:[f],V=pe.length>0,G={padding:Q,boundary:pe.filter($Q),altBoundary:V},{refs:W,floatingStyles:ie,placement:re,isPositioned:Y,middlewareData:H}=PT({strategy:"fixed",placement:z,whileElementsMounted:(...Z)=>_T(...Z,{animationFrame:x==="always"}),elements:{reference:C.anchor},middleware:[OT({mainAxis:s+D,alignmentAxis:l}),d&&IT({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?AT():void 0,...G}),d&&DT({...G}),FT({...G,apply:({elements:Z,rects:ye,availableWidth:Re,availableHeight:$e})=>{const{width:Ye,height:Fe}=ye.reference,ft=Z.floating.style;ft.setProperty("--radix-popper-available-width",`${Re}px`),ft.setProperty("--radix-popper-available-height",`${$e}px`),ft.setProperty("--radix-popper-anchor-width",`${Ye}px`),ft.setProperty("--radix-popper-anchor-height",`${Fe}px`)}}),_&&$T({element:_,padding:u}),BQ({arrowWidth:O,arrowHeight:D}),g&<({strategy:"referenceHidden",...G})]}),[q,he]=$P(re),A=ig(b);Ta(()=>{Y&&A?.()},[Y,A]);const F=H.arrow?.x,fe=H.arrow?.y,te=H.arrow?.centerOffset!==0,[de,ge]=y.useState();return Ta(()=>{k&&ge(window.getComputedStyle(k).zIndex)},[k]),i.jsx("div",{ref:W.setFloating,"data-radix-popper-content-wrapper":"",style:{...ie,transform:Y?ie.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:de,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:i.jsx(DQ,{scope:n,placedSide:q,onArrowChange:R,arrowX:F,arrowY:fe,shouldHideArrow:te,children:i.jsx(Fa.div,{"data-side":q,"data-align":he,...w,ref:M,style:{...w.style,animation:Y?void 0:"none"}})})})});DP.displayName=Ux;var FP="PopperArrow",LQ={top:"bottom",right:"left",bottom:"top",left:"right"},LP=y.forwardRef(function(t,n){const{__scopePopper:r,...s}=t,o=FQ(FP,r),l=LQ[o.placedSide];return i.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:i.jsx(OQ,{...s,ref:n,style:{...s.style,display:"block"}})})});LP.displayName=FP;function $Q(e){return e!==null}var BQ=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:s}=t,l=s.arrow?.centerOffset!==0,u=l?0:e.arrowWidth,d=l?0:e.arrowHeight,[f,h]=$P(n),m={start:"0%",center:"50%",end:"100%"}[h],g=(s.arrow?.x??0)+u/2,x=(s.arrow?.y??0)+d/2;let b="",w="";return f==="bottom"?(b=l?m:`${g}px`,w=`${-d}px`):f==="top"?(b=l?m:`${g}px`,w=`${r.floating.height+d}px`):f==="right"?(b=`${-d}px`,w=l?m:`${x}px`):f==="left"&&(b=`${r.floating.width+d}px`,w=l?m:`${x}px`),{data:{x:b,y:w}}}});function $P(e){const[t,n="center"]=e.split("-");return[t,n]}var zQ=OP,UQ=AP,VQ=DP,HQ=LP,qQ="Portal",BP=y.forwardRef((e,t)=>{const{container:n,...r}=e,[s,o]=y.useState(!1);Ta(()=>o(!0),[]);const l=n||s&&globalThis?.document?.body;return l?Ib.createPortal(i.jsx(Fa.div,{...r,ref:t}),l):null});BP.displayName=qQ;function KQ(e,t){return y.useReducer((n,r)=>t[n][r]??n,e)}var Vx=e=>{const{present:t,children:n}=e,r=WQ(t),s=typeof n=="function"?n({present:r.isPresent}):y.Children.only(n),o=Ui(r.ref,GQ(s));return typeof n=="function"||r.isPresent?y.cloneElement(s,{ref:o}):null};Vx.displayName="Presence";function WQ(e){const[t,n]=y.useState(),r=y.useRef(null),s=y.useRef(e),o=y.useRef("none"),l=e?"mounted":"unmounted",[u,d]=KQ(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const f=Xf(r.current);o.current=u==="mounted"?f:"none"},[u]),Ta(()=>{const f=r.current,h=s.current;if(h!==e){const g=o.current,x=Xf(f);e?d("MOUNT"):x==="none"||f?.display==="none"?d("UNMOUNT"):d(h&&g!==x?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,d]),Ta(()=>{if(t){let f;const h=t.ownerDocument.defaultView??window,m=x=>{const w=Xf(r.current).includes(CSS.escape(x.animationName));if(x.target===t&&w&&(d("ANIMATION_END"),!s.current)){const C=t.style.animationFillMode;t.style.animationFillMode="forwards",f=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=C)})}},g=x=>{x.target===t&&(o.current=Xf(r.current))};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(f),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:y.useCallback(f=>{r.current=f?getComputedStyle(f):null,n(f)},[])}}function Xf(e){return e?.animationName||"none"}function GQ(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var JQ=Yl[" useInsertionEffect ".trim().toString()]||Ta;function QQ({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[s,o,l]=ZQ({defaultProp:t,onChange:n}),u=e!==void 0,d=u?e:s;{const h=y.useRef(e!==void 0);y.useEffect(()=>{const m=h.current;m!==u&&console.warn(`${r} is changing from ${m?"controlled":"uncontrolled"} to ${u?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),h.current=u},[u,r])}const f=y.useCallback(h=>{if(u){const m=YQ(h)?h(e):h;m!==e&&l.current?.(m)}else o(h)},[u,e,o,l]);return[d,f]}function ZQ({defaultProp:e,onChange:t}){const[n,r]=y.useState(e),s=y.useRef(n),o=y.useRef(t);return JQ(()=>{o.current=t},[t]),y.useEffect(()=>{s.current!==n&&(o.current?.(n),s.current=n)},[n,s]),[n,r,o]}function YQ(e){return typeof e=="function"}var XQ=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),eZ="VisuallyHidden",zP=y.forwardRef((e,t)=>i.jsx(Fa.span,{...e,ref:t,style:{...XQ,...e.style}}));zP.displayName=eZ;var tZ=zP,[lg]=EP("Tooltip",[RP]),cg=RP(),UP="TooltipProvider",nZ=700,gb="tooltip.open",[rZ,Hx]=lg(UP),VP=e=>{const{__scopeTooltip:t,delayDuration:n=nZ,skipDelayDuration:r=300,disableHoverableContent:s=!1,children:o}=e,l=y.useRef(!0),u=y.useRef(!1),d=y.useRef(0);return y.useEffect(()=>{const f=d.current;return()=>window.clearTimeout(f)},[]),i.jsx(rZ,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:y.useCallback(()=>{window.clearTimeout(d.current),l.current=!1},[]),onClose:y.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:y.useCallback(f=>{u.current=f},[]),disableHoverableContent:s,children:o})};VP.displayName=UP;var id="Tooltip",[sZ,Nd]=lg(id),HP=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:s,onOpenChange:o,disableHoverableContent:l,delayDuration:u}=e,d=Hx(id,e.__scopeTooltip),f=cg(t),[h,m]=y.useState(null),g=RQ(),x=y.useRef(0),b=l??d.disableHoverableContent,w=u??d.delayDuration,C=y.useRef(!1),[k,j]=QQ({prop:r,defaultProp:s??!1,onChange:O=>{O?(d.onOpen(),document.dispatchEvent(new CustomEvent(gb))):d.onClose(),o?.(O)},caller:id}),M=y.useMemo(()=>k?C.current?"delayed-open":"instant-open":"closed",[k]),_=y.useCallback(()=>{window.clearTimeout(x.current),x.current=0,C.current=!1,j(!0)},[j]),R=y.useCallback(()=>{window.clearTimeout(x.current),x.current=0,j(!1)},[j]),N=y.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{C.current=!0,j(!0),x.current=0},w)},[w,j]);return y.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]),i.jsx(zQ,{...f,children:i.jsx(sZ,{scope:t,contentId:g,open:k,stateAttribute:M,trigger:h,onTriggerChange:m,onTriggerEnter:y.useCallback(()=>{d.isOpenDelayedRef.current?N():_()},[d.isOpenDelayedRef,N,_]),onTriggerLeave:y.useCallback(()=>{b?R():(window.clearTimeout(x.current),x.current=0)},[R,b]),onOpen:_,onClose:R,disableHoverableContent:b,children:n})})};HP.displayName=id;var mb="TooltipTrigger",qP=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,s=Nd(mb,n),o=Hx(mb,n),l=cg(n),u=y.useRef(null),d=Ui(t,u,s.onTriggerChange),f=y.useRef(!1),h=y.useRef(!1),m=y.useCallback(()=>f.current=!1,[]);return y.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),i.jsx(UQ,{asChild:!0,...l,children:i.jsx(Fa.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...r,ref:d,onPointerMove:bo(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!o.isPointerInTransitRef.current&&(s.onTriggerEnter(),h.current=!0)}),onPointerLeave:bo(e.onPointerLeave,()=>{s.onTriggerLeave(),h.current=!1}),onPointerDown:bo(e.onPointerDown,()=>{s.open&&s.onClose(),f.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:bo(e.onFocus,()=>{f.current||s.onOpen()}),onBlur:bo(e.onBlur,s.onClose),onClick:bo(e.onClick,s.onClose)})})});qP.displayName=mb;var qx="TooltipPortal",[oZ,aZ]=lg(qx,{forceMount:void 0}),KP=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:s}=e,o=Nd(qx,t);return i.jsx(oZ,{scope:t,forceMount:n,children:i.jsx(Vx,{present:n||o.open,children:i.jsx(BP,{asChild:!0,container:s,children:r})})})};KP.displayName=qx;var Wl="TooltipContent",WP=y.forwardRef((e,t)=>{const n=aZ(Wl,e.__scopeTooltip),{forceMount:r=n.forceMount,side:s="top",...o}=e,l=Nd(Wl,e.__scopeTooltip);return i.jsx(Vx,{present:r||l.open,children:l.disableHoverableContent?i.jsx(GP,{side:s,...o,ref:t}):i.jsx(iZ,{side:s,...o,ref:t})})}),iZ=y.forwardRef((e,t)=>{const n=Nd(Wl,e.__scopeTooltip),r=Hx(Wl,e.__scopeTooltip),s=y.useRef(null),o=Ui(t,s),[l,u]=y.useState(null),{trigger:d,onClose:f}=n,h=s.current,{onPointerInTransitChange:m}=r,g=y.useCallback(()=>{u(null),m(!1)},[m]),x=y.useCallback((b,w)=>{const C=b.currentTarget,k={x:b.clientX,y:b.clientY},j=dZ(k,C.getBoundingClientRect()),M=fZ(k,j),_=pZ(w.getBoundingClientRect()),R=gZ([...M,..._]);u(R),m(!0)},[m]);return y.useEffect(()=>()=>g(),[g]),y.useEffect(()=>{if(d&&h){const b=C=>x(C,h),w=C=>x(C,d);return d.addEventListener("pointerleave",b),h.addEventListener("pointerleave",w),()=>{d.removeEventListener("pointerleave",b),h.removeEventListener("pointerleave",w)}}},[d,h,x,g]),y.useEffect(()=>{if(l){const b=w=>{const C=w.target,k={x:w.clientX,y:w.clientY},j=d?.contains(C)||h?.contains(C),M=!hZ(k,l);j?g():M&&(g(),f())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[d,h,l,f,g]),i.jsx(GP,{...e,ref:o})}),[lZ,cZ]=lg(id,{isInside:!1}),uZ=gQ("TooltipContent"),GP=y.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":s,onEscapeKeyDown:o,onPointerDownOutside:l,...u}=e,d=Nd(Wl,n),f=cg(n),{onClose:h}=d;return y.useEffect(()=>(document.addEventListener(gb,h),()=>document.removeEventListener(gb,h)),[h]),y.useEffect(()=>{if(d.trigger){const m=g=>{g.target?.contains(d.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[d.trigger,h]),i.jsx(TP,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:l,onFocusOutside:m=>m.preventDefault(),onDismiss:h,children:i.jsxs(VQ,{"data-state":d.stateAttribute,...f,...u,ref:t,style:{...u.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[i.jsx(uZ,{children:r}),i.jsx(lZ,{scope:n,isInside:!0,children:i.jsx(tZ,{id:d.contentId,role:"tooltip",children:s||r})})]})})});WP.displayName=Wl;var JP="TooltipArrow",QP=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,s=cg(n);return cZ(JP,n).isInside?null:i.jsx(HQ,{...s,...r,ref:t})});QP.displayName=JP;function dZ(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),s=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,s,o)){case o:return"left";case s:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function fZ(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function pZ(e){const{top:t,right:n,bottom:r,left:s}=e;return[{x:s,y:t},{x:n,y:t},{x:n,y:r},{x:s,y:r}]}function hZ(e,t){const{x:n,y:r}=e;let s=!1;for(let o=0,l=t.length-1;or!=g>r&&n<(m-f)*(r-h)/(g-h)+f&&(s=!s)}return s}function gZ(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),mZ(t)}function mZ(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const o=t[t.length-1],l=t[t.length-2];if((o.x-l.x)*(s.y-l.y)>=(o.y-l.y)*(s.x-l.x))t.pop();else break}t.push(s)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const s=e[r];for(;n.length>=2;){const o=n[n.length-1],l=n[n.length-2];if((o.x-l.x)*(s.y-l.y)>=(o.y-l.y)*(s.x-l.x))n.pop();else break}n.push(s)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var vZ=VP,yZ=HP,bZ=qP,xZ=KP,wZ=WP,SZ=QP;function FE({content:e,children:t,side:n="top"}){return i.jsx(vZ,{delayDuration:200,children:i.jsxs(yZ,{children:[i.jsx(bZ,{asChild:!0,children:t}),i.jsx(xZ,{children:i.jsxs(wZ,{side:n,className:` + rounded px-3 py-1.5 text-sm z-50 border shadow-lg + bg-gray-100 text-gray-900 border-gray-300 + dark:bg-gray-800 dark:text-gray-100 dark:border-gray-700 + `,children:[e,i.jsx(SZ,{className:"fill-gray-100 dark:fill-gray-800",width:18,height:9})]})})]})})}function CZ(){const{t:e}=Ve(),[t,n]=y.useState(null),{deleteInstance:r,logout:s}=Hh(),{data:o,refetch:l}=q5(),[u,d]=y.useState([]),[f,h]=y.useState("all"),[m,g]=y.useState(""),x=async()=>{await l()},b=async k=>{n(null),d([...u,k]);try{try{await s(k)}catch(j){console.error("Error logout:",j)}await r(k),await new Promise(j=>setTimeout(j,1e3)),x()}catch(j){console.error("Error instance delete:",j),me.error(`Error : ${j?.response?.data?.response?.message}`)}finally{d(u.filter(j=>j!==k))}},w=y.useMemo(()=>{let k=o?[...o]:[];return f!=="all"&&(k=k.filter(j=>j.connectionStatus===f)),m!==""&&(k=k.filter(j=>j.name.toLowerCase().includes(m.toLowerCase()))),k},[o,m,f]),C=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return i.jsxs("div",{className:"my-4 px-4",children:[i.jsxs("div",{className:"flex w-full items-center justify-between",children:[i.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(se,{variant:"outline",size:"icon",children:i.jsx(Ip,{onClick:x,size:"20"})}),i.jsx(dQ,{resetTable:x})]})]}),i.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx(ne,{placeholder:e("dashboard.search"),value:m,onChange:k=>g(k.target.value)})}),i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"secondary",children:[e("dashboard.status")," ",i.jsx(J$,{size:"15"})]})}),i.jsx(hr,{children:C.map(k=>i.jsx(aM,{checked:f===k.value,onCheckedChange:j=>{j&&h(k.value)},children:k.label},k.value))})]})]}),i.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:w.length>0&&Array.isArray(w)?w.map(k=>i.jsxs(So,{children:[i.jsx(Co,{children:i.jsxs(Fu,{to:`/manager/instance/${k.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[i.jsx(FE,{content:k.name,side:"top",children:i.jsx("h3",{className:"text-wrap font-semibold truncate",children:k.name})}),i.jsx(FE,{content:e("dashboard.settings"),side:"top",children:i.jsx(se,{variant:"ghost",size:"icon",children:i.jsx(Oo,{className:"card-icon",size:"20"})})})]})}),i.jsxs(Eo,{className:"flex-1 space-y-6",children:[i.jsx(c_,{token:k.token}),i.jsxs("div",{className:"flex w-full flex-wrap",children:[i.jsx("div",{className:"flex flex-1 gap-2",children:k.profileName&&i.jsxs(i.Fragment,{children:[i.jsx(Ei,{children:i.jsx(ki,{src:k.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:k.profileName}),i.jsx("p",{className:"text-sm text-muted-foreground",children:k.ownerJid&&k.ownerJid.split("@")[0]})]})]})}),i.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(pT,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(k?._count?.Contact||0)})]}),i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(Bl,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(k?._count?.Message||0)})]})]})]})]}),i.jsxs(Vh,{className:"justify-between",children:[i.jsx(l_,{status:k.connectionStatus}),i.jsx(se,{variant:"destructive",size:"sm",onClick:()=>n(k.name),disabled:u.includes(k.name),children:u.includes(k.name)?i.jsx("span",{children:e("button.deleting")}):i.jsx("span",{children:e("button.delete")})})]})]},k.id)):i.jsx("p",{children:e("dashboard.instancesNotFound")})}),!!t&&i.jsx(Pt,{onOpenChange:()=>n(null),open:!0,children:i.jsxs(Nt,{children:[i.jsx($M,{}),i.jsx(Mt,{children:e("modal.delete.title")}),i.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),i.jsx(Yt,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(se,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),i.jsx(se,{onClick:()=>b(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:Gl,createContext:EZ,forwardRef:ZP,useCallback:Fr,useContext:YP,useEffect:vi,useImperativeHandle:XP,useLayoutEffect:kZ,useMemo:jZ,useRef:kr,useState:Mu}=Yl,LE=Yl.useId,TZ=kZ,ug=EZ(null);ug.displayName="PanelGroupContext";const yi=TZ,NZ=typeof LE=="function"?LE:()=>null;let MZ=0;function Kx(e=null){const t=NZ(),n=kr(e||t||null);return n.current===null&&(n.current=""+MZ++),e??n.current}function eO({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:l,maxSize:u,minSize:d,onCollapse:f,onExpand:h,onResize:m,order:g,style:x,tagName:b="div",...w}){const C=YP(ug);if(C===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:k,expandPanel:j,getPanelSize:M,getPanelStyle:_,groupId:R,isPanelCollapsed:N,reevaluatePanelConstraints:O,registerPanel:D,resizePanel:z,unregisterPanel:Q}=C,pe=Kx(l),V=kr({callbacks:{onCollapse:f,onExpand:h,onResize:m},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:u,minSize:d},id:pe,idIsFromProps:l!==void 0,order:g});kr({didLogMissingDefaultSizeWarning:!1}),yi(()=>{const{callbacks:W,constraints:ie}=V.current,re={...ie};V.current.id=pe,V.current.idIsFromProps=l!==void 0,V.current.order=g,W.onCollapse=f,W.onExpand=h,W.onResize=m,ie.collapsedSize=n,ie.collapsible=r,ie.defaultSize=s,ie.maxSize=u,ie.minSize=d,(re.collapsedSize!==ie.collapsedSize||re.collapsible!==ie.collapsible||re.maxSize!==ie.maxSize||re.minSize!==ie.minSize)&&O(V.current,re)}),yi(()=>{const W=V.current;return D(W),()=>{Q(W)}},[g,pe,D,Q]),XP(o,()=>({collapse:()=>{k(V.current)},expand:W=>{j(V.current,W)},getId(){return pe},getSize(){return M(V.current)},isCollapsed(){return N(V.current)},isExpanded(){return!N(V.current)},resize:W=>{z(V.current,W)}}),[k,j,M,N,pe,z]);const G=_(V.current,s);return Gl(b,{...w,children:e,className:t,id:l,style:{...G,...x},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":R,"data-panel-id":pe,"data-panel-size":parseFloat(""+G.flexGrow).toFixed(1)})}const tO=ZP((e,t)=>Gl(eO,{...e,forwardedRef:t}));eO.displayName="Panel";tO.displayName="forwardRef(Panel)";let vb=null,di=null;function _Z(e,t){if(t){const n=(t&aO)!==0,r=(t&iO)!==0,s=(t&lO)!==0,o=(t&cO)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function RZ(){di!==null&&(document.head.removeChild(di),vb=null,di=null)}function Wv(e,t){const n=_Z(e,t);vb!==n&&(vb=n,di===null&&(di=document.createElement("style"),document.head.appendChild(di)),di.innerHTML=`*{cursor: ${n}!important;}`)}function nO(e){return e.type==="keydown"}function rO(e){return e.type.startsWith("pointer")}function sO(e){return e.type.startsWith("mouse")}function dg(e){if(rO(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(sO(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function PZ(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function OZ(e,t,n){return e.xt.x&&e.yt.y}function IZ(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:zE(e),b:zE(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;kt(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:BE($E(n.a)),b:BE($E(n.b))};if(s.a===s.b){const o=r.childNodes,l={a:n.a.at(-1),b:n.b.at(-1)};let u=o.length;for(;u--;){const d=o[u];if(d===l.a)return 1;if(d===l.b)return-1}}return Math.sign(s.a-s.b)}const AZ=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function DZ(e){var t;const n=getComputedStyle((t=oO(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function FZ(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||DZ(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||AZ.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function $E(e){let t=e.length;for(;t--;){const n=e[t];if(kt(n,"Missing node"),FZ(n))return n}return null}function BE(e){return e&&Number(getComputedStyle(e).zIndex)||0}function zE(e){const t=[];for(;e;)t.push(e),e=oO(e);return t}function oO(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const aO=1,iO=2,lO=4,cO=8,LZ=PZ()==="coarse";let js=[],ld=!1,ha=new Map,fg=new Map;const cd=new Set;function $Z(e,t,n,r,s){var o;const{ownerDocument:l}=t,u={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},d=(o=ha.get(l))!==null&&o!==void 0?o:0;return ha.set(l,d+1),cd.add(u),lh(),function(){var h;fg.delete(e),cd.delete(u);const m=(h=ha.get(l))!==null&&h!==void 0?h:1;if(ha.set(l,m-1),lh(),m===1&&ha.delete(l),js.includes(u)){const g=js.indexOf(u);g>=0&&js.splice(g,1),Gx()}}}function UE(e){const{target:t}=e,{x:n,y:r}=dg(e);ld=!0,Wx({target:t,x:n,y:r}),lh(),js.length>0&&(ch("down",e),e.preventDefault(),e.stopPropagation())}function du(e){const{x:t,y:n}=dg(e);if(e.buttons===0&&(ld=!1,ch("up",e)),!ld){const{target:r}=e;Wx({target:r,x:t,y:n})}ch("move",e),Gx(),js.length>0&&e.preventDefault()}function bl(e){const{target:t}=e,{x:n,y:r}=dg(e);fg.clear(),ld=!1,js.length>0&&e.preventDefault(),ch("up",e),Wx({target:t,x:n,y:r}),Gx(),lh()}function Wx({target:e,x:t,y:n}){js.splice(0);let r=null;e instanceof HTMLElement&&(r=e),cd.forEach(s=>{const{element:o,hitAreaMargins:l}=s,u=o.getBoundingClientRect(),{bottom:d,left:f,right:h,top:m}=u,g=LZ?l.coarse:l.fine;if(t>=f-g&&t<=h+g&&n>=m-g&&n<=d+g){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&IZ(r,o)>0){let b=r,w=!1;for(;b&&!b.contains(o);){if(OZ(b.getBoundingClientRect(),u)){w=!0;break}b=b.parentElement}if(w)return}js.push(s)}})}function Gv(e,t){fg.set(e,t)}function Gx(){let e=!1,t=!1;js.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;fg.forEach(r=>{n|=r}),e&&t?Wv("intersection",n):e?Wv("horizontal",n):t?Wv("vertical",n):RZ()}function lh(){ha.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",bl),n.removeEventListener("pointerdown",UE),n.removeEventListener("pointerleave",du),n.removeEventListener("pointermove",du)}),window.removeEventListener("pointerup",bl),window.removeEventListener("pointercancel",bl),cd.size>0&&(ld?(js.length>0&&ha.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",bl),n.addEventListener("pointerleave",du),n.addEventListener("pointermove",du))}),window.addEventListener("pointerup",bl),window.addEventListener("pointercancel",bl)):ha.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",UE,{capture:!0}),n.addEventListener("pointermove",du))}))}function ch(e,t){cd.forEach(n=>{const{setResizeHandlerState:r}=n,s=js.includes(n);r(e,s,t)})}function kt(e,t){if(!e)throw console.error(t),Error(t)}const Jx=10;function Ri(e,t,n=Jx){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function xo(e,t,n=Jx){return Ri(e,t,n)===0}function $r(e,t,n){return Ri(e,t,n)===0}function BZ(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-k:k)}}}{const m=e<0?u:d,g=n[m];kt(g,`No panel constraints found for index ${m}`);const{collapsedSize:x=0,collapsible:b,minSize:w=0}=g;if(b){const C=t[m];if(kt(C!=null,`Previous layout not found for panel index ${m}`),$r(C,w)){const k=C-x;Ri(k,Math.abs(e))>0&&(e=e<0?0-k:k)}}}}{const m=e<0?1:-1;let g=e<0?d:u,x=0;for(;;){const w=t[g];kt(w!=null,`Previous layout not found for panel index ${g}`);const k=Ml({panelConstraints:n,panelIndex:g,size:100})-w;if(x+=k,g+=m,g<0||g>=n.length)break}const b=Math.min(Math.abs(e),Math.abs(x));e=e<0?0-b:b}{let g=e<0?u:d;for(;g>=0&&g=0))break;e<0?g--:g++}}if(BZ(s,l))return s;{const m=e<0?d:u,g=t[m];kt(g!=null,`Previous layout not found for panel index ${m}`);const x=g+f,b=Ml({panelConstraints:n,panelIndex:m,size:x});if(l[m]=b,!$r(b,x)){let w=x-b,k=e<0?d:u;for(;k>=0&&k0?k--:k++}}}const h=l.reduce((m,g)=>g+m,0);return $r(h,100)?l:s}function zZ({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,l=0;const u=n[0];kt(u!=null,"No pivot index found"),t.forEach((m,g)=>{const{constraints:x}=m,{maxSize:b=100,minSize:w=0}=x;g===u?(r=w,s=b):(o+=w,l+=b)});const d=Math.min(s,100-o),f=Math.max(r,100-l),h=e[u];return{valueMax:d,valueMin:f,valueNow:h}}function ud(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function uO(e,t,n=document){const s=ud(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function dO(e,t,n){const r=uO(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function fO(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function pg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function UZ(e,t,n,r=document){var s,o,l,u;const d=pg(t,r),f=ud(e,r),h=d?f.indexOf(d):-1,m=(s=(o=n[h])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,g=(l=(u=n[h+1])===null||u===void 0?void 0:u.id)!==null&&l!==void 0?l:null;return[m,g]}function VZ({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:l}){kr({didWarnAboutMissingResizeHandle:!1}),yi(()=>{if(!o)return;const u=ud(n,o);for(let d=0;d{u.forEach((d,f)=>{d.removeAttribute("aria-controls"),d.removeAttribute("aria-valuemax"),d.removeAttribute("aria-valuemin"),d.removeAttribute("aria-valuenow")})}},[n,r,s,o]),vi(()=>{if(!o)return;const u=t.current;kt(u,"Eager values not found");const{panelDataArray:d}=u,f=fO(n,o);kt(f!=null,`No group found for id "${n}"`);const h=ud(n,o);kt(h,`No resize handles found for group id "${n}"`);const m=h.map(g=>{const x=g.getAttribute("data-panel-resize-handle-id");kt(x,"Resize handle element has no handle id attribute");const[b,w]=UZ(n,x,d,o);if(b==null||w==null)return()=>{};const C=k=>{if(!k.defaultPrevented)switch(k.key){case"Enter":{k.preventDefault();const j=d.findIndex(M=>M.id===b);if(j>=0){const M=d[j];kt(M,`No panel data found for index ${j}`);const _=r[j],{collapsedSize:R=0,collapsible:N,minSize:O=0}=M.constraints;if(_!=null&&N){const D=wu({delta:$r(_,R)?O-R:R-_,initialLayout:r,panelConstraints:d.map(z=>z.constraints),pivotIndices:dO(n,x,o),prevLayout:r,trigger:"keyboard"});r!==D&&l(D)}}break}}};return g.addEventListener("keydown",C),()=>{g.removeEventListener("keydown",C)}});return()=>{m.forEach(g=>g())}},[o,e,t,n,r,s,l])}function VE(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];kt(o,`Panel data not found for index ${s}`);const{callbacks:l,constraints:u,id:d}=o,{collapsedSize:f=0,collapsible:h}=u,m=n[d];if(m==null||r!==m){n[d]=r;const{onCollapse:g,onExpand:x,onResize:b}=l;b&&b(r,m),h&&(g||x)&&(x&&(m==null||xo(m,f))&&!xo(r,f)&&x(),g&&(m==null||!xo(m,f))&&xo(r,f)&&g())}})}function ep(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function HE(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function hO(e){return`react-resizable-panels:${e}`}function gO(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function mO(e,t){try{const n=hO(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function JZ(e,t,n){var r,s;const o=(r=mO(e,n))!==null&&r!==void 0?r:{},l=gO(t);return(s=o[l])!==null&&s!==void 0?s:null}function QZ(e,t,n,r,s){var o;const l=hO(e),u=gO(t),d=(o=mO(e,s))!==null&&o!==void 0?o:{};d[u]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(l,JSON.stringify(d))}catch(f){console.error(f)}}function qE({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,l)=>o+l,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!$r(r,100))for(let o=0;o(HE(Su),Su.getItem(e)),setItem:(e,t)=>{HE(Su),Su.setItem(e,t)}},KE={};function vO({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:l=null,keyboardResizeBy:u=null,storage:d=Su,style:f,tagName:h="div",...m}){const g=Kx(o),x=kr(null),[b,w]=Mu(null),[C,k]=Mu([]),j=kr({}),M=kr(new Map),_=kr(0),R=kr({autoSaveId:e,direction:r,dragState:b,id:g,keyboardResizeBy:u,onLayout:l,storage:d}),N=kr({layout:C,panelDataArray:[],panelDataArrayChanged:!1});kr({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),XP(s,()=>({getId:()=>R.current.id,getLayout:()=>{const{layout:F}=N.current;return F},setLayout:F=>{const{onLayout:fe}=R.current,{layout:te,panelDataArray:de}=N.current,ge=qE({layout:F,panelConstraints:de.map(Z=>Z.constraints)});VE(te,ge)||(k(ge),N.current.layout=ge,fe&&fe(ge),xl(de,ge,j.current))}}),[]),yi(()=>{R.current.autoSaveId=e,R.current.direction=r,R.current.dragState=b,R.current.id=g,R.current.onLayout=l,R.current.storage=d}),VZ({committedValuesRef:R,eagerValuesRef:N,groupId:g,layout:C,panelDataArray:N.current.panelDataArray,setLayout:k,panelGroupElement:x.current}),vi(()=>{const{panelDataArray:F}=N.current;if(e){if(C.length===0||C.length!==F.length)return;let fe=KE[e];fe==null&&(fe=GZ(QZ,ZZ),KE[e]=fe);const te=[...F],de=new Map(M.current);fe(e,te,de,C,d)}},[e,C,d]),vi(()=>{});const O=Fr(F=>{const{onLayout:fe}=R.current,{layout:te,panelDataArray:de}=N.current;if(F.constraints.collapsible){const ge=de.map($e=>$e.constraints),{collapsedSize:Z=0,panelSize:ye,pivotIndices:Re}=ri(de,F,te);if(kt(ye!=null,`Panel size not found for panel "${F.id}"`),!xo(ye,Z)){M.current.set(F.id,ye);const Ye=kl(de,F)===de.length-1?ye-Z:Z-ye,Fe=wu({delta:Ye,initialLayout:te,panelConstraints:ge,pivotIndices:Re,prevLayout:te,trigger:"imperative-api"});ep(te,Fe)||(k(Fe),N.current.layout=Fe,fe&&fe(Fe),xl(de,Fe,j.current))}}},[]),D=Fr((F,fe)=>{const{onLayout:te}=R.current,{layout:de,panelDataArray:ge}=N.current;if(F.constraints.collapsible){const Z=ge.map(ft=>ft.constraints),{collapsedSize:ye=0,panelSize:Re=0,minSize:$e=0,pivotIndices:Ye}=ri(ge,F,de),Fe=fe??$e;if(xo(Re,ye)){const ft=M.current.get(F.id),ln=ft!=null&&ft>=Fe?ft:Fe,vn=kl(ge,F)===ge.length-1?Re-ln:ln-Re,Cn=wu({delta:vn,initialLayout:de,panelConstraints:Z,pivotIndices:Ye,prevLayout:de,trigger:"imperative-api"});ep(de,Cn)||(k(Cn),N.current.layout=Cn,te&&te(Cn),xl(ge,Cn,j.current))}}},[]),z=Fr(F=>{const{layout:fe,panelDataArray:te}=N.current,{panelSize:de}=ri(te,F,fe);return kt(de!=null,`Panel size not found for panel "${F.id}"`),de},[]),Q=Fr((F,fe)=>{const{panelDataArray:te}=N.current,de=kl(te,F);return WZ({defaultSize:fe,dragState:b,layout:C,panelData:te,panelIndex:de})},[b,C]),pe=Fr(F=>{const{layout:fe,panelDataArray:te}=N.current,{collapsedSize:de=0,collapsible:ge,panelSize:Z}=ri(te,F,fe);return kt(Z!=null,`Panel size not found for panel "${F.id}"`),ge===!0&&xo(Z,de)},[]),V=Fr(F=>{const{layout:fe,panelDataArray:te}=N.current,{collapsedSize:de=0,collapsible:ge,panelSize:Z}=ri(te,F,fe);return kt(Z!=null,`Panel size not found for panel "${F.id}"`),!ge||Ri(Z,de)>0},[]),G=Fr(F=>{const{panelDataArray:fe}=N.current;fe.push(F),fe.sort((te,de)=>{const ge=te.order,Z=de.order;return ge==null&&Z==null?0:ge==null?-1:Z==null?1:ge-Z}),N.current.panelDataArrayChanged=!0},[]);yi(()=>{if(N.current.panelDataArrayChanged){N.current.panelDataArrayChanged=!1;const{autoSaveId:F,onLayout:fe,storage:te}=R.current,{layout:de,panelDataArray:ge}=N.current;let Z=null;if(F){const Re=JZ(F,ge,te);Re&&(M.current=new Map(Object.entries(Re.expandToSizes)),Z=Re.layout)}Z==null&&(Z=KZ({panelDataArray:ge}));const ye=qE({layout:Z,panelConstraints:ge.map(Re=>Re.constraints)});VE(de,ye)||(k(ye),N.current.layout=ye,fe&&fe(ye),xl(ge,ye,j.current))}}),yi(()=>{const F=N.current;return()=>{F.layout=[]}},[]);const W=Fr(F=>function(te){te.preventDefault();const de=x.current;if(!de)return()=>null;const{direction:ge,dragState:Z,id:ye,keyboardResizeBy:Re,onLayout:$e}=R.current,{layout:Ye,panelDataArray:Fe}=N.current,{initialLayout:ft}=Z??{},ln=dO(ye,F,de);let Sn=qZ(te,F,ge,Z,Re,de);const vn=ge==="horizontal";document.dir==="rtl"&&vn&&(Sn=-Sn);const Cn=Fe.map(ue=>ue.constraints),L=wu({delta:Sn,initialLayout:ft??Ye,panelConstraints:Cn,pivotIndices:ln,prevLayout:Ye,trigger:nO(te)?"keyboard":"mouse-or-touch"}),X=!ep(Ye,L);(rO(te)||sO(te))&&_.current!=Sn&&(_.current=Sn,X?Gv(F,0):vn?Gv(F,Sn<0?aO:iO):Gv(F,Sn<0?lO:cO)),X&&(k(L),N.current.layout=L,$e&&$e(L),xl(Fe,L,j.current))},[]),ie=Fr((F,fe)=>{const{onLayout:te}=R.current,{layout:de,panelDataArray:ge}=N.current,Z=ge.map(ft=>ft.constraints),{panelSize:ye,pivotIndices:Re}=ri(ge,F,de);kt(ye!=null,`Panel size not found for panel "${F.id}"`);const Ye=kl(ge,F)===ge.length-1?ye-fe:fe-ye,Fe=wu({delta:Ye,initialLayout:de,panelConstraints:Z,pivotIndices:Re,prevLayout:de,trigger:"imperative-api"});ep(de,Fe)||(k(Fe),N.current.layout=Fe,te&&te(Fe),xl(ge,Fe,j.current))},[]),re=Fr((F,fe)=>{const{layout:te,panelDataArray:de}=N.current,{collapsedSize:ge=0,collapsible:Z}=fe,{collapsedSize:ye=0,collapsible:Re,maxSize:$e=100,minSize:Ye=0}=F.constraints,{panelSize:Fe}=ri(de,F,te);Fe!=null&&(Z&&Re&&xo(Fe,ge)?xo(ge,ye)||ie(F,ye):Fe$e&&ie(F,$e))},[ie]),Y=Fr((F,fe)=>{const{direction:te}=R.current,{layout:de}=N.current;if(!x.current)return;const ge=pg(F,x.current);kt(ge,`Drag handle element not found for id "${F}"`);const Z=pO(te,fe);w({dragHandleId:F,dragHandleRect:ge.getBoundingClientRect(),initialCursorPosition:Z,initialLayout:de})},[]),H=Fr(()=>{w(null)},[]),q=Fr(F=>{const{panelDataArray:fe}=N.current,te=kl(fe,F);te>=0&&(fe.splice(te,1),delete j.current[F.id],N.current.panelDataArrayChanged=!0)},[]),he=jZ(()=>({collapsePanel:O,direction:r,dragState:b,expandPanel:D,getPanelSize:z,getPanelStyle:Q,groupId:g,isPanelCollapsed:pe,isPanelExpanded:V,reevaluatePanelConstraints:re,registerPanel:G,registerResizeHandle:W,resizePanel:ie,startDragging:Y,stopDragging:H,unregisterPanel:q,panelGroupElement:x.current}),[O,b,r,D,z,Q,g,pe,V,re,G,W,ie,Y,H,q]),A={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return Gl(ug.Provider,{value:he},Gl(h,{...m,children:t,className:n,id:o,ref:x,style:{...A,...f},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":g}))}const yO=ZP((e,t)=>Gl(vO,{...e,forwardedRef:t}));vO.displayName="PanelGroup";yO.displayName="forwardRef(PanelGroup)";function kl(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function ri(e,t,n){const r=kl(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],l=n[r];return{...t.constraints,panelSize:l,pivotIndices:o}}function YZ({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){vi(()=>{if(e||n==null||r==null)return;const s=pg(t,r);if(s==null)return;const o=l=>{if(!l.defaultPrevented)switch(l.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{l.preventDefault(),n(l);break}case"F6":{l.preventDefault();const u=s.getAttribute("data-panel-group-id");kt(u,`No group element found for id "${u}"`);const d=ud(u,r),f=uO(u,t,r);kt(f!==null,`No resize element found for id "${t}"`);const h=l.shiftKey?f>0?f-1:d.length-1:f+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function bO({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:l,onFocus:u,style:d={},tabIndex:f=0,tagName:h="div",...m}){var g,x;const b=kr(null),w=kr({onDragging:l});vi(()=>{w.current.onDragging=l});const C=YP(ug);if(C===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:k,groupId:j,registerResizeHandle:M,startDragging:_,stopDragging:R,panelGroupElement:N}=C,O=Kx(s),[D,z]=Mu("inactive"),[Q,pe]=Mu(!1),[V,G]=Mu(null),W=kr({state:D});yi(()=>{W.current.state=D}),vi(()=>{if(n)G(null);else{const H=M(O);G(()=>H)}},[n,O,M]);const ie=(g=r?.coarse)!==null&&g!==void 0?g:15,re=(x=r?.fine)!==null&&x!==void 0?x:5;return vi(()=>{if(n||V==null)return;const H=b.current;return kt(H,"Element ref not attached"),$Z(O,H,k,{coarse:ie,fine:re},(he,A,F)=>{if(A)switch(he){case"down":{z("drag"),_(O,F);const{onDragging:fe}=w.current;fe&&fe(!0);break}case"move":{const{state:fe}=W.current;fe!=="drag"&&z("hover"),V(F);break}case"up":{z("hover"),R();const{onDragging:fe}=w.current;fe&&fe(!1);break}}else z("inactive")})},[ie,k,n,re,M,O,V,_,R]),YZ({disabled:n,handleId:O,resizeHandler:V,panelGroupElement:N}),Gl(h,{...m,children:e,className:t,id:s,onBlur:()=>{pe(!1),o?.()},onFocus:()=>{pe(!0),u?.()},ref:b,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...d},tabIndex:f,"data-panel-group-direction":k,"data-panel-group-id":j,"data-resize-handle":"","data-resize-handle-active":D==="drag"?"pointer":Q?"keyboard":void 0,"data-resize-handle-state":D,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":O})}bO.displayName="PanelResizeHandle";const $o=({className:e,...t})=>i.jsx(yO,{className:Ie("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),Hn=tO,Bo=({withHandle:e,className:t,...n})=>i.jsx(bO,{className:Ie("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&i.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:i.jsx(lB,{className:"h-2.5 w-2.5"})})});var Qx="Tabs",[XZ]=us(Qx,[Dh]),xO=Dh(),[eY,Zx]=XZ(Qx),wO=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:l="horizontal",dir:u,activationMode:d="automatic",...f}=e,h=xd(u),[m,g]=ya({prop:r,onChange:s,defaultProp:o});return i.jsx(eY,{scope:n,baseId:Es(),value:m,onValueChange:g,orientation:l,dir:h,activationMode:d,children:i.jsx(rt.div,{dir:h,"data-orientation":l,...f,ref:t})})});wO.displayName=Qx;var SO="TabsList",CO=y.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=Zx(SO,n),l=xO(n);return i.jsx(aN,{asChild:!0,...l,orientation:o.orientation,dir:o.dir,loop:r,children:i.jsx(rt.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});CO.displayName=SO;var EO="TabsTrigger",kO=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,l=Zx(EO,n),u=xO(n),d=NO(l.baseId,r),f=MO(l.baseId,r),h=r===l.value;return i.jsx(iN,{asChild:!0,...u,focusable:!s,active:h,children:i.jsx(rt.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":f,"data-state":h?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:d,...o,ref:t,onMouseDown:Ue(e.onMouseDown,m=>{!s&&m.button===0&&m.ctrlKey===!1?l.onValueChange(r):m.preventDefault()}),onKeyDown:Ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&l.onValueChange(r)}),onFocus:Ue(e.onFocus,()=>{const m=l.activationMode!=="manual";!h&&!s&&m&&l.onValueChange(r)})})})});kO.displayName=EO;var jO="TabsContent",TO=y.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...l}=e,u=Zx(jO,n),d=NO(u.baseId,r),f=MO(u.baseId,r),h=r===u.value,m=y.useRef(h);return y.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),i.jsx(Mr,{present:s||h,children:({present:g})=>i.jsx(rt.div,{"data-state":h?"active":"inactive","data-orientation":u.orientation,role:"tabpanel","aria-labelledby":d,hidden:!g,id:f,tabIndex:0,...l,ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0},children:g&&o})})});TO.displayName=jO;function NO(e,t){return`${e}-trigger-${t}`}function MO(e,t){return`${e}-content-${t}`}var tY=wO,_O=CO,RO=kO,PO=TO;const Yx=tY,hg=y.forwardRef(({className:e,...t},n)=>i.jsx(_O,{ref:n,className:Ie("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));hg.displayName=_O.displayName;const Jl=y.forwardRef(({className:e,...t},n)=>i.jsx(RO,{ref:n,className:Ie("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));Jl.displayName=RO.displayName;const Ql=y.forwardRef(({className:e,...t},n)=>i.jsx(PO,{ref:n,className:Ie("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));Ql.displayName=PO.displayName;const nY=e=>["chats","findChats",JSON.stringify(e)],rY=async({instanceName:e})=>(await Ee.post(`/chat/findChats/${e}`,{where:{}})).data,sY=e=>{const{instanceName:t,...n}=e;return mt({...n,queryKey:nY({instanceName:t}),queryFn:()=>rY({instanceName:t}),enabled:!!t})};function zo(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=y.useState(t(e));function s(){r(t(e))}return y.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const Ys=Object.create(null);Ys.open="0";Ys.close="1";Ys.ping="2";Ys.pong="3";Ys.message="4";Ys.upgrade="5";Ys.noop="6";const Cp=Object.create(null);Object.keys(Ys).forEach(e=>{Cp[Ys[e]]=e});const yb={type:"error",data:"parser error"},OO=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",IO=typeof ArrayBuffer=="function",AO=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Xx=({type:e,data:t},n,r)=>OO&&t instanceof Blob?n?r(t):WE(t,r):IO&&(t instanceof ArrayBuffer||AO(t))?n?r(t):WE(new Blob([t]),r):r(Ys[e]+(t||"")),WE=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function GE(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Jv;function oY(e,t){if(OO&&e.data instanceof Blob)return e.data.arrayBuffer().then(GE).then(t);if(IO&&(e.data instanceof ArrayBuffer||AO(e.data)))return t(GE(e.data));Xx(e,!1,n=>{Jv||(Jv=new TextEncoder),t(Jv.encode(n))})}const JE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,s=0,o,l,u,d;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),h=new Uint8Array(f);for(r=0;r>4,h[s++]=(l&15)<<4|u>>2,h[s++]=(u&3)<<6|d&63;return f},iY=typeof ArrayBuffer=="function",ew=(e,t)=>{if(typeof e!="string")return{type:"message",data:DO(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:lY(e.substring(1),t)}:Cp[n]?e.length>1?{type:Cp[n],data:e.substring(1)}:{type:Cp[n]}:yb},lY=(e,t)=>{if(iY){const n=aY(e);return DO(n,t)}else return{base64:!0,data:e}},DO=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},FO="",cY=(e,t)=>{const n=e.length,r=new Array(n);let s=0;e.forEach((o,l)=>{Xx(o,!1,u=>{r[l]=u,++s===n&&t(r.join(FO))})})},uY=(e,t)=>{const n=e.split(FO),r=[];for(let s=0;s{const r=n.length;let s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);const o=new DataView(s.buffer);o.setUint8(0,126),o.setUint16(1,r)}else{s=new Uint8Array(9);const o=new DataView(s.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(s[0]|=128),t.enqueue(s),t.enqueue(n)})}})}let Qv;function tp(e){return e.reduce((t,n)=>t+n.length,0)}function np(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let s=0;sMath.pow(2,21)-1){u.enqueue(yb);break}s=h*Math.pow(2,32)+f.getUint32(4),r=3}else{if(tp(n)e){u.enqueue(yb);break}}}})}const LO=4;function Pn(e){if(e)return pY(e)}function pY(e){for(var t in Pn.prototype)e[t]=Pn.prototype[t];return e}Pn.prototype.on=Pn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Pn.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Pn.prototype.off=Pn.prototype.removeListener=Pn.prototype.removeAllListeners=Pn.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,s=0;sPromise.resolve().then(t):(t,n)=>n(t,0),as=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),hY="arraybuffer";function $O(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const gY=as.setTimeout,mY=as.clearTimeout;function mg(e,t){t.useNativeTimers?(e.setTimeoutFn=gY.bind(as),e.clearTimeoutFn=mY.bind(as)):(e.setTimeoutFn=as.setTimeout.bind(as),e.clearTimeoutFn=as.clearTimeout.bind(as))}const vY=1.33;function yY(e){return typeof e=="string"?bY(e):Math.ceil((e.byteLength||e.size)*vY)}function bY(e){let t=0,n=0;for(let r=0,s=e.length;r=57344?n+=3:(r++,n+=4);return n}function BO(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xY(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function wY(e){let t={},n=e.split("&");for(let r=0,s=n.length;r{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};uY(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,cY(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=BO()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let zO=!1;try{zO=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const EY=zO;function kY(){}class jY extends CY{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(s,o)=>{this.onError("xhr post error",s,o)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}let Dl=class Ep extends Pn{constructor(t,n,r){super(),this.createRequest=t,mg(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=$O(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&r.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var s;r.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=Ep.requestsCount++,Ep.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=kY,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Ep.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Dl.requestsCount=0;Dl.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",QE);else if(typeof addEventListener=="function"){const e="onpagehide"in as?"pagehide":"unload";addEventListener(e,QE,!1)}}function QE(){for(let e in Dl.requests)Dl.requests.hasOwnProperty(e)&&Dl.requests[e].abort()}const TY=(function(){const e=UO({xdomain:!1});return e&&e.responseType!==null})();class NY extends jY{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=TY&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new Dl(UO,this.uri(),t)}}function UO(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||EY))return new XMLHttpRequest}catch{}if(!t)try{return new as[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const VO=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class MY extends tw{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=VO?{}:$O(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{try{this.doWrite(r,o)}catch{}s&&gg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=BO()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Zv=as.WebSocket||as.MozWebSocket;class _Y extends MY{createSocket(t,n,r){return VO?new Zv(t,n,r):n?new Zv(t,n):new Zv(t)}doWrite(t,n){this.ws.send(n)}}class RY extends tw{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=fY(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),s=dY();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const o=()=>{r.read().then(({done:u,value:d})=>{u||(this.onPacket(d),o())}).catch(u=>{})};o();const l={type:"open"};this.query.sid&&(l.data=`{"sid":"${this.query.sid}"}`),this._writer.write(l).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n{s&&gg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const PY={websocket:_Y,webtransport:RY,polling:NY},OY=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,IY=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function bb(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let s=OY.exec(e||""),o={},l=14;for(;l--;)o[IY[l]]=s[l]||"";return n!=-1&&r!=-1&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=AY(o,o.path),o.queryKey=DY(o,o.query),o}function AY(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function DY(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,o){s&&(n[s]=o)}),n}const xb=typeof addEventListener=="function"&&typeof removeEventListener=="function",kp=[];xb&&addEventListener("offline",()=>{kp.forEach(e=>e())},!1);class va extends Pn{constructor(t,n){if(super(),this.binaryType=hY,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=bb(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=bb(n.host).host);mg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const s=r.prototype.name;this.transports.push(s),this._transportsByName[s]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=wY(this.opts.query)),xb&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},kp.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=LO,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&va.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",va.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,gg(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,s){if(typeof n=="function"&&(s=n,n=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const o={type:t,data:n,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(va.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),xb&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=kp.indexOf(this._offlineEventListener);r!==-1&&kp.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}va.protocol=LO;class FY extends va{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;va.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function o(){r||(r=!0,h(),n.close(),n=null)}const l=m=>{const g=new Error("probe error: "+m);g.transport=n.name,o(),this.emitReserved("upgradeError",g)};function u(){l("transport closed")}function d(){l("socket closed")}function f(m){n&&m.name!==n.name&&o()}const h=()=>{n.removeListener("open",s),n.removeListener("error",l),n.removeListener("close",u),this.off("close",d),this.off("upgrading",f)};n.once("open",s),n.once("error",l),n.once("close",u),this.once("close",d),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;rPY[s]).filter(s=>!!s)),super(t,r)}};function $Y(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=bb(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}const BY=typeof ArrayBuffer=="function",zY=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,HO=Object.prototype.toString,UY=typeof Blob=="function"||typeof Blob<"u"&&HO.call(Blob)==="[object BlobConstructor]",VY=typeof File=="function"||typeof File<"u"&&HO.call(File)==="[object FileConstructor]";function nw(e){return BY&&(e instanceof ArrayBuffer||zY(e))||UY&&e instanceof Blob||VY&&e instanceof File}function jp(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let u=0;u{this.io.clearTimeoutFn(o),n.apply(this,u)};l.withError=!0,this.acks[t]=l}emitWithAck(t,...n){return new Promise((r,s)=>{const o=(l,u)=>l?s(l):r(u);o.withError=!0,n.push(o),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((s,...o)=>r!==this._queue[0]?void 0:(s!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(s)):(this._queue.shift(),n&&n(null,...o)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:_t.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case _t.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case _t.EVENT:case _t.BINARY_EVENT:this.onevent(t);break;case _t.ACK:case _t.BINARY_ACK:this.onack(t);break;case _t.DISCONNECT:this.ondisconnect();break;case _t.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...s){r||(r=!0,n.packet({type:_t.ACK,id:t,data:s}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:_t.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}mc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(Math.floor(t*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};mc.prototype.reset=function(){this.attempts=0};mc.prototype.setMin=function(e){this.ms=e};mc.prototype.setMax=function(e){this.max=e};mc.prototype.setJitter=function(e){this.jitter=e};class Cb extends Pn{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,mg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new mc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const s=n.parser||QY;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new LY(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const s=xs(n,"open",function(){r.onopen(),t&&t()}),o=u=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",u),t?t(u):this.maybeReconnectOnOpen()},l=xs(n,"error",o);if(this._timeout!==!1){const u=this._timeout,d=this.setTimeoutFn(()=>{s(),o(new Error("timeout")),n.close()},u);this.opts.autoUnref&&d.unref(),this.subs.push(()=>{this.clearTimeoutFn(d)})}return this.subs.push(s),this.subs.push(l),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(xs(t,"ping",this.onping.bind(this)),xs(t,"data",this.ondata.bind(this)),xs(t,"error",this.onerror.bind(this)),xs(t,"close",this.onclose.bind(this)),xs(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){gg(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new qO(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(s=>{s?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",s)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const fu={};function Tp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=$Y(e,t.path||"/socket.io"),r=n.source,s=n.id,o=n.path,l=fu[s]&&o in fu[s].nsps,u=t.forceNew||t["force new connection"]||t.multiplex===!1||l;let d;return u?d=new Cb(r,t):(fu[s]||(fu[s]=new Cb(r,t)),d=fu[s]),n.query&&!t.query&&(t.query=n.queryKey),d.socket(n.path,t)}Object.assign(Tp,{Manager:Cb,Socket:qO,io:Tp,connect:Tp});const _u=new Map,sw=e=>{if(_u.has(e)){const n=_u.get(e);return YE(n)}const t=Tp(e,{transports:["websocket","polling"],autoConnect:!1,reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,timeout:2e4});return _u.set(e,t),t.on("connect",()=>{console.log(`✅ WebSocket connected to ${e}`)}),t.on("disconnect",n=>{console.log(`❌ WebSocket disconnected from ${e}:`,n)}),t.on("connect_error",n=>{console.error(`🚫 WebSocket connection error to ${e}:`,n)}),t.on("reconnect",n=>{console.log(`🔄 WebSocket reconnected to ${e} after ${n} attempts`)}),t.on("reconnect_error",n=>{console.error(`🔄❌ WebSocket reconnection error to ${e}:`,n)}),YE(t)},ow=e=>{for(const[t,n]of _u.entries())if(n===e||e._socket===n){console.log(`🔌 Disconnecting socket for ${t}`),n.disconnect(),_u.delete(t);break}},YE=e=>({on:(t,n)=>{e.on(t,n)},off:t=>{e.off(t)},connect:()=>{e.connected||e.connect()},disconnect:()=>{e.disconnect()}}),bi=y.forwardRef(({className:e,...t},n)=>i.jsx("textarea",{className:Ie("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));bi.displayName="Textarea";const YY=e=>["chats","findChats",JSON.stringify(e)],XY=async({instanceName:e,remoteJid:t})=>{const n=await Ee.post(`/chat/findChats/${e}`,{where:{remoteJid:t}});return Array.isArray(n.data)?n.data[0]:n.data},eX=e=>{const{instanceName:t,remoteJid:n,...r}=e;return mt({...r,queryKey:YY({instanceName:t,remoteJid:n}),queryFn:()=>XY({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},tX=e=>["chats","findMessages",JSON.stringify(e)],nX=async({instanceName:e,remoteJid:t})=>{const n=await Ee.post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}});return n.data?.messages?.records?n.data.messages.records:n.data},rX=e=>{const{instanceName:t,remoteJid:n,...r}=e;return mt({...r,queryKey:tX({instanceName:t,remoteJid:n}),queryFn:()=>nX({instanceName:t,remoteJid:n}),enabled:!!t&&!!n})},sX=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/message/sendText/${e}`,n,{headers:{apikey:t,"content-type":"application/json"}})).data,oX=async({instanceName:e,token:t,data:n})=>{try{const r={number:n.number,mediatype:n.mediaMessage.mediatype,mimetype:n.mediaMessage.mimetype,caption:n.mediaMessage.caption,media:n.mediaMessage.media,fileName:n.mediaMessage.fileName};return(await Ee.post(`/message/sendMedia/${e}`,r,{headers:{apikey:t,"content-type":"application/json"}})).data}catch(r){throw console.error("Erro ao enviar mídia:",r),r}},aX=async({instanceName:e,token:t,data:n})=>{try{const r={number:n.number,audioMessage:{audio:n.audioMessage.audio},options:n.options};return(await Ee.post(`/message/sendWhatsAppAudio/${e}`,r,{headers:{apikey:t,"content-type":"application/json"}})).data}catch(r){throw console.error("Erro ao enviar áudio:",r),r}};function KO(){return{sendText:nt(sX,{invalidateKeys:[["chats","findMessages"],["chats","findChats"]]})}}function WO(){return{sendMedia:nt(oX)}}function iX(){return{sendAudio:nt(aX)}}const GO=y.createContext({backgroundColor:"",textForegroundColor:"",primaryColor:"",fromMeBubbleColor:"",fromMeForegroundColor:"",fromOtherBubbleColor:"",fromOtherForegroundColor:"",fromMeQuotedBubbleColor:"",fromOtherQuotedBubbleColor:"",inputBackgroundColor:"",inputTextForegroundColor:"",inputIconsMainColor:""});function lX({children:e}){const[t]=hd(),{theme:n}=tc(),r=t.get("backgroundColor"),s=t.get("textForegroundColor"),o=t.get("primaryColor"),l=t.get("fromMeBubbleColor"),u=t.get("fromMeForegroundColor"),d=t.get("fromOtherBubbleColor"),f=t.get("fromOtherForegroundColor"),h=t.get("fromMeQuotedBubbleColor"),m=t.get("fromOtherQuotedBubbleColor"),g=t.get("inputBackgroundColor"),x=t.get("inputTextForegroundColor"),b=t.get("inputIconsMainColor"),w=()=>n==="dark"?"#0f0f0f":"#faf9fa",C=()=>n==="dark"?"#faf9fa":"#020202",k=()=>n==="dark"?"#0b332a":"#e0f0f0",j=()=>n==="dark"?"#0b332a":"#c8fff2",M=()=>n==="dark"?"#ffffff":"#020202",_=()=>n==="dark"?"#1d2724":"#e0f0f0",R=()=>n==="dark"?"#ffffff":"#020202",N=()=>n==="dark"?"#161616":"#e0f0f0",O=()=>n==="dark"?"#faf9fa":"#020202",D=()=>n==="dark"?"#1f463d":"#aff7e6",z=()=>n==="dark"?"#0f1413":"#d2e2e2",Q=()=>n==="dark"?"#0e6451":"#0b332a";return i.jsx(GO.Provider,{value:{backgroundColor:r||w(),textForegroundColor:s||C(),primaryColor:o||k(),fromMeBubbleColor:l||j(),fromMeForegroundColor:u||M(),fromOtherBubbleColor:d||_(),fromOtherForegroundColor:f||R(),fromMeQuotedBubbleColor:h||D(),fromOtherQuotedBubbleColor:m||z(),inputBackgroundColor:g||N(),inputTextForegroundColor:x||O(),inputIconsMainColor:b||Q()},children:e})}const La=()=>y.useContext(GO),JO=({setSelectedMedia:e})=>{const{t}=Ve(),{inputIconsMainColor:n}=La(),r=y.useRef(null),s=y.useRef(null),[o,l]=y.useState(!1),u=m=>{const g=m.target.files?.[0];if(!g){e(null);return}const x=g.type.split("/")[0],b=g.size/(1024*1024);switch(x){case"audio":if(b>16){me.error(t("chat.media.errors.audioSize"));return}break;case"image":if(b>5){me.error(t("chat.media.errors.imageSize"));return}break;case"video":if(b>16){me.error(t("chat.media.errors.videoSize"));return}break;case"application":case"text":if(b>100){me.error(t("chat.media.errors.documentSize"));return}break;default:me.error(t("chat.media.errors.unsupportedType"));return}e(g)},d=m=>{m.preventDefault(),r.current&&r.current.click()},f=m=>{m.preventDefault(),s.current&&s.current.click()},h=["text/plain","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/zip","application/x-rar-compressed","application/x-7z-compressed"];return i.jsx(i.Fragment,{children:i.jsxs(Kr,{open:o,onOpenChange:l,children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{type:"button",variant:"ghost",size:"icon",className:"rounded-full p-2",children:[i.jsx(cs,{className:"h-6 w-6",style:{color:n}}),i.jsx("span",{className:"sr-only",children:t("chat.media.attach")})]})}),i.jsxs(hr,{align:"end",children:[i.jsx("input",{ref:s,type:"file",accept:h.join(", "),onChange:u,className:"hidden"}),i.jsxs(wt,{onClick:f,children:[i.jsx(rB,{className:"mr-2 h-4 w-4"}),t("chat.media.document")]}),i.jsx("input",{ref:r,type:"file",accept:"image/*, video/*",onChange:u,className:"hidden"}),i.jsxs(wt,{onClick:d,children:[i.jsx(uB,{className:"mr-2 h-4 w-4"}),t("chat.media.photosAndVideos")]})]})]})})},QO=({selectedMedia:e,setSelectedMedia:t})=>{const{t:n}=Ve(),r=()=>{t(null)},s=l=>l.type.includes("image")?i.jsx("img",{className:"w-80 rounded-lg",src:URL.createObjectURL(l),alt:n("chat.media.selectedMedia.imageAlt"),style:{maxHeight:"400px",objectFit:"contain"}}):l.type.includes("video")?i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("video",{className:"w-80 rounded-lg object-cover",src:URL.createObjectURL(l),controls:!0})}):i.jsx("div",{className:"flex items-center justify-center",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Hb,{className:"h-6 w-6"}),n("chat.media.selectedMedia.file")]})}),o=l=>{const u=["B","KB","MB","GB","TB"];let d=0;for(;l>1024;)l/=1024,d++;return`${l.toFixed(2)} ${u[d]}`};return i.jsxs("div",{className:"relative flex items-center rounded-lg bg-[#e0f0f0] dark:bg-[#1d2724] dark:text-white",children:[i.jsx("div",{className:"absolute h-full w-1 rounded-l-lg bg-blue-700 dark:bg-blue-300"}),i.jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-6 p-4 pl-4",children:[e&&s(e),i.jsxs("div",{className:"flex flex-col items-center justify-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium",children:e?.name||n("chat.media.selectedMedia.selectedFile")}),i.jsx("span",{className:"text-xs text-gray-500",children:o(e?.size||0)})]})]}),i.jsx(se,{size:"icon",variant:"ghost",className:"ml-auto h-10 w-10 rounded-full",onClick:r,children:i.jsx(qb,{className:"h-6 w-6"})})]})},XE=e=>{const t=new Date,n=new Date(t);n.setDate(n.getDate()-1);const r=new Date(e);return r.toDateString()===t.toDateString()?"Hoje":r.toDateString()===n.toDateString()?"Ontem":Math.floor((t.getTime()-r.getTime())/(1e3*60*60*24))<7?r.toLocaleDateString("pt-BR",{weekday:"long"}):r.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})},Yv=e=>{try{if(!e.messageTimestamp)return new Date;if(typeof e.messageTimestamp=="object"){const n=[e.messageTimestamp.low,e.messageTimestamp.seconds,e.messageTimestamp.timestamp,e.messageTimestamp.time,e.messageTimestamp.value].find(r=>typeof r=="number"&&!isNaN(r))||Date.now()/1e3;return new Date(n*1e3)}else if(isNaN(Number(e.messageTimestamp))){if(typeof e.messageTimestamp=="string"&&e.messageTimestamp.includes("T"))return new Date(e.messageTimestamp)}else{const t=Number(e.messageTimestamp);return t>1e12?new Date(t):new Date(t*1e3)}return new Date}catch{return new Date}},cX=({date:e})=>i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx("div",{className:"rounded-full bg-muted px-3 py-1",children:i.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:e})})}),uX=e=>{if(!e)return"";if(typeof e=="string")try{const t=JSON.parse(e);return t.conversation||t.text||e}catch{return e}return typeof e=="object"?e.conversation||e.text||"":String(e)},ek=({message:e})=>{const t=e.messageType;switch(t){case"conversation":if(e.message.contactMessage){const d=e.message.contactMessage;return i.jsxs("div",{className:"p-3 bg-muted rounded-lg max-w-xs",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("div",{className:"text-xl",children:"👤"}),i.jsx("span",{className:"font-medium",children:"Contact"})]}),d.displayName&&i.jsx("p",{className:"text-sm font-medium",children:d.displayName}),d.vcard&&i.jsx("p",{className:"text-xs text-muted-foreground",children:"Contact card"})]})}if(e.message.locationMessage){const d=e.message.locationMessage;return i.jsxs("div",{className:"p-3 bg-muted rounded-lg max-w-xs",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("div",{className:"text-xl",children:"📍"}),i.jsx("span",{className:"font-medium",children:"Location"})]}),d.name&&i.jsx("p",{className:"text-sm font-medium",children:d.name}),d.address&&i.jsx("p",{className:"text-xs text-muted-foreground",children:d.address}),d.degreesLatitude&&d.degreesLongitude&&i.jsx("a",{href:`https://maps.google.com/?q=${d.degreesLatitude},${d.degreesLongitude}`,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm mt-1 inline-block",children:"View on Maps"})]})}return i.jsx("span",{children:uX(e.message)});case"extendedTextMessage":return i.jsx("span",{children:e.message.conversation??e.message.extendedTextMessage?.text});case"imageMessage":const r=(e.message.base64?e.message.base64.startsWith("data:")?e.message.base64:`data:image/jpeg;base64,${e.message.base64}`:null)||e.message.mediaUrl;return i.jsxs("div",{className:"flex flex-col gap-2",children:[r?i.jsx("img",{src:r,alt:"Image",className:"rounded-lg max-w-full h-auto",style:{maxWidth:"400px",maxHeight:"400px",objectFit:"contain"},loading:"lazy"}):i.jsxs("div",{className:"rounded bg-muted p-4 max-w-xs",children:[i.jsx("p",{className:"text-center text-muted-foreground",children:"Image couldn't be loaded"}),i.jsx("p",{className:"text-center text-xs text-muted-foreground mt-1",children:"Missing base64 data and mediaUrl"})]}),e.message.imageMessage?.caption&&i.jsx("p",{className:"text-sm",children:e.message.imageMessage.caption})]});case"videoMessage":const o=(e.message.base64?e.message.base64.startsWith("data:")?e.message.base64:`data:video/mp4;base64,${e.message.base64}`:null)||e.message.mediaUrl;return i.jsxs("div",{className:"flex flex-col gap-2",children:[o?i.jsx("video",{src:o,controls:!0,className:"rounded-lg max-w-full h-auto",style:{maxWidth:"400px",maxHeight:"400px"}}):i.jsxs("div",{className:"rounded bg-muted p-4 max-w-xs",children:[i.jsx("p",{className:"text-center text-muted-foreground",children:"Video couldn't be loaded"}),i.jsx("p",{className:"text-center text-xs text-muted-foreground mt-1",children:"Missing base64 data and mediaUrl"})]}),e.message.videoMessage?.caption&&i.jsx("p",{className:"text-sm",children:e.message.videoMessage.caption})]});case"audioMessage":const u=(e.message.base64?e.message.base64.startsWith("data:")?e.message.base64:`data:audio/mpeg;base64,${e.message.base64}`:null)||e.message.mediaUrl;return u?i.jsxs("audio",{controls:!0,className:"w-full max-w-xs",children:[i.jsx("source",{src:u,type:"audio/mpeg"}),"Your browser does not support the audio element."]}):i.jsxs("div",{className:"rounded bg-muted p-4 max-w-xs",children:[i.jsx("p",{className:"text-center text-muted-foreground",children:"Audio couldn't be loaded"}),i.jsx("p",{className:"text-center text-xs text-muted-foreground mt-1",children:"Missing base64 data and mediaUrl"})]});case"documentMessage":return i.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg max-w-xs",children:[i.jsx("div",{className:"text-2xl",children:"📄"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"font-medium truncate",children:e.message.documentMessage?.fileName||"Document"}),e.message.documentMessage?.fileLength&&i.jsxs("p",{className:"text-xs text-muted-foreground",children:[(e.message.documentMessage.fileLength/1024/1024).toFixed(2)," MB"]})]})]});case"stickerMessage":return i.jsx("img",{src:e.message.mediaUrl,alt:"Sticker",className:"max-w-32 max-h-32 object-contain"});default:return i.jsx("div",{className:"text-xs text-muted-foreground bg-muted p-2 rounded max-w-xs",children:i.jsxs("details",{children:[i.jsxs("summary",{children:["Unknown message type: ",t]}),i.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-all text-xs",children:JSON.stringify(e.message,null,2)})]})})}};function ZO({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=ct(),[l,u]=y.useState(""),[d,f]=y.useState(!1),[h,m]=y.useState(null),[g,x]=y.useState([]),{sendText:b}=KO(),{sendMedia:w}=WO(),{remoteJid:C}=ls(),k=async()=>{if(!(!l.trim()||!C||!o?.name||!o?.token||d))try{f(!0),await b({instanceName:o.name,token:o.token,data:{number:C,text:l.trim()}}),u(""),e.current&&(e.current.value="",t())}catch(G){console.error("Error sending message:",G)}finally{f(!1)}},j=async()=>{if(!(!h||!C||!o?.name||!o?.token||d))try{f(!0);const G=await new Promise((W,ie)=>{const re=new FileReader;re.readAsDataURL(h),re.onload=()=>{const H=re.result.split(",")[1];W(H)},re.onerror=ie});await w({instanceName:o.name,token:o.token,data:{number:C,mediaMessage:{mediatype:h.type.split("/")[0]==="application"?"document":h.type.split("/")[0],mimetype:h.type,caption:l.trim(),media:G,fileName:h.name}}}),m(null),u(""),e.current&&(e.current.value="",t())}catch(G){console.error("Error sending media:",G)}finally{f(!1)}},M=async()=>{h?await j():await k()},_=G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),M())},R=G=>{u(G.target.value),t()},{data:N}=eX({remoteJid:C,instanceName:o?.name}),{data:O,isSuccess:D}=rX({remoteJid:C,instanceName:o?.name}),z=y.useMemo(()=>{if(!O)return g;const G=new Map;return O.forEach(W=>G.set(W.key.id,W)),g.forEach(W=>{G.set(W.key.id,W)}),Array.from(G.values())},[O,g]);y.useEffect(()=>{if(!o?.name||!C)return;const G=dr(jn.API_URL);if(!G){console.error("API URL not found in localStorage");return}const W=sw(G),ie=(Y,H)=>{if(!o||H.instance!==o.name||H?.data?.key?.remoteJid!==C)return;const q=H.data;x(he=>{const A=he.findIndex(F=>F.key.id===q.key.id);if(A!==-1){const F=[...he];return F[A]=q,F}else return[...he,q]})},re=Y=>{o&&Y.instance===o.name&&console.log("Received message status update:",Y)};return W.on("messages.upsert",Y=>{ie("messages.upsert",Y)}),W.on("send.message",Y=>{ie("send.message",Y)}),W.on("messages.update",Y=>{re(Y)}),W.connect(),()=>{W.off("messages.upsert"),W.off("send.message"),W.off("messages.update"),ow(W)}},[o?.name,C]);const Q=y.useMemo(()=>{if(!z)return[];const G=[...z].sort((Y,H)=>{const q=Yv(Y).getTime(),he=Yv(H).getTime();return q-he}),W=[];let ie="",re=[];return G.forEach(Y=>{const q=Yv(Y).toDateString();q!==ie?(re.length>0&&W.push({date:XE(new Date(ie)),messages:re}),ie=q,re=[Y]):re.push(Y)}),re.length>0&&W.push({date:XE(new Date(ie)),messages:re}),W},[z]);y.useEffect(()=>{D&&z&&s()},[D,z,s]),y.useEffect(()=>{m(null),u(""),x([]),e.current&&(e.current.value="",t())},[C]);const pe=G=>i.jsx("div",{className:"bubble-right",children:i.jsx("div",{className:"flex items-start gap-4 self-end",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"bubble",children:i.jsx(ek,{message:G})})})})},G.id),V=G=>i.jsx("div",{className:"bubble-left",children:i.jsx("div",{className:"flex items-start gap-4",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"bubble",children:i.jsx(ek,{message:G})})})})},G.id);return i.jsxs("div",{className:"flex h-full flex-col",children:[i.jsx("div",{className:"sticky top-0 bg-background border-b border-border p-3",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(Ei,{className:"h-10 w-10",children:[i.jsx(ki,{src:N?.profilePicUrl,alt:N?.pushName||N?.remoteJid?.split("@")[0]}),i.jsx(Up,{className:"bg-slate-700 text-slate-300 border border-slate-600",children:i.jsx(Ap,{className:"h-5 w-5"})})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium text-sm truncate",children:N?.pushName||N?.remoteJid?.split("@")[0]}),i.jsx("div",{className:"text-xs text-muted-foreground truncate",children:N?.remoteJid?.split("@")[0]})]}),i.jsxs(dx,{children:[i.jsx(fx,{asChild:!0,children:i.jsx(se,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:i.jsx(Nh,{className:"h-4 w-4"})})}),i.jsxs(hr,{align:"start",className:"max-w-[300px]",children:[i.jsxs(wt,{className:"items-start gap-2",children:[i.jsx(wB,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-4"}),i.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),i.jsx(Xs,{}),i.jsxs(wt,{className:"items-start gap-2",children:[i.jsx(mT,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-3"}),i.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})]})}),i.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-2 overflow-y-auto px-2",children:[Q.map((G,W)=>i.jsxs("div",{children:[i.jsx(cX,{date:G.date}),i.jsx("div",{className:"flex flex-col gap-2",children:G.messages.map(ie=>ie.key.fromMe?pe(ie):V(ie))})]},W)),i.jsx("div",{ref:r})]}),i.jsxs("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-2 py-2",children:[h&&i.jsx(QO,{selectedMedia:h,setSelectedMedia:m}),i.jsxs("div",{className:"flex items-center rounded-3xl border border-border bg-background px-2 py-1",children:[o&&i.jsx(JO,{instance:o,setSelectedMedia:m}),i.jsx(bi,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,value:l,onChange:R,onKeyDown:_,disabled:d,style:{height:n},className:"min-h-0 w-full resize-none border-none p-3 focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 focus-visible:ring-offset-transparent"}),i.jsxs(se,{type:"button",size:"icon",onClick:M,disabled:!l.trim()&&!h||d,className:"rounded-full p-2 disabled:opacity-50",children:[i.jsx(Th,{className:"h-6 w-6"}),i.jsx("span",{className:"sr-only",children:"Enviar"})]})]})]})]})}const dX=e=>e.split("@")[0];function tk(){const e=zo("(min-width: 768px)"),t=y.useRef(null),[n]=y.useState("auto"),r=y.useRef(null),{instance:s}=ct(),[o,l]=y.useState([]),{data:u,isSuccess:d}=sY({instanceName:s?.name}),f=qe.useMemo(()=>{if(!u)return o;const C=new Map;return u.forEach(k=>C.set(k.remoteJid,k)),o.forEach(k=>{const j=C.get(k.remoteJid);j?C.set(k.remoteJid,{...j,...k}):C.set(k.remoteJid,k)}),Array.from(C.values())},[u,o]),{instanceId:h,remoteJid:m}=ls(),g=dn();y.useEffect(()=>{if(!s?.name)return;const C=dr(jn.API_URL);if(!C){console.error("API URL not found in localStorage");return}const k=sw(C),j=(M,_)=>{if(!s||_.instance!==s.name)return;const R=_?.data?.key?.remoteJid;R&&l(N=>{const O=N.findIndex(z=>z.remoteJid===R),D={id:R,remoteJid:R,pushName:_?.data?.pushName||dX(R),profilePicUrl:_?.data?.key?.profilePictureUrl||"",..._?.data};if(O!==-1){const z=[...N];return z[O]={...z[O],...D},z}else return[...N,D]})};return k.on("messages.upsert",M=>{j("messages.upsert",M)}),k.on("send.message",M=>{j("send.message",M)}),k.connect(),()=>{k.off("messages.upsert"),k.off("send.message"),ow(k)}},[s?.name]);const x=y.useCallback(()=>{t.current&&t.current.scrollIntoView({})},[]),b=()=>{if(r.current){r.current.style.height="auto";const C=r.current.scrollHeight,j=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(C,j)}px`}};y.useEffect(()=>{d&&x()},[d,x]);const w=C=>{g(`/manager/instance/${h}/chat/${C}`)};return i.jsx("div",{className:"h-[calc(100vh-160px)] overflow-hidden",children:i.jsxs($o,{direction:e?"horizontal":"vertical",className:"h-full",children:[i.jsx(Hn,{defaultSize:20,children:i.jsxs("div",{className:"hidden h-full flex-col bg-background text-foreground md:flex",children:[i.jsx("div",{className:"flex-shrink-0 p-2",children:i.jsxs(se,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[i.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:i.jsx(Bl,{className:"h-4 w-4"})}),i.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),i.jsx(cs,{className:"h-4 w-4"})]})}),i.jsxs(Yx,{defaultValue:"contacts",className:"flex flex-col flex-1 min-h-0",children:[i.jsxs(hg,{className:"tabs-chat flex-shrink-0",children:[i.jsx(Jl,{value:"contacts",children:"Contatos"}),i.jsx(Jl,{value:"groups",children:"Grupos"})]}),i.jsx(Ql,{value:"contacts",className:"flex-1 overflow-hidden",children:i.jsx("div",{className:"h-full overflow-auto",children:i.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[i.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),u?.map(C=>C.remoteJid.includes("@s.whatsapp.net")&&i.jsxs(Fu,{to:"#",onClick:()=>w(C.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${m===C.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsxs(Ei,{className:"h-8 w-8",children:[i.jsx(ki,{src:C.profilePicUrl,alt:C.pushName||C.remoteJid.split("@")[0]}),i.jsx(Up,{className:"bg-slate-700 text-slate-300 border border-slate-600",children:i.jsx(Ap,{className:"h-5 w-5"})})]})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:C.pushName||C.remoteJid.split("@")[0]}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:C.remoteJid.split("@")[0]})]})]},C.id))]})})}),i.jsx(Ql,{value:"groups",className:"flex-1 overflow-hidden",children:i.jsx("div",{className:"h-full overflow-auto",children:i.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:f?.map(C=>C.remoteJid.includes("@g.us")&&i.jsxs(Fu,{to:"#",onClick:()=>w(C.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${m===C.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsxs(Ei,{className:"h-8 w-8",children:[i.jsx(ki,{src:C.profilePicUrl,alt:C.pushName||C.remoteJid.split("@")[0]}),i.jsx(Up,{className:"bg-slate-700 text-slate-300 border border-slate-600",children:i.jsx(Ap,{className:"h-5 w-5"})})]})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:C.pushName||C.remoteJid.split("@")[0]}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:C.remoteJid})]})]},C.id))})})})]})]})}),i.jsx(Bo,{withHandle:!0,className:"border border-black"}),i.jsx(Hn,{children:m&&i.jsx(ZO,{textareaRef:r,handleTextareaChange:b,textareaHeight:n,lastMessageRef:t,scrollToBottom:x})})]})})}const fX=e=>["chatwoot","fetchChatwoot",JSON.stringify(e)],pX=async({instanceName:e,token:t})=>(await Ee.get(`/chatwoot/find/${e}`,{headers:{apiKey:t}})).data,hX=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:fX({instanceName:t,token:n}),queryFn:()=>pX({instanceName:t,token:n}),enabled:!!t})},gX=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data;function mX(){return{createChatwoot:nt(gX,{invalidateKeys:[["chatwoot","fetchChatwoot"]]})}}const rp=P.string().optional().transform(e=>e===""?void 0:e),vX=P.object({enabled:P.boolean(),accountId:P.string(),token:P.string(),url:P.string(),signMsg:P.boolean().optional(),signDelimiter:rp,nameInbox:rp,organization:rp,logo:rp,reopenConversation:P.boolean().optional(),conversationPending:P.boolean().optional(),mergeBrazilContacts:P.boolean().optional(),importContacts:P.boolean().optional(),importMessages:P.boolean().optional(),daysLimitImportMessages:P.coerce.number().optional(),autoCreate:P.boolean(),ignoreJids:P.array(P.string()).default([])});function yX(){const{t:e}=Ve(),{instance:t}=ct(),[,n]=y.useState(!1),{createChatwoot:r}=mX(),{data:s}=hX({instanceName:t?.name,token:t?.token}),o=on({resolver:an(vX),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});y.useEffect(()=>{if(s){o.setValue("ignoreJids",s.ignoreJids||[]);const u={enabled:s.enabled,accountId:s.accountId,token:s.token,url:s.url,signMsg:s.signMsg||!1,signDelimiter:s.signDelimiter||"\\n",nameInbox:s.nameInbox||"",organization:s.organization||"",logo:s.logo||"",reopenConversation:s.reopenConversation||!1,conversationPending:s.conversationPending||!1,mergeBrazilContacts:s.mergeBrazilContacts||!1,importContacts:s.importContacts||!1,importMessages:s.importMessages||!1,daysLimitImportMessages:s.daysLimitImportMessages||7,autoCreate:s.autoCreate||!1,ignoreJids:s.ignoreJids};o.reset(u)}},[s,o]);const l=async u=>{if(!t)return;n(!0);const d={enabled:u.enabled,accountId:u.accountId,token:u.token,url:u.url,signMsg:u.signMsg||!1,signDelimiter:u.signDelimiter||"\\n",nameInbox:u.nameInbox||"",organization:u.organization||"",logo:u.logo||"",reopenConversation:u.reopenConversation||!1,conversationPending:u.conversationPending||!1,mergeBrazilContacts:u.mergeBrazilContacts||!1,importContacts:u.importContacts||!1,importMessages:u.importMessages||!1,daysLimitImportMessages:u.daysLimitImportMessages||7,autoCreate:u.autoCreate,ignoreJids:u.ignoreJids};await r({instanceName:t.name,token:t.token,data:d},{onSuccess:()=>{me.success(e("chatwoot.toast.success"))},onError:f=>{console.error(e("chatwoot.toast.error"),f),rT(f)?me.error(`Error: ${f?.response?.data?.response?.message}`):me.error(e("chatwoot.toast.error"))},onSettled:()=>{n(!1)}})};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...o,children:i.jsxs("form",{onSubmit:o.handleSubmit(l),className:"w-full space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[i.jsx(Pe,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),i.jsx(le,{name:"url",label:e("chatwoot.form.url.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"token",label:e("chatwoot.form.token.label"),children:i.jsx(ne,{type:"password"})}),i.jsx(Pe,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),i.jsx(le,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"organization",label:e("chatwoot.form.organization.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"logo",label:e("chatwoot.form.logo.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),i.jsx(Pe,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),i.jsx(Pe,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),i.jsx(Pe,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),i.jsx(le,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),i.jsx(Pe,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),i.jsx("div",{className:"mx-4 flex justify-end",children:i.jsx(se,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var wl={},Xv={exports:{}},ey,nk;function bX(){if(nk)return ey;nk=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return ey=e,ey}var ty,rk;function xX(){if(rk)return ty;rk=1;var e=bX();function t(){}function n(){}return n.resetWarningCache=t,ty=function(){function r(l,u,d,f,h,m){if(m!==e){var g=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw g.name="Invariant Violation",g}}r.isRequired=r;function s(){return r}var o={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:s,element:r,elementType:r,instanceOf:s,node:r,objectOf:s,oneOf:s,oneOfType:s,shape:s,exact:s,checkPropTypes:n,resetWarningCache:t};return o.PropTypes=o,o},ty}var sk;function YO(){return sk||(sk=1,Xv.exports=xX()()),Xv.exports}var ny,ok;function XO(){return ok||(ok=1,ny={L:1,M:0,Q:3,H:2}),ny}var ry,ak;function eI(){return ak||(ak=1,ry={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}),ry}var sy,ik;function wX(){if(ik)return sy;ik=1;var e=eI();function t(n){this.mode=e.MODE_8BIT_BYTE,this.data=n}return t.prototype={getLength:function(n){return this.data.length},write:function(n){for(var r=0;r>>7-t%8&1)==1},put:function(t,n){for(var r=0;r>>n-r-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(t){var n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},ay=e,ay}var iy,uk;function tI(){if(uk)return iy;uk=1;for(var e={glog:function(n){if(n<1)throw new Error("glog("+n+")");return e.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return e.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)},t=0;t<8;t++)e.EXP_TABLE[t]=1<=0;)l^=s.G15<=0;)l^=s.G18<>>=1;return l},getPatternPosition:function(o){return s.PATTERN_POSITION_TABLE[o-1]},getMask:function(o,l,u){switch(o){case r.PATTERN000:return(l+u)%2==0;case r.PATTERN001:return l%2==0;case r.PATTERN010:return u%3==0;case r.PATTERN011:return(l+u)%3==0;case r.PATTERN100:return(Math.floor(l/2)+Math.floor(u/3))%2==0;case r.PATTERN101:return l*u%2+l*u%3==0;case r.PATTERN110:return(l*u%2+l*u%3)%2==0;case r.PATTERN111:return(l*u%3+(l+u)%2)%2==0;default:throw new Error("bad maskPattern:"+o)}},getErrorCorrectPolynomial:function(o){for(var l=new t([1],0),u=0;u5&&(u+=3+h-5)}for(var d=0;d=7&&this.setupTypeNumber(u),this.dataCache==null&&(this.dataCache=o.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,d)},l.setupPositionProbePattern=function(u,d){for(var f=-1;f<=7;f++)if(!(u+f<=-1||this.moduleCount<=u+f))for(var h=-1;h<=7;h++)d+h<=-1||this.moduleCount<=d+h||(0<=f&&f<=6&&(h==0||h==6)||0<=h&&h<=6&&(f==0||f==6)||2<=f&&f<=4&&2<=h&&h<=4?this.modules[u+f][d+h]=!0:this.modules[u+f][d+h]=!1)},l.getBestMaskPattern=function(){for(var u=0,d=0,f=0;f<8;f++){this.makeImpl(!0,f);var h=r.getLostPoint(this);(f==0||u>h)&&(u=h,d=f)}return d},l.createMovieClip=function(u,d,f){var h=u.createEmptyMovieClip(d,f),m=1;this.make();for(var g=0;g>f&1)==1;this.modules[Math.floor(f/3)][f%3+this.moduleCount-8-3]=h}for(var f=0;f<18;f++){var h=!u&&(d>>f&1)==1;this.modules[f%3+this.moduleCount-8-3][Math.floor(f/3)]=h}},l.setupTypeInfo=function(u,d){for(var f=this.errorCorrectLevel<<3|d,h=r.getBCHTypeInfo(f),m=0;m<15;m++){var g=!u&&(h>>m&1)==1;m<6?this.modules[m][8]=g:m<8?this.modules[m+1][8]=g:this.modules[this.moduleCount-15+m][8]=g}for(var m=0;m<15;m++){var g=!u&&(h>>m&1)==1;m<8?this.modules[8][this.moduleCount-m-1]=g:m<9?this.modules[8][15-m-1+1]=g:this.modules[8][15-m-1]=g}this.modules[this.moduleCount-8][8]=!u},l.mapData=function(u,d){for(var f=-1,h=this.moduleCount-1,m=7,g=0,x=this.moduleCount-1;x>0;x-=2)for(x==6&&x--;;){for(var b=0;b<2;b++)if(this.modules[h][x-b]==null){var w=!1;g>>m&1)==1);var C=r.getMask(d,h,x-b);C&&(w=!w),this.modules[h][x-b]=w,m--,m==-1&&(g++,m=7)}if(h+=f,h<0||this.moduleCount<=h){h-=f,f=-f;break}}},o.PAD0=236,o.PAD1=17,o.createData=function(u,d,f){for(var h=t.getRSBlocks(u,d),m=new n,g=0;gb*8)throw new Error("code length overflow. ("+m.getLengthInBits()+">"+b*8+")");for(m.getLengthInBits()+4<=b*8&&m.put(0,4);m.getLengthInBits()%8!=0;)m.putBit(!1);for(;!(m.getLengthInBits()>=b*8||(m.put(o.PAD0,8),m.getLengthInBits()>=b*8));)m.put(o.PAD1,8);return o.createBytes(m,h)},o.createBytes=function(u,d){for(var f=0,h=0,m=0,g=new Array(d.length),x=new Array(d.length),b=0;b=0?_.get(R):0}}for(var N=0,k=0;k=0||Object.prototype.hasOwnProperty.call(f,g)&&(m[g]=f[g]);return m}var u={bgColor:n.default.oneOfType([n.default.object,n.default.string]).isRequired,bgD:n.default.string.isRequired,fgColor:n.default.oneOfType([n.default.object,n.default.string]).isRequired,fgD:n.default.string.isRequired,size:n.default.number.isRequired,title:n.default.string,viewBoxSize:n.default.number.isRequired,xmlns:n.default.string},d=(0,r.forwardRef)(function(f,h){var m=f.bgColor,g=f.bgD,x=f.fgD,b=f.fgColor,w=f.size,C=f.title,k=f.viewBoxSize,j=f.xmlns,M=j===void 0?"http://www.w3.org/2000/svg":j,_=l(f,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return s.default.createElement("svg",e({},_,{height:w,ref:h,viewBox:"0 0 "+k+" "+k,width:w,xmlns:M}),C?s.default.createElement("title",null,C):null,s.default.createElement("path",{d:g,fill:m}),s.default.createElement("path",{d:x,fill:b}))});return d.displayName="QRCodeSvg",d.propTypes=u,sp.default=d,sp}var gk;function TX(){if(gk)return wl;gk=1,Object.defineProperty(wl,"__esModule",{value:!0}),wl.QRCode=void 0;var e=Object.assign||function(w){for(var C=1;C=0||Object.prototype.hasOwnProperty.call(w,j)&&(k[j]=w[j]);return k}var x={bgColor:n.default.oneOfType([n.default.object,n.default.string]),fgColor:n.default.oneOfType([n.default.object,n.default.string]),level:n.default.string,size:n.default.number,value:n.default.string.isRequired},b=(0,u.forwardRef)(function(w,C){var k=w.bgColor,j=k===void 0?"#FFFFFF":k,M=w.fgColor,_=M===void 0?"#000000":M,R=w.level,N=R===void 0?"L":R,O=w.size,D=O===void 0?256:O,z=w.value,Q=g(w,["bgColor","fgColor","level","size","value"]),pe=new l.default(-1,s.default[N]);pe.addData(z),pe.make();var V=pe.modules;return d.default.createElement(h.default,e({},Q,{bgColor:j,bgD:V.map(function(G,W){return G.map(function(ie,re){return ie?"":"M "+re+" "+W+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:_,fgD:V.map(function(G,W){return G.map(function(ie,re){return ie?"M "+re+" "+W+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:C,size:D,viewBoxSize:V.length}))});return wl.QRCode=b,b.displayName="QRCode",b.propTypes=x,wl.default=b,wl}var NX=TX();const MX=fd(NX),_X=jh("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),rI=y.forwardRef(({className:e,variant:t,...n},r)=>i.jsx("div",{ref:r,role:"alert",className:Ie(_X({variant:t}),e),...n}));rI.displayName="Alert";const sI=y.forwardRef(({className:e,...t},n)=>i.jsx("h5",{ref:n,className:Ie("font-medium leading-none tracking-tight",e),...t}));sI.displayName="AlertTitle";const RX=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:Ie("text-sm [&_p]:leading-relaxed",e),...t}));RX.displayName="AlertDescription";const On=({size:e=45,className:t,...n})=>i.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:Ie("animate-spin",t),children:i.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})});function PX(){const{t:e,i18n:t}=Ve(),n=new Intl.NumberFormat(t.language),[r,s]=y.useState(null),[o,l]=y.useState(""),u=dr(jn.TOKEN),{theme:d}=tc(),{connect:f,logout:h,restart:m}=Hh(),{instance:g,reloadInstance:x}=ct();y.useEffect(()=>{g&&(localStorage.setItem(jn.INSTANCE_ID,g.id),localStorage.setItem(jn.INSTANCE_NAME,g.name),localStorage.setItem(jn.INSTANCE_TOKEN,g.token))},[g]);const b=async()=>{await x()},w=async R=>{try{await m(R),await x()}catch(N){console.error("Error:",N)}},C=async R=>{try{await h(R),await x()}catch(N){console.error("Error:",N)}},k=async(R,N)=>{try{if(s(null),!u){console.error("Token not found.");return}if(N){const O=await f({instanceName:R,token:u,number:g?.number});l(O.pairingCode)}else{const O=await f({instanceName:R,token:u});s(O.code)}}catch(O){console.error("Error:",O)}},j=async()=>{s(null),l(""),await x()},M=y.useMemo(()=>g?{contacts:g._count?.Contact||0,chats:g._count?.Chat||0,messages:g._count?.Message||0}:{contacts:0,chats:0,messages:0},[g]),_=y.useMemo(()=>d==="dark"?"#fff":d==="light"?"#000":"#189d68",[d]);return g?i.jsxs("main",{className:"flex flex-col gap-8",children:[i.jsx("section",{children:i.jsxs(So,{children:[i.jsx(Co,{children:i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsx("h2",{className:"break-all text-lg font-semibold",children:g.name}),i.jsx(l_,{status:g.connectionStatus})]})}),i.jsxs(Eo,{className:"flex flex-col items-start space-y-6",children:[i.jsx("div",{className:"flex w-full flex-1",children:i.jsx(c_,{token:g.token})}),g.profileName&&i.jsxs("div",{className:"flex flex-1 gap-2",children:[i.jsx(Ei,{children:i.jsx(ki,{src:g.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:g.profileName}),i.jsx("p",{className:"break-all text-sm text-muted-foreground",children:g.ownerJid})]})]}),g.connectionStatus!=="open"&&i.jsxs(rI,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx(sI,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),i.jsxs(Pt,{children:[i.jsx(Bt,{onClick:()=>k(g.name,!1),asChild:!0,children:i.jsx(se,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),i.jsxs(Nt,{onCloseAutoFocus:j,children:[i.jsx(Mt,{children:e("instance.dashboard.button.qrcode.title")}),i.jsx("div",{className:"flex items-center justify-center",children:r&&i.jsx(MX,{value:r,size:256,bgColor:"transparent",fgColor:_,className:"rounded-sm"})})]})]}),g.number&&i.jsxs(Pt,{children:[i.jsx(Bt,{className:"connect-code-button",onClick:()=>k(g.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),i.jsx(Nt,{onCloseAutoFocus:j,children:i.jsx(Mt,{children:i.jsx(eo,{children:o?i.jsxs("div",{className:"py-3",children:[i.jsx("p",{className:"text-center",children:i.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),i.jsxs("p",{className:"pairing-code text-center",children:[o.substring(0,4),"-",o.substring(4,8)]})]}):i.jsx(On,{})})})})]})]})]}),i.jsxs(Vh,{className:"flex flex-wrap items-center justify-end gap-3",children:[i.jsx(se,{variant:"outline",className:"refresh-button",size:"icon",onClick:b,children:i.jsx(Ip,{size:"20"})}),i.jsx(se,{className:"action-button",variant:"secondary",onClick:()=>w(g.name),children:e("instance.dashboard.button.restart").toUpperCase()}),i.jsx(se,{variant:"destructive",onClick:()=>C(g.name),disabled:g.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),i.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[i.jsxs(So,{className:"instance-card",children:[i.jsx(Co,{children:i.jsxs(gi,{className:"flex items-center gap-2",children:[i.jsx(pT,{size:"20"}),e("instance.dashboard.contacts")]})}),i.jsx(Eo,{children:n.format(M.contacts)})]}),i.jsxs(So,{className:"instance-card",children:[i.jsx(Co,{children:i.jsxs(gi,{className:"flex items-center gap-2",children:[i.jsx(jB,{size:"20"}),e("instance.dashboard.chats")]})}),i.jsx(Eo,{children:n.format(M.chats)})]}),i.jsxs(So,{className:"instance-card",children:[i.jsx(Co,{children:i.jsxs(gi,{className:"flex items-center gap-2",children:[i.jsx(Bl,{size:"20"}),e("instance.dashboard.messages")]})}),i.jsx(Eo,{children:n.format(M.messages)})]})]})]}):i.jsx(On,{})}var OX="Separator",mk="horizontal",IX=["horizontal","vertical"],oI=y.forwardRef((e,t)=>{const{decorative:n,orientation:r=mk,...s}=e,o=AX(r)?r:mk,u=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return i.jsx(rt.div,{"data-orientation":o,...u,...s,ref:t})});oI.displayName=OX;function AX(e){return IX.includes(e)}var aI=oI;const $t=y.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>i.jsx(aI,{ref:s,decorative:n,orientation:t,className:Ie("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));$t.displayName=aI.displayName;const DX=e=>["dify","fetchDify",JSON.stringify(e)],FX=async({instanceName:e,token:t})=>(await Ee.get(`/dify/find/${e}`,{headers:{apikey:t}})).data,iI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:DX({instanceName:t,token:n}),queryFn:()=>FX({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},LX=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,$X=async({instanceName:e,difyId:t,data:n})=>(await Ee.put(`/dify/update/${t}/${e}`,n)).data,BX=async({instanceName:e,difyId:t})=>(await Ee.delete(`/dify/delete/${t}/${e}`)).data,zX=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,UX=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function vg(){const e=nt(zX,{invalidateKeys:[["dify","fetchDefaultSettings"]]}),t=nt(UX,{invalidateKeys:[["dify","getDify"],["dify","fetchSessions"]]}),n=nt(BX,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),r=nt($X,{invalidateKeys:[["dify","getDify"],["dify","fetchDify"],["dify","fetchSessions"]]}),s=nt(LX,{invalidateKeys:[["dify","fetchDify"]]});return{setDefaultSettingsDify:e,changeStatusDify:t,deleteDify:n,updateDify:r,createDify:s}}const VX=e=>["dify","fetchDefaultSettings",JSON.stringify(e)],HX=async({instanceName:e,token:t})=>(await Ee.get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,qX=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:VX({instanceName:t,token:n}),queryFn:()=>HX({instanceName:t,token:n}),enabled:!!t})},KX=P.object({expire:P.string(),keywordFinish:P.string(),delayMessage:P.string(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.string(),ignoreJids:P.array(P.string()).default([]),difyIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean(),timePerChar:P.string()});function WX(){const{t:e}=Ve(),{instance:t}=ct(),{setDefaultSettingsDify:n}=vg(),[r,s]=y.useState(!1),{data:o,refetch:l}=iI({instanceName:t?.name,token:t?.token,enabled:r}),{data:u,refetch:d}=qX({instanceName:t?.name,token:t?.token}),f=on({resolver:an(KX),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});y.useEffect(()=>{u&&f.reset({expire:u?.expire?u.expire.toString():"0",keywordFinish:u.keywordFinish,delayMessage:u.delayMessage?u.delayMessage.toString():"0",unknownMessage:u.unknownMessage,listeningFromMe:u.listeningFromMe,stopBotFromMe:u.stopBotFromMe,keepOpen:u.keepOpen,debounceTime:u.debounceTime?u.debounceTime.toString():"0",ignoreJids:u.ignoreJids,difyIdFallback:u.difyIdFallback,splitMessages:u.splitMessages,timePerChar:u.timePerChar?u.timePerChar.toString():"0"})},[u]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),difyIdFallback:g.difyIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:parseInt(g.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),me.success(e("dify.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){d(),l()}return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("dify.defaultSettings")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:o?.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id}))??[]}),i.jsx(le,{name:"expire",label:e("dify.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("dify.form.splitMessages.label"),reverse:!0}),i.jsx(le,{name:"timePerChar",label:e("dify.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("dify.button.save")})})]})})]})]})}/** + * table-core + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function ma(e,t){return typeof e=="function"?e(t):e}function qr(e,t){return n=>{t.setState(r=>({...r,[e]:ma(n,r[e])}))}}function yg(e){return e instanceof Function}function GX(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function lI(e,t){const n=[],r=s=>{s.forEach(o=>{n.push(o);const l=t(o);l!=null&&l.length&&r(l)})};return r(e),n}function ot(e,t,n){let r=[],s;return o=>{let l;n.key&&n.debug&&(l=Date.now());const u=e(o);if(!(u.length!==r.length||u.some((h,m)=>r[m]!==h)))return s;r=u;let f;if(n.key&&n.debug&&(f=Date.now()),s=t(...u),n==null||n.onChange==null||n.onChange(s),n.key&&n.debug&&n!=null&&n.debug()){const h=Math.round((Date.now()-l)*100)/100,m=Math.round((Date.now()-f)*100)/100,g=m/16,x=(b,w)=>{for(b=String(b);b.length{var s;return(s=e?.debugAll)!=null?s:e[t]},key:!1,onChange:r}}function JX(e,t,n,r){const s=()=>{var l;return(l=o.getValue())!=null?l:e.options.renderFallbackValue},o={id:`${t.id}_${n.id}`,row:t,column:n,getValue:()=>t.getValue(r),renderValue:s,getContext:ot(()=>[e,n,t,o],(l,u,d,f)=>({table:l,column:u,row:d,cell:f,getValue:f.getValue,renderValue:f.renderValue}),at(e.options,"debugCells"))};return e._features.forEach(l=>{l.createCell==null||l.createCell(o,n,t,e)},{}),o}function QX(e,t,n,r){var s,o;const u={...e._getDefaultColumnDef(),...t},d=u.accessorKey;let f=(s=(o=u.id)!=null?o:d?typeof String.prototype.replaceAll=="function"?d.replaceAll(".","_"):d.replace(/\./g,"_"):void 0)!=null?s:typeof u.header=="string"?u.header:void 0,h;if(u.accessorFn?h=u.accessorFn:d&&(d.includes(".")?h=g=>{let x=g;for(const w of d.split(".")){var b;x=(b=x)==null?void 0:b[w]}return x}:h=g=>g[u.accessorKey]),!f)throw new Error;let m={id:`${String(f)}`,accessorFn:h,parent:r,depth:n,columnDef:u,columns:[],getFlatColumns:ot(()=>[!0],()=>{var g;return[m,...(g=m.columns)==null?void 0:g.flatMap(x=>x.getFlatColumns())]},at(e.options,"debugColumns")),getLeafColumns:ot(()=>[e._getOrderColumnsFn()],g=>{var x;if((x=m.columns)!=null&&x.length){let b=m.columns.flatMap(w=>w.getLeafColumns());return g(b)}return[m]},at(e.options,"debugColumns"))};for(const g of e._features)g.createColumn==null||g.createColumn(m,e);return m}const nr="debugHeaders";function vk(e,t,n){var r;let o={id:(r=n.id)!=null?r:t.id,column:t,index:n.index,isPlaceholder:!!n.isPlaceholder,placeholderId:n.placeholderId,depth:n.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const l=[],u=d=>{d.subHeaders&&d.subHeaders.length&&d.subHeaders.map(u),l.push(d)};return u(o),l},getContext:()=>({table:e,header:o,column:t})};return e._features.forEach(l=>{l.createHeader==null||l.createHeader(o,e)}),o}const ZX={createTable:e=>{e.getHeaderGroups=ot(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>{var o,l;const u=(o=r?.map(m=>n.find(g=>g.id===m)).filter(Boolean))!=null?o:[],d=(l=s?.map(m=>n.find(g=>g.id===m)).filter(Boolean))!=null?l:[],f=n.filter(m=>!(r!=null&&r.includes(m.id))&&!(s!=null&&s.includes(m.id)));return op(t,[...u,...f,...d],e)},at(e.options,nr)),e.getCenterHeaderGroups=ot(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r,s)=>(n=n.filter(o=>!(r!=null&&r.includes(o.id))&&!(s!=null&&s.includes(o.id))),op(t,n,e,"center")),at(e.options,nr)),e.getLeftHeaderGroups=ot(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,n,r)=>{var s;const o=(s=r?.map(l=>n.find(u=>u.id===l)).filter(Boolean))!=null?s:[];return op(t,o,e,"left")},at(e.options,nr)),e.getRightHeaderGroups=ot(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,n,r)=>{var s;const o=(s=r?.map(l=>n.find(u=>u.id===l)).filter(Boolean))!=null?s:[];return op(t,o,e,"right")},at(e.options,nr)),e.getFooterGroups=ot(()=>[e.getHeaderGroups()],t=>[...t].reverse(),at(e.options,nr)),e.getLeftFooterGroups=ot(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),at(e.options,nr)),e.getCenterFooterGroups=ot(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),at(e.options,nr)),e.getRightFooterGroups=ot(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),at(e.options,nr)),e.getFlatHeaders=ot(()=>[e.getHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,nr)),e.getLeftFlatHeaders=ot(()=>[e.getLeftHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,nr)),e.getCenterFlatHeaders=ot(()=>[e.getCenterHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,nr)),e.getRightFlatHeaders=ot(()=>[e.getRightHeaderGroups()],t=>t.map(n=>n.headers).flat(),at(e.options,nr)),e.getCenterLeafHeaders=ot(()=>[e.getCenterFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,nr)),e.getLeftLeafHeaders=ot(()=>[e.getLeftFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,nr)),e.getRightLeafHeaders=ot(()=>[e.getRightFlatHeaders()],t=>t.filter(n=>{var r;return!((r=n.subHeaders)!=null&&r.length)}),at(e.options,nr)),e.getLeafHeaders=ot(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,n,r)=>{var s,o,l,u,d,f;return[...(s=(o=t[0])==null?void 0:o.headers)!=null?s:[],...(l=(u=n[0])==null?void 0:u.headers)!=null?l:[],...(d=(f=r[0])==null?void 0:f.headers)!=null?d:[]].map(h=>h.getLeafHeaders()).flat()},at(e.options,nr))}};function op(e,t,n,r){var s,o;let l=0;const u=function(g,x){x===void 0&&(x=1),l=Math.max(l,x),g.filter(b=>b.getIsVisible()).forEach(b=>{var w;(w=b.columns)!=null&&w.length&&u(b.columns,x+1)},0)};u(e);let d=[];const f=(g,x)=>{const b={depth:x,id:[r,`${x}`].filter(Boolean).join("_"),headers:[]},w=[];g.forEach(C=>{const k=[...w].reverse()[0],j=C.column.depth===b.depth;let M,_=!1;if(j&&C.column.parent?M=C.column.parent:(M=C.column,_=!0),k&&k?.column===M)k.subHeaders.push(C);else{const R=vk(n,M,{id:[r,x,M.id,C?.id].filter(Boolean).join("_"),isPlaceholder:_,placeholderId:_?`${w.filter(N=>N.column===M).length}`:void 0,depth:x,index:w.length});R.subHeaders.push(C),w.push(R)}b.headers.push(C),C.headerGroup=b}),d.push(b),x>0&&f(w,x-1)},h=t.map((g,x)=>vk(n,g,{depth:l,index:x}));f(h,l-1),d.reverse();const m=g=>g.filter(b=>b.column.getIsVisible()).map(b=>{let w=0,C=0,k=[0];b.subHeaders&&b.subHeaders.length?(k=[],m(b.subHeaders).forEach(M=>{let{colSpan:_,rowSpan:R}=M;w+=_,k.push(R)})):w=1;const j=Math.min(...k);return C=C+j,b.colSpan=w,b.rowSpan=C,{colSpan:w,rowSpan:C}});return m((s=(o=d[0])==null?void 0:o.headers)!=null?s:[]),d}const bg=(e,t,n,r,s,o,l)=>{let u={id:t,index:r,original:n,depth:s,parentId:l,_valuesCache:{},_uniqueValuesCache:{},getValue:d=>{if(u._valuesCache.hasOwnProperty(d))return u._valuesCache[d];const f=e.getColumn(d);if(f!=null&&f.accessorFn)return u._valuesCache[d]=f.accessorFn(u.original,r),u._valuesCache[d]},getUniqueValues:d=>{if(u._uniqueValuesCache.hasOwnProperty(d))return u._uniqueValuesCache[d];const f=e.getColumn(d);if(f!=null&&f.accessorFn)return f.columnDef.getUniqueValues?(u._uniqueValuesCache[d]=f.columnDef.getUniqueValues(u.original,r),u._uniqueValuesCache[d]):(u._uniqueValuesCache[d]=[u.getValue(d)],u._uniqueValuesCache[d])},renderValue:d=>{var f;return(f=u.getValue(d))!=null?f:e.options.renderFallbackValue},subRows:o??[],getLeafRows:()=>lI(u.subRows,d=>d.subRows),getParentRow:()=>u.parentId?e.getRow(u.parentId,!0):void 0,getParentRows:()=>{let d=[],f=u;for(;;){const h=f.getParentRow();if(!h)break;d.push(h),f=h}return d.reverse()},getAllCells:ot(()=>[e.getAllLeafColumns()],d=>d.map(f=>JX(e,u,f,f.id)),at(e.options,"debugRows")),_getAllCellsByColumnId:ot(()=>[u.getAllCells()],d=>d.reduce((f,h)=>(f[h.column.id]=h,f),{}),at(e.options,"debugRows"))};for(let d=0;d{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},cI=(e,t,n)=>{var r;const s=n.toLowerCase();return!!(!((r=e.getValue(t))==null||(r=r.toString())==null||(r=r.toLowerCase())==null)&&r.includes(s))};cI.autoRemove=e=>Ts(e);const uI=(e,t,n)=>{var r;return!!(!((r=e.getValue(t))==null||(r=r.toString())==null)&&r.includes(n))};uI.autoRemove=e=>Ts(e);const dI=(e,t,n)=>{var r;return((r=e.getValue(t))==null||(r=r.toString())==null?void 0:r.toLowerCase())===n?.toLowerCase()};dI.autoRemove=e=>Ts(e);const fI=(e,t,n)=>{var r;return(r=e.getValue(t))==null?void 0:r.includes(n)};fI.autoRemove=e=>Ts(e)||!(e!=null&&e.length);const pI=(e,t,n)=>!n.some(r=>{var s;return!((s=e.getValue(t))!=null&&s.includes(r))});pI.autoRemove=e=>Ts(e)||!(e!=null&&e.length);const hI=(e,t,n)=>n.some(r=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(r)});hI.autoRemove=e=>Ts(e)||!(e!=null&&e.length);const gI=(e,t,n)=>e.getValue(t)===n;gI.autoRemove=e=>Ts(e);const mI=(e,t,n)=>e.getValue(t)==n;mI.autoRemove=e=>Ts(e);const aw=(e,t,n)=>{let[r,s]=n;const o=e.getValue(t);return o>=r&&o<=s};aw.resolveFilterValue=e=>{let[t,n]=e,r=typeof t!="number"?parseFloat(t):t,s=typeof n!="number"?parseFloat(n):n,o=t===null||Number.isNaN(r)?-1/0:r,l=n===null||Number.isNaN(s)?1/0:s;if(o>l){const u=o;o=l,l=u}return[o,l]};aw.autoRemove=e=>Ts(e)||Ts(e[0])&&Ts(e[1]);const yo={includesString:cI,includesStringSensitive:uI,equalsString:dI,arrIncludes:fI,arrIncludesAll:pI,arrIncludesSome:hI,equals:gI,weakEquals:mI,inNumberRange:aw};function Ts(e){return e==null||e===""}const XX={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:qr("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);return typeof r=="string"?yo.includesString:typeof r=="number"?yo.inNumberRange:typeof r=="boolean"||r!==null&&typeof r=="object"?yo.equals:Array.isArray(r)?yo.arrIncludes:yo.weakEquals},e.getFilterFn=()=>{var n,r;return yg(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(n=(r=t.options.filterFns)==null?void 0:r[e.columnDef.filterFn])!=null?n:yo[e.columnDef.filterFn]},e.getCanFilter=()=>{var n,r,s;return((n=e.columnDef.enableColumnFilter)!=null?n:!0)&&((r=t.options.enableColumnFilters)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var n;return(n=t.getState().columnFilters)==null||(n=n.find(r=>r.id===e.id))==null?void 0:n.value},e.getFilterIndex=()=>{var n,r;return(n=(r=t.getState().columnFilters)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.setFilterValue=n=>{t.setColumnFilters(r=>{const s=e.getFilterFn(),o=r?.find(h=>h.id===e.id),l=ma(n,o?o.value:void 0);if(yk(s,l,e)){var u;return(u=r?.filter(h=>h.id!==e.id))!=null?u:[]}const d={id:e.id,value:l};if(o){var f;return(f=r?.map(h=>h.id===e.id?d:h))!=null?f:[]}return r!=null&&r.length?[...r,d]:[d]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const n=e.getAllLeafColumns(),r=s=>{var o;return(o=ma(t,s))==null?void 0:o.filter(l=>{const u=n.find(d=>d.id===l.id);if(u){const d=u.getFilterFn();if(yk(d,l.value,u))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(r)},e.resetColumnFilters=t=>{var n,r;e.setColumnFilters(t?[]:(n=(r=e.initialState)==null?void 0:r.columnFilters)!=null?n:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function yk(e,t,n){return(e&&e.autoRemove?e.autoRemove(t,n):!1)||typeof t>"u"||typeof t=="string"&&!t}const eee=(e,t,n)=>n.reduce((r,s)=>{const o=s.getValue(e);return r+(typeof o=="number"?o:0)},0),tee=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r>o||r===void 0&&o>=o)&&(r=o)}),r},nee=(e,t,n)=>{let r;return n.forEach(s=>{const o=s.getValue(e);o!=null&&(r=o)&&(r=o)}),r},ree=(e,t,n)=>{let r,s;return n.forEach(o=>{const l=o.getValue(e);l!=null&&(r===void 0?l>=l&&(r=s=l):(r>l&&(r=l),s{let n=0,r=0;if(t.forEach(s=>{let o=s.getValue(e);o!=null&&(o=+o)>=o&&(++n,r+=o)}),n)return r/n},oee=(e,t)=>{if(!t.length)return;const n=t.map(o=>o.getValue(e));if(!GX(n))return;if(n.length===1)return n[0];const r=Math.floor(n.length/2),s=n.sort((o,l)=>o-l);return n.length%2!==0?s[r]:(s[r-1]+s[r])/2},aee=(e,t)=>Array.from(new Set(t.map(n=>n.getValue(e))).values()),iee=(e,t)=>new Set(t.map(n=>n.getValue(e))).size,lee=(e,t)=>t.length,dy={sum:eee,min:tee,max:nee,extent:ree,mean:see,median:oee,unique:aee,uniqueCount:iee,count:lee},cee={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,n;return(t=(n=e.getValue())==null||n.toString==null?void 0:n.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:qr("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(n=>n!=null&&n.includes(e.id)?n.filter(r=>r!==e.id):[...n??[],e.id])},e.getCanGroup=()=>{var n,r;return((n=e.columnDef.enableGrouping)!=null?n:!0)&&((r=t.options.enableGrouping)!=null?r:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.includes(e.id)},e.getGroupedIndex=()=>{var n;return(n=t.getState().grouping)==null?void 0:n.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const n=e.getCanGroup();return()=>{n&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const n=t.getCoreRowModel().flatRows[0],r=n?.getValue(e.id);if(typeof r=="number")return dy.sum;if(Object.prototype.toString.call(r)==="[object Date]")return dy.extent},e.getAggregationFn=()=>{var n,r;if(!e)throw new Error;return yg(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(n=(r=t.options.aggregationFns)==null?void 0:r[e.columnDef.aggregationFn])!=null?n:dy[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var n,r;e.setGrouping(t?[]:(n=(r=e.initialState)==null?void 0:r.grouping)!=null?n:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=n=>{if(e._groupingValuesCache.hasOwnProperty(n))return e._groupingValuesCache[n];const r=t.getColumn(n);return r!=null&&r.columnDef.getGroupingValue?(e._groupingValuesCache[n]=r.columnDef.getGroupingValue(e.original),e._groupingValuesCache[n]):e.getValue(n)},e._groupingValuesCache={}},createCell:(e,t,n,r)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===n.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=n.subRows)!=null&&s.length)}}};function uee(e,t,n){if(!(t!=null&&t.length)||!n)return e;const r=e.filter(o=>!t.includes(o.id));return n==="remove"?r:[...t.map(o=>e.find(l=>l.id===o)).filter(Boolean),...r]}const dee={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:qr("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=ot(n=>[Ru(t,n)],n=>n.findIndex(r=>r.id===e.id),at(t.options,"debugColumns")),e.getIsFirstColumn=n=>{var r;return((r=Ru(t,n)[0])==null?void 0:r.id)===e.id},e.getIsLastColumn=n=>{var r;const s=Ru(t,n);return((r=s[s.length-1])==null?void 0:r.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var n;e.setColumnOrder(t?[]:(n=e.initialState.columnOrder)!=null?n:[])},e._getOrderColumnsFn=ot(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,n,r)=>s=>{let o=[];if(!(t!=null&&t.length))o=s;else{const l=[...t],u=[...s];for(;u.length&&l.length;){const d=l.shift(),f=u.findIndex(h=>h.id===d);f>-1&&o.push(u.splice(f,1)[0])}o=[...o,...u]}return uee(o,n,r)},at(e.options,"debugTable"))}},fy=()=>({left:[],right:[]}),fee={getInitialState:e=>({columnPinning:fy(),...e}),getDefaultOptions:e=>({onColumnPinningChange:qr("columnPinning",e)}),createColumn:(e,t)=>{e.pin=n=>{const r=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var o,l;if(n==="right"){var u,d;return{left:((u=s?.left)!=null?u:[]).filter(m=>!(r!=null&&r.includes(m))),right:[...((d=s?.right)!=null?d:[]).filter(m=>!(r!=null&&r.includes(m))),...r]}}if(n==="left"){var f,h;return{left:[...((f=s?.left)!=null?f:[]).filter(m=>!(r!=null&&r.includes(m))),...r],right:((h=s?.right)!=null?h:[]).filter(m=>!(r!=null&&r.includes(m)))}}return{left:((o=s?.left)!=null?o:[]).filter(m=>!(r!=null&&r.includes(m))),right:((l=s?.right)!=null?l:[]).filter(m=>!(r!=null&&r.includes(m)))}})},e.getCanPin=()=>e.getLeafColumns().some(r=>{var s,o,l;return((s=r.columnDef.enablePinning)!=null?s:!0)&&((o=(l=t.options.enableColumnPinning)!=null?l:t.options.enablePinning)!=null?o:!0)}),e.getIsPinned=()=>{const n=e.getLeafColumns().map(u=>u.id),{left:r,right:s}=t.getState().columnPinning,o=n.some(u=>r?.includes(u)),l=n.some(u=>s?.includes(u));return o?"left":l?"right":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();return s?(n=(r=t.getState().columnPinning)==null||(r=r[s])==null?void 0:r.indexOf(e.id))!=null?n:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=ot(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(n,r,s)=>{const o=[...r??[],...s??[]];return n.filter(l=>!o.includes(l.column.id))},at(t.options,"debugRows")),e.getLeftVisibleCells=ot(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(n,r)=>(r??[]).map(o=>n.find(l=>l.column.id===o)).filter(Boolean).map(o=>({...o,position:"left"})),at(t.options,"debugRows")),e.getRightVisibleCells=ot(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(n,r)=>(r??[]).map(o=>n.find(l=>l.column.id===o)).filter(Boolean).map(o=>({...o,position:"right"})),at(t.options,"debugRows"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var n,r;return e.setColumnPinning(t?fy():(n=(r=e.initialState)==null?void 0:r.columnPinning)!=null?n:fy())},e.getIsSomeColumnsPinned=t=>{var n;const r=e.getState().columnPinning;if(!t){var s,o;return!!((s=r.left)!=null&&s.length||(o=r.right)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e.getLeftLeafColumns=ot(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),at(e.options,"debugColumns")),e.getRightLeafColumns=ot(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,n)=>(n??[]).map(r=>t.find(s=>s.id===r)).filter(Boolean),at(e.options,"debugColumns")),e.getCenterLeafColumns=ot(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,n,r)=>{const s=[...n??[],...r??[]];return t.filter(o=>!s.includes(o.id))},at(e.options,"debugColumns"))}},ap={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},py=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),pee={getDefaultColumnDef:()=>ap,getInitialState:e=>({columnSizing:{},columnSizingInfo:py(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:qr("columnSizing",e),onColumnSizingInfoChange:qr("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var n,r,s;const o=t.getState().columnSizing[e.id];return Math.min(Math.max((n=e.columnDef.minSize)!=null?n:ap.minSize,(r=o??e.columnDef.size)!=null?r:ap.size),(s=e.columnDef.maxSize)!=null?s:ap.maxSize)},e.getStart=ot(n=>[n,Ru(t,n),t.getState().columnSizing],(n,r)=>r.slice(0,e.getIndex(n)).reduce((s,o)=>s+o.getSize(),0),at(t.options,"debugColumns")),e.getAfter=ot(n=>[n,Ru(t,n),t.getState().columnSizing],(n,r)=>r.slice(e.getIndex(n)+1).reduce((s,o)=>s+o.getSize(),0),at(t.options,"debugColumns")),e.resetSize=()=>{t.setColumnSizing(n=>{let{[e.id]:r,...s}=n;return s})},e.getCanResize=()=>{var n,r;return((n=e.columnDef.enableResizing)!=null?n:!0)&&((r=t.options.enableColumnResizing)!=null?r:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let n=0;const r=s=>{if(s.subHeaders.length)s.subHeaders.forEach(r);else{var o;n+=(o=s.column.getSize())!=null?o:0}};return r(e),n},e.getStart=()=>{if(e.index>0){const n=e.headerGroup.headers[e.index-1];return n.getStart()+n.getSize()}return 0},e.getResizeHandler=n=>{const r=t.getColumn(e.column.id),s=r?.getCanResize();return o=>{if(!r||!s||(o.persist==null||o.persist(),hy(o)&&o.touches&&o.touches.length>1))return;const l=e.getSize(),u=e?e.getLeafHeaders().map(k=>[k.column.id,k.column.getSize()]):[[r.id,r.getSize()]],d=hy(o)?Math.round(o.touches[0].clientX):o.clientX,f={},h=(k,j)=>{typeof j=="number"&&(t.setColumnSizingInfo(M=>{var _,R;const N=t.options.columnResizeDirection==="rtl"?-1:1,O=(j-((_=M?.startOffset)!=null?_:0))*N,D=Math.max(O/((R=M?.startSize)!=null?R:0),-.999999);return M.columnSizingStart.forEach(z=>{let[Q,pe]=z;f[Q]=Math.round(Math.max(pe+pe*D,0)*100)/100}),{...M,deltaOffset:O,deltaPercentage:D}}),(t.options.columnResizeMode==="onChange"||k==="end")&&t.setColumnSizing(M=>({...M,...f})))},m=k=>h("move",k),g=k=>{h("end",k),t.setColumnSizingInfo(j=>({...j,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},x=n||typeof document<"u"?document:null,b={moveHandler:k=>m(k.clientX),upHandler:k=>{x?.removeEventListener("mousemove",b.moveHandler),x?.removeEventListener("mouseup",b.upHandler),g(k.clientX)}},w={moveHandler:k=>(k.cancelable&&(k.preventDefault(),k.stopPropagation()),m(k.touches[0].clientX),!1),upHandler:k=>{var j;x?.removeEventListener("touchmove",w.moveHandler),x?.removeEventListener("touchend",w.upHandler),k.cancelable&&(k.preventDefault(),k.stopPropagation()),g((j=k.touches[0])==null?void 0:j.clientX)}},C=hee()?{passive:!1}:!1;hy(o)?(x?.addEventListener("touchmove",w.moveHandler,C),x?.addEventListener("touchend",w.upHandler,C)):(x?.addEventListener("mousemove",b.moveHandler,C),x?.addEventListener("mouseup",b.upHandler,C)),t.setColumnSizingInfo(k=>({...k,startOffset:d,startSize:l,deltaOffset:0,deltaPercentage:0,columnSizingStart:u,isResizingColumn:r.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var n;e.setColumnSizing(t?{}:(n=e.initialState.columnSizing)!=null?n:{})},e.resetHeaderSizeInfo=t=>{var n;e.setColumnSizingInfo(t?py():(n=e.initialState.columnSizingInfo)!=null?n:py())},e.getTotalSize=()=>{var t,n;return(t=(n=e.getHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,n;return(t=(n=e.getLeftHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,n;return(t=(n=e.getCenterHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,n;return(t=(n=e.getRightHeaderGroups()[0])==null?void 0:n.headers.reduce((r,s)=>r+s.getSize(),0))!=null?t:0}}};let ip=null;function hee(){if(typeof ip=="boolean")return ip;let e=!1;try{const t={get passive(){return e=!0,!1}},n=()=>{};window.addEventListener("test",n,t),window.removeEventListener("test",n)}catch{e=!1}return ip=e,ip}function hy(e){return e.type==="touchstart"}const gee={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:qr("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=n=>{e.getCanHide()&&t.setColumnVisibility(r=>({...r,[e.id]:n??!e.getIsVisible()}))},e.getIsVisible=()=>{var n,r;const s=e.columns;return(n=s.length?s.some(o=>o.getIsVisible()):(r=t.getState().columnVisibility)==null?void 0:r[e.id])!=null?n:!0},e.getCanHide=()=>{var n,r;return((n=e.columnDef.enableHiding)!=null?n:!0)&&((r=t.options.enableHiding)!=null?r:!0)},e.getToggleVisibilityHandler=()=>n=>{e.toggleVisibility==null||e.toggleVisibility(n.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=ot(()=>[e.getAllCells(),t.getState().columnVisibility],n=>n.filter(r=>r.column.getIsVisible()),at(t.options,"debugRows")),e.getVisibleCells=ot(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(n,r,s)=>[...n,...r,...s],at(t.options,"debugRows"))},createTable:e=>{const t=(n,r)=>ot(()=>[r(),r().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(o=>o.getIsVisible==null?void 0:o.getIsVisible()),at(e.options,"debugColumns"));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=n=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(n),e.resetColumnVisibility=n=>{var r;e.setColumnVisibility(n?{}:(r=e.initialState.columnVisibility)!=null?r:{})},e.toggleAllColumnsVisible=n=>{var r;n=(r=n)!=null?r:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,o)=>({...s,[o.id]:n||!(o.getCanHide!=null&&o.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(n=>!(n.getIsVisible!=null&&n.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(n=>n.getIsVisible==null?void 0:n.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>n=>{var r;e.toggleAllColumnsVisible((r=n.target)==null?void 0:r.checked)}}};function Ru(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const mee={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},vee={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:qr("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var n;const r=(n=e.getCoreRowModel().flatRows[0])==null||(n=n._getAllCellsByColumnId()[t.id])==null?void 0:n.getValue();return typeof r=="string"||typeof r=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var n,r,s,o;return((n=e.columnDef.enableGlobalFilter)!=null?n:!0)&&((r=t.options.enableGlobalFilter)!=null?r:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((o=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?o:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>yo.includesString,e.getGlobalFilterFn=()=>{var t,n;const{globalFilterFn:r}=e.options;return yg(r)?r:r==="auto"?e.getGlobalAutoFilterFn():(t=(n=e.options.filterFns)==null?void 0:n[r])!=null?t:yo[r]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},yee={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:qr("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,n=!1;e._autoResetExpanded=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?r:!e.options.manualExpanding){if(n)return;n=!0,e._queue(()=>{e.resetExpanded(),n=!1})}},e.setExpanded=r=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(r),e.toggleAllRowsExpanded=r=>{r??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=r=>{var s,o;e.setExpanded(r?{}:(s=(o=e.initialState)==null?void 0:o.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(r=>r.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>r=>{r.persist==null||r.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const r=e.getState().expanded;return r===!0||Object.values(r).some(Boolean)},e.getIsAllRowsExpanded=()=>{const r=e.getState().expanded;return typeof r=="boolean"?r===!0:!(!Object.keys(r).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let r=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(o=>{const l=o.split(".");r=Math.max(r,l.length)}),r},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=n=>{t.setExpanded(r=>{var s;const o=r===!0?!0:!!(r!=null&&r[e.id]);let l={};if(r===!0?Object.keys(t.getRowModel().rowsById).forEach(u=>{l[u]=!0}):l=r,n=(s=n)!=null?s:!o,!o&&n)return{...l,[e.id]:!0};if(o&&!n){const{[e.id]:u,...d}=l;return d}return r})},e.getIsExpanded=()=>{var n;const r=t.getState().expanded;return!!((n=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?n:r===!0||r?.[e.id])},e.getCanExpand=()=>{var n,r,s;return(n=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?n:((r=t.options.enableExpanding)!=null?r:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let n=!0,r=e;for(;n&&r.parentId;)r=t.getRow(r.parentId,!0),n=r.getIsExpanded();return n},e.getToggleExpandedHandler=()=>{const n=e.getCanExpand();return()=>{n&&e.toggleExpanded()}}}},Eb=0,kb=10,gy=()=>({pageIndex:Eb,pageSize:kb}),bee={getInitialState:e=>({...e,pagination:{...gy(),...e?.pagination}}),getDefaultOptions:e=>({onPaginationChange:qr("pagination",e)}),createTable:e=>{let t=!1,n=!1;e._autoResetPageIndex=()=>{var r,s;if(!t){e._queue(()=>{t=!0});return}if((r=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?r:!e.options.manualPagination){if(n)return;n=!0,e._queue(()=>{e.resetPageIndex(),n=!1})}},e.setPagination=r=>{const s=o=>ma(r,o);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=r=>{var s;e.setPagination(r?gy():(s=e.initialState.pagination)!=null?s:gy())},e.setPageIndex=r=>{e.setPagination(s=>{let o=ma(r,s.pageIndex);const l=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return o=Math.max(0,Math.min(o,l)),{...s,pageIndex:o}})},e.resetPageIndex=r=>{var s,o;e.setPageIndex(r?Eb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageIndex)!=null?s:Eb)},e.resetPageSize=r=>{var s,o;e.setPageSize(r?kb:(s=(o=e.initialState)==null||(o=o.pagination)==null?void 0:o.pageSize)!=null?s:kb)},e.setPageSize=r=>{e.setPagination(s=>{const o=Math.max(1,ma(r,s.pageSize)),l=s.pageSize*s.pageIndex,u=Math.floor(l/o);return{...s,pageIndex:u,pageSize:o}})},e.setPageCount=r=>e.setPagination(s=>{var o;let l=ma(r,(o=e.options.pageCount)!=null?o:-1);return typeof l=="number"&&(l=Math.max(-1,l)),{...s,pageCount:l}}),e.getPageOptions=ot(()=>[e.getPageCount()],r=>{let s=[];return r&&r>0&&(s=[...new Array(r)].fill(null).map((o,l)=>l)),s},at(e.options,"debugTable")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:r}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:re.setPageIndex(r=>r-1),e.nextPage=()=>e.setPageIndex(r=>r+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var r;return(r=e.options.pageCount)!=null?r:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var r;return(r=e.options.rowCount)!=null?r:e.getPrePaginationRowModel().rows.length}}},my=()=>({top:[],bottom:[]}),xee={getInitialState:e=>({rowPinning:my(),...e}),getDefaultOptions:e=>({onRowPinningChange:qr("rowPinning",e)}),createRow:(e,t)=>{e.pin=(n,r,s)=>{const o=r?e.getLeafRows().map(d=>{let{id:f}=d;return f}):[],l=s?e.getParentRows().map(d=>{let{id:f}=d;return f}):[],u=new Set([...l,e.id,...o]);t.setRowPinning(d=>{var f,h;if(n==="bottom"){var m,g;return{top:((m=d?.top)!=null?m:[]).filter(w=>!(u!=null&&u.has(w))),bottom:[...((g=d?.bottom)!=null?g:[]).filter(w=>!(u!=null&&u.has(w))),...Array.from(u)]}}if(n==="top"){var x,b;return{top:[...((x=d?.top)!=null?x:[]).filter(w=>!(u!=null&&u.has(w))),...Array.from(u)],bottom:((b=d?.bottom)!=null?b:[]).filter(w=>!(u!=null&&u.has(w)))}}return{top:((f=d?.top)!=null?f:[]).filter(w=>!(u!=null&&u.has(w))),bottom:((h=d?.bottom)!=null?h:[]).filter(w=>!(u!=null&&u.has(w)))}})},e.getCanPin=()=>{var n;const{enableRowPinning:r,enablePinning:s}=t.options;return typeof r=="function"?r(e):(n=r??s)!=null?n:!0},e.getIsPinned=()=>{const n=[e.id],{top:r,bottom:s}=t.getState().rowPinning,o=n.some(u=>r?.includes(u)),l=n.some(u=>s?.includes(u));return o?"top":l?"bottom":!1},e.getPinnedIndex=()=>{var n,r;const s=e.getIsPinned();if(!s)return-1;const o=(n=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:n.map(l=>{let{id:u}=l;return u});return(r=o?.indexOf(e.id))!=null?r:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var n,r;return e.setRowPinning(t?my():(n=(r=e.initialState)==null?void 0:r.rowPinning)!=null?n:my())},e.getIsSomeRowsPinned=t=>{var n;const r=e.getState().rowPinning;if(!t){var s,o;return!!((s=r.top)!=null&&s.length||(o=r.bottom)!=null&&o.length)}return!!((n=r[t])!=null&&n.length)},e._getPinnedRows=(t,n,r)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(n??[]).map(l=>{const u=e.getRow(l,!0);return u.getIsAllParentsExpanded()?u:null}):(n??[]).map(l=>t.find(u=>u.id===l))).filter(Boolean).map(l=>({...l,position:r}))},e.getTopRows=ot(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,n)=>e._getPinnedRows(t,n,"top"),at(e.options,"debugRows")),e.getBottomRows=ot(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,n)=>e._getPinnedRows(t,n,"bottom"),at(e.options,"debugRows")),e.getCenterRows=ot(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,n,r)=>{const s=new Set([...n??[],...r??[]]);return t.filter(o=>!s.has(o.id))},at(e.options,"debugRows"))}},wee={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:qr("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var n;return e.setRowSelection(t?{}:(n=e.initialState.rowSelection)!=null?n:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(n=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const r={...n},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(o=>{o.getCanSelect()&&(r[o.id]=!0)}):s.forEach(o=>{delete r[o.id]}),r})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(n=>{const r=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...n};return e.getRowModel().rows.forEach(o=>{jb(s,o.id,r,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=ot(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,n)=>Object.keys(t).length?vy(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable")),e.getFilteredSelectedRowModel=ot(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,n)=>Object.keys(t).length?vy(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable")),e.getGroupedSelectedRowModel=ot(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,n)=>Object.keys(t).length?vy(e,n):{rows:[],flatRows:[],rowsById:{}},at(e.options,"debugTable")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:n}=e.getState();let r=!!(t.length&&Object.keys(n).length);return r&&t.some(s=>s.getCanSelect()&&!n[s.id])&&(r=!1),r},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:n}=e.getState();let r=!!t.length;return r&&t.some(s=>!n[s.id])&&(r=!1),r},e.getIsSomeRowsSelected=()=>{var t;const n=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return n>0&&n{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(n=>n.getCanSelect()).some(n=>n.getIsSelected()||n.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(n,r)=>{const s=e.getIsSelected();t.setRowSelection(o=>{var l;if(n=typeof n<"u"?n:!s,e.getCanSelect()&&s===n)return o;const u={...o};return jb(u,e.id,n,(l=r?.selectChildren)!=null?l:!0,t),u})},e.getIsSelected=()=>{const{rowSelection:n}=t.getState();return iw(e,n)},e.getIsSomeSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:n}=t.getState();return Tb(e,n)==="all"},e.getCanSelect=()=>{var n;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(n=t.options.enableRowSelection)!=null?n:!0},e.getCanSelectSubRows=()=>{var n;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(n=t.options.enableSubRowSelection)!=null?n:!0},e.getCanMultiSelect=()=>{var n;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(n=t.options.enableMultiRowSelection)!=null?n:!0},e.getToggleSelectedHandler=()=>{const n=e.getCanSelect();return r=>{var s;n&&e.toggleSelected((s=r.target)==null?void 0:s.checked)}}}},jb=(e,t,n,r,s)=>{var o;const l=s.getRow(t,!0);n?(l.getCanMultiSelect()||Object.keys(e).forEach(u=>delete e[u]),l.getCanSelect()&&(e[t]=!0)):delete e[t],r&&(o=l.subRows)!=null&&o.length&&l.getCanSelectSubRows()&&l.subRows.forEach(u=>jb(e,u.id,n,r,s))};function vy(e,t){const n=e.getState().rowSelection,r=[],s={},o=function(l,u){return l.map(d=>{var f;const h=iw(d,n);if(h&&(r.push(d),s[d.id]=d),(f=d.subRows)!=null&&f.length&&(d={...d,subRows:o(d.subRows)}),h)return d}).filter(Boolean)};return{rows:o(t.rows),flatRows:r,rowsById:s}}function iw(e,t){var n;return(n=t[e.id])!=null?n:!1}function Tb(e,t,n){var r;if(!((r=e.subRows)!=null&&r.length))return!1;let s=!0,o=!1;return e.subRows.forEach(l=>{if(!(o&&!s)&&(l.getCanSelect()&&(iw(l,t)?o=!0:s=!1),l.subRows&&l.subRows.length)){const u=Tb(l,t);u==="all"?o=!0:(u==="some"&&(o=!0),s=!1)}}),s?"all":o?"some":!1}const Nb=/([0-9]+)/gm,See=(e,t,n)=>vI(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),Cee=(e,t,n)=>vI(Na(e.getValue(n)),Na(t.getValue(n))),Eee=(e,t,n)=>lw(Na(e.getValue(n)).toLowerCase(),Na(t.getValue(n)).toLowerCase()),kee=(e,t,n)=>lw(Na(e.getValue(n)),Na(t.getValue(n))),jee=(e,t,n)=>{const r=e.getValue(n),s=t.getValue(n);return r>s?1:rlw(e.getValue(n),t.getValue(n));function lw(e,t){return e===t?0:e>t?1:-1}function Na(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function vI(e,t){const n=e.split(Nb).filter(Boolean),r=t.split(Nb).filter(Boolean);for(;n.length&&r.length;){const s=n.shift(),o=r.shift(),l=parseInt(s,10),u=parseInt(o,10),d=[l,u].sort();if(isNaN(d[0])){if(s>o)return 1;if(o>s)return-1;continue}if(isNaN(d[1]))return isNaN(l)?-1:1;if(l>u)return 1;if(u>l)return-1}return n.length-r.length}const pu={alphanumeric:See,alphanumericCaseSensitive:Cee,text:Eee,textCaseSensitive:kee,datetime:jee,basic:Tee},Nee={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:qr("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const n=t.getFilteredRowModel().flatRows.slice(10);let r=!1;for(const s of n){const o=s?.getValue(e.id);if(Object.prototype.toString.call(o)==="[object Date]")return pu.datetime;if(typeof o=="string"&&(r=!0,o.split(Nb).length>1))return pu.alphanumeric}return r?pu.text:pu.basic},e.getAutoSortDir=()=>{const n=t.getFilteredRowModel().flatRows[0];return typeof n?.getValue(e.id)=="string"?"asc":"desc"},e.getSortingFn=()=>{var n,r;if(!e)throw new Error;return yg(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(n=(r=t.options.sortingFns)==null?void 0:r[e.columnDef.sortingFn])!=null?n:pu[e.columnDef.sortingFn]},e.toggleSorting=(n,r)=>{const s=e.getNextSortingOrder(),o=typeof n<"u"&&n!==null;t.setSorting(l=>{const u=l?.find(x=>x.id===e.id),d=l?.findIndex(x=>x.id===e.id);let f=[],h,m=o?n:s==="desc";if(l!=null&&l.length&&e.getCanMultiSort()&&r?u?h="toggle":h="add":l!=null&&l.length&&d!==l.length-1?h="replace":u?h="toggle":h="replace",h==="toggle"&&(o||s||(h="remove")),h==="add"){var g;f=[...l,{id:e.id,desc:m}],f.splice(0,f.length-((g=t.options.maxMultiSortColCount)!=null?g:Number.MAX_SAFE_INTEGER))}else h==="toggle"?f=l.map(x=>x.id===e.id?{...x,desc:m}:x):h==="remove"?f=l.filter(x=>x.id!==e.id):f=[{id:e.id,desc:m}];return f})},e.getFirstSortDir=()=>{var n,r;return((n=(r=e.columnDef.sortDescFirst)!=null?r:t.options.sortDescFirst)!=null?n:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=n=>{var r,s;const o=e.getFirstSortDir(),l=e.getIsSorted();return l?l!==o&&((r=t.options.enableSortingRemoval)==null||r)&&(!(n&&(s=t.options.enableMultiRemove)!=null)||s)?!1:l==="desc"?"asc":"desc":o},e.getCanSort=()=>{var n,r;return((n=e.columnDef.enableSorting)!=null?n:!0)&&((r=t.options.enableSorting)!=null?r:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var n,r;return(n=(r=e.columnDef.enableMultiSort)!=null?r:t.options.enableMultiSort)!=null?n:!!e.accessorFn},e.getIsSorted=()=>{var n;const r=(n=t.getState().sorting)==null?void 0:n.find(s=>s.id===e.id);return r?r.desc?"desc":"asc":!1},e.getSortIndex=()=>{var n,r;return(n=(r=t.getState().sorting)==null?void 0:r.findIndex(s=>s.id===e.id))!=null?n:-1},e.clearSorting=()=>{t.setSorting(n=>n!=null&&n.length?n.filter(r=>r.id!==e.id):[])},e.getToggleSortingHandler=()=>{const n=e.getCanSort();return r=>{n&&(r.persist==null||r.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(r):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var n,r;e.setSorting(t?[]:(n=(r=e.initialState)==null?void 0:r.sorting)!=null?n:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Mee=[ZX,gee,dee,fee,YX,XX,mee,vee,Nee,cee,yee,bee,xee,wee,pee];function _ee(e){var t,n;const r=[...Mee,...(t=e._features)!=null?t:[]];let s={_features:r};const o=s._features.reduce((g,x)=>Object.assign(g,x.getDefaultOptions==null?void 0:x.getDefaultOptions(s)),{}),l=g=>s.options.mergeOptions?s.options.mergeOptions(o,g):{...o,...g};let d={...{},...(n=e.initialState)!=null?n:{}};s._features.forEach(g=>{var x;d=(x=g.getInitialState==null?void 0:g.getInitialState(d))!=null?x:d});const f=[];let h=!1;const m={_features:r,options:{...o,...e},initialState:d,_queue:g=>{f.push(g),h||(h=!0,Promise.resolve().then(()=>{for(;f.length;)f.shift()();h=!1}).catch(x=>setTimeout(()=>{throw x})))},reset:()=>{s.setState(s.initialState)},setOptions:g=>{const x=ma(g,s.options);s.options=l(x)},getState:()=>s.options.state,setState:g=>{s.options.onStateChange==null||s.options.onStateChange(g)},_getRowId:(g,x,b)=>{var w;return(w=s.options.getRowId==null?void 0:s.options.getRowId(g,x,b))!=null?w:`${b?[b.id,x].join("."):x}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(g,x)=>{let b=(x?s.getPrePaginationRowModel():s.getRowModel()).rowsById[g];if(!b&&(b=s.getCoreRowModel().rowsById[g],!b))throw new Error;return b},_getDefaultColumnDef:ot(()=>[s.options.defaultColumn],g=>{var x;return g=(x=g)!=null?x:{},{header:b=>{const w=b.header.column.columnDef;return w.accessorKey?w.accessorKey:w.accessorFn?w.id:null},cell:b=>{var w,C;return(w=(C=b.renderValue())==null||C.toString==null?void 0:C.toString())!=null?w:null},...s._features.reduce((b,w)=>Object.assign(b,w.getDefaultColumnDef==null?void 0:w.getDefaultColumnDef()),{}),...g}},at(e,"debugColumns")),_getColumnDefs:()=>s.options.columns,getAllColumns:ot(()=>[s._getColumnDefs()],g=>{const x=function(b,w,C){return C===void 0&&(C=0),b.map(k=>{const j=QX(s,k,C,w),M=k;return j.columns=M.columns?x(M.columns,j,C+1):[],j})};return x(g)},at(e,"debugColumns")),getAllFlatColumns:ot(()=>[s.getAllColumns()],g=>g.flatMap(x=>x.getFlatColumns()),at(e,"debugColumns")),_getAllFlatColumnsById:ot(()=>[s.getAllFlatColumns()],g=>g.reduce((x,b)=>(x[b.id]=b,x),{}),at(e,"debugColumns")),getAllLeafColumns:ot(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(g,x)=>{let b=g.flatMap(w=>w.getLeafColumns());return x(b)},at(e,"debugColumns")),getColumn:g=>s._getAllFlatColumnsById()[g]};Object.assign(s,m);for(let g=0;got(()=>[e.options.data],t=>{const n={rows:[],flatRows:[],rowsById:{}},r=function(s,o,l){o===void 0&&(o=0);const u=[];for(let f=0;fe._autoResetPageIndex()))}function Pee(e,t,n){return n.options.filterFromLeafRows?Oee(e,t,n):Iee(e,t,n)}function Oee(e,t,n){var r;const s=[],o={},l=(r=n.options.maxLeafRowFilterDepth)!=null?r:100,u=function(d,f){f===void 0&&(f=0);const h=[];for(let g=0;got(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,n,r)=>{if(!t.rows.length||!(n!=null&&n.length)&&!r){for(let g=0;g{var x;const b=e.getColumn(g.id);if(!b)return;const w=b.getFilterFn();w&&s.push({id:g.id,filterFn:w,resolvedValue:(x=w.resolveFilterValue==null?void 0:w.resolveFilterValue(g.value))!=null?x:g.value})});const l=(n??[]).map(g=>g.id),u=e.getGlobalFilterFn(),d=e.getAllLeafColumns().filter(g=>g.getCanGlobalFilter());r&&u&&d.length&&(l.push("__global__"),d.forEach(g=>{var x;o.push({id:g.id,filterFn:u,resolvedValue:(x=u.resolveFilterValue==null?void 0:u.resolveFilterValue(r))!=null?x:r})}));let f,h;for(let g=0;g{x.columnFiltersMeta[w]=C})}if(o.length){for(let b=0;b{x.columnFiltersMeta[w]=C})){x.columnFilters.__global__=!0;break}}x.columnFilters.__global__!==!0&&(x.columnFilters.__global__=!1)}}const m=g=>{for(let x=0;xe._autoResetPageIndex()))}function Dee(){return e=>ot(()=>[e.getState().grouping,e.getPreGroupedRowModel()],(t,n)=>{if(!n.rows.length||!t.length)return n.rows.forEach(d=>{d.depth=0,d.parentId=void 0}),n;const r=t.filter(d=>e.getColumn(d)),s=[],o={},l=function(d,f,h){if(f===void 0&&(f=0),f>=r.length)return d.map(b=>(b.depth=f,s.push(b),o[b.id]=b,b.subRows&&(b.subRows=l(b.subRows,f+1,b.id)),b));const m=r[f],g=Fee(d,m);return Array.from(g.entries()).map((b,w)=>{let[C,k]=b,j=`${m}:${C}`;j=h?`${h}>${j}`:j;const M=l(k,f+1,j);M.forEach(N=>{N.parentId=j});const _=f?lI(k,N=>N.subRows):k,R=bg(e,j,_[0].original,w,f,void 0,h);return Object.assign(R,{groupingColumnId:m,groupingValue:C,subRows:M,leafRows:_,getValue:N=>{if(r.includes(N)){if(R._valuesCache.hasOwnProperty(N))return R._valuesCache[N];if(k[0]){var O;R._valuesCache[N]=(O=k[0].getValue(N))!=null?O:void 0}return R._valuesCache[N]}if(R._groupingValuesCache.hasOwnProperty(N))return R._groupingValuesCache[N];const D=e.getColumn(N),z=D?.getAggregationFn();if(z)return R._groupingValuesCache[N]=z(N,_,k),R._groupingValuesCache[N]}}),M.forEach(N=>{s.push(N),o[N.id]=N}),R})},u=l(n.rows,0);return u.forEach(d=>{s.push(d),o[d.id]=d}),{rows:u,flatRows:s,rowsById:o}},at(e.options,"debugTable","getGroupedRowModel",()=>{e._queue(()=>{e._autoResetExpanded(),e._autoResetPageIndex()})}))}function Fee(e,t){const n=new Map;return e.reduce((r,s)=>{const o=`${s.getGroupingValue(t)}`,l=r.get(o);return l?l.push(s):r.set(o,[s]),r},n)}function Lee(){return e=>ot(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,n)=>{if(!n.rows.length||!(t!=null&&t.length))return n;const r=e.getState().sorting,s=[],o=r.filter(d=>{var f;return(f=e.getColumn(d.id))==null?void 0:f.getCanSort()}),l={};o.forEach(d=>{const f=e.getColumn(d.id);f&&(l[d.id]={sortUndefined:f.columnDef.sortUndefined,invertSorting:f.columnDef.invertSorting,sortingFn:f.getSortingFn()})});const u=d=>{const f=d.map(h=>({...h}));return f.sort((h,m)=>{for(let x=0;x{var m;s.push(h),(m=h.subRows)!=null&&m.length&&(h.subRows=u(h.subRows))}),f};return{rows:u(n.rows),flatRows:s,rowsById:n.rowsById}},at(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/** + * react-table + * + * Copyright (c) TanStack + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function bk(e,t){return e?$ee(e)?y.createElement(e,t):e:null}function $ee(e){return Bee(e)||typeof e=="function"||zee(e)}function Bee(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function zee(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Uee(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=y.useState(()=>({current:_ee(t)})),[r,s]=y.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:l=>{s(l),e.onStateChange==null||e.onStateChange(l)}})),n.current}const yI=y.forwardRef(({className:e,...t},n)=>i.jsx("div",{className:"relative w-full overflow-auto",children:i.jsx("table",{ref:n,className:Ie("w-full caption-bottom text-sm",e),...t})}));yI.displayName="Table";const bI=y.forwardRef(({className:e,...t},n)=>i.jsx("thead",{ref:n,className:Ie("[&_tr]:border-b",e),...t}));bI.displayName="TableHeader";const xI=y.forwardRef(({className:e,...t},n)=>i.jsx("tbody",{ref:n,className:Ie("[&_tr:last-child]:border-0",e),...t}));xI.displayName="TableBody";const Vee=y.forwardRef(({className:e,...t},n)=>i.jsx("tfoot",{ref:n,className:Ie("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));Vee.displayName="TableFooter";const Eu=y.forwardRef(({className:e,...t},n)=>i.jsx("tr",{ref:n,className:Ie("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));Eu.displayName="TableRow";const wI=y.forwardRef(({className:e,...t},n)=>i.jsx("th",{ref:n,className:Ie("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));wI.displayName="TableHead";const Np=y.forwardRef(({className:e,...t},n)=>i.jsx("td",{ref:n,className:Ie("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));Np.displayName="TableCell";const Hee=y.forwardRef(({className:e,...t},n)=>i.jsx("caption",{ref:n,className:Ie("mt-4 text-sm text-muted-foreground",e),...t}));Hee.displayName="TableCaption";function $a({columns:e,data:t,isLoading:n,loadingMessage:r,noResultsMessage:s,enableHeaders:o=!0,className:l,highlightedRows:u,...d}){const f=Uee({...d,data:t,columns:e,getCoreRowModel:Ree(),getFilteredRowModel:Aee(),getGroupedRowModel:Dee(),getSortedRowModel:Lee()});return i.jsx("div",{className:Ie("rounded-md border",l),children:i.jsxs(yI,{children:[o&&i.jsx(bI,{children:f.getHeaderGroups().map(h=>i.jsx(Eu,{children:h.headers.map(m=>i.jsx(wI,{children:m.isPlaceholder?null:bk(m.column.columnDef.header,m.getContext())},m.id))},h.id))}),i.jsx(xI,{children:n?i.jsx(Eu,{children:i.jsx(Np,{colSpan:e.length,className:"h-24 text-center text-muted-foreground",children:r??"Carregando..."})}):i.jsx(i.Fragment,{children:f.getRowModel().rows?.length?f.getRowModel().rows.map(h=>i.jsx(Eu,{"data-state":h.getIsSelected()?"selected":u?.includes(h.id)?"highlighted":"",children:h.getVisibleCells().map(m=>i.jsx(Np,{children:bk(m.column.columnDef.cell,m.getContext())},m.id))},h.id)):i.jsx(Eu,{children:i.jsx(Np,{colSpan:e.length,className:"h-24 text-center",children:s??"Nenhum resultado encontrado!"})})})})]})})}const qee=e=>["dify","fetchSessions",JSON.stringify(e)],Kee=async({difyId:e,instanceName:t})=>(await Ee.get(`/dify/fetchSessions/${e}/${t}`)).data,Wee=e=>{const{difyId:t,instanceName:n,...r}=e;return mt({...r,queryKey:qee({difyId:t,instanceName:n}),queryFn:()=>Kee({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function SI({difyId:e}){const{t}=Ve(),{instance:n}=ct(),{changeStatusDify:r}=vg(),[s,o]=y.useState([]),{data:l,refetch:u}=Wee({difyId:e,instanceName:n?.name}),[d,f]=y.useState(!1),[h,m]=y.useState("");function g(){u()}const x=async(w,C)=>{try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("dify.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("dify.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:d,onOpenChange:f,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("dify.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("dify.sessions.search"),value:h,onChange:w=>m(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{})})]}),i.jsx($a,{columns:b,data:l??[],onSortingChange:o,state:{sorting:s,globalFilter:h},onGlobalFilterChange:m,enableGlobalFilter:!0,noResultsMessage:t("dify.sessions.table.none")})]})]})]})}const Gee=P.object({enabled:P.boolean(),description:P.string(),botType:P.string(),apiUrl:P.string(),apiKey:P.string(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function CI({initialData:e,onSubmit:t,handleDelete:n,difyId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(Gee),defaultValues:e||{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("dify.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("dify.form.description.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("dify.form.difySettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"botType",label:d("dify.form.botType.label"),options:[{label:d("dify.form.botType.chatBot"),value:"chatBot"},{label:d("dify.form.botType.textGenerator"),value:"textGenerator"},{label:d("dify.form.botType.agent"),value:"agent"},{label:d("dify.form.botType.workflow"),value:"workflow"}]}),i.jsx(le,{name:"apiUrl",label:d("dify.form.apiUrl.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"apiKey",label:d("dify.form.apiKey.label"),required:!0,children:i.jsx(ne,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("dify.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("dify.form.triggerType.label"),options:[{label:d("dify.form.triggerType.keyword"),value:"keyword"},{label:d("dify.form.triggerType.all"),value:"all"},{label:d("dify.form.triggerType.advanced"),value:"advanced"},{label:d("dify.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("dify.form.triggerOperator.label"),options:[{label:d("dify.form.triggerOperator.contains"),value:"contains"},{label:d("dify.form.triggerOperator.equals"),value:"equals"},{label:d("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("dify.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("dify.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("dify.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("dify.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("dify.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("dify.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("dify.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("dify.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("dify.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("dify.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:d("dify.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:d("dify.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"dify.button.saving":"dify.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(SI,{difyId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("dify.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"dify.button.saving":"dify.button.update")})]})]})]})})}function Jee({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState(!1),[o,l]=y.useState(!1),{createDify:u}=vg(),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:f.enabled,description:f.description,botType:f.botType,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar||0};await u({instanceName:n.name,token:n.token,data:h}),me.success(t("dify.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{s(!1)}};return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("dify.form.title")})}),i.jsx(CI,{onSubmit:d,isModal:!0,isLoading:r})]})]})}const Qee=e=>["dify","getDify",JSON.stringify(e)],Zee=async({difyId:e,instanceName:t})=>(await Ee.get(`/dify/fetch/${e}/${t}`)).data,Yee=e=>{const{difyId:t,instanceName:n,...r}=e;return mt({...r,queryKey:Qee({difyId:t,instanceName:n}),queryFn:()=>Zee({difyId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function Xee({difyId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteDify:u,updateDify:d}=vg(),{data:f,isLoading:h}=Yee({difyId:e,instanceName:r?.name}),m=y.useMemo(()=>({enabled:!!f?.enabled,description:f?.description??"",botType:f?.botType??"",apiUrl:f?.apiUrl??"",apiKey:f?.apiKey??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue??"",expire:f?.expire??0,keywordFinish:f?.keywordFinish??"",delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage??"",listeningFromMe:!!f?.listeningFromMe,stopBotFromMe:!!f?.stopBotFromMe,keepOpen:!!f?.keepOpen,debounceTime:f?.debounceTime??0,splitMessages:f?.splitMessages??!1,timePerChar:f?.timePerChar??0}),[f?.apiKey,f?.apiUrl,f?.botType,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,botType:b.botType,apiUrl:b.apiUrl,apiKey:b.apiKey,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar||0};await d({instanceName:r.name,difyId:e,data:w}),me.success(n("dify.toast.success.update")),t(),s(`/manager/instance/${r.id}/dify/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,difyId:e}),me.success(n("dify.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/dify`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir dify:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(CI,{initialData:m,onSubmit:g,difyId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function xk(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{difyId:r}=ls(),{data:s,refetch:o,isLoading:l}=iI({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/dify/${h}`)},f=()=>{o()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(SI,{}),i.jsx(WX,{}),i.jsx(Jee,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:l?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsxs(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:h.description||h.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:h.botType})]},h.id)):i.jsx(se,{variant:"link",children:e("dify.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(Xee,{difyId:r,resetTable:f})})]})]})]})}const EI=y.createContext({instance:null,isLoading:!0,error:null});function ete({children:e}){const[t]=hd(),[n,r]=y.useState(null),[s,o]=y.useState(!0),[l,u]=y.useState(null);return y.useEffect(()=>{(async()=>{const f=t.get("token"),h=t.get("instanceName"),m=t.get("apiUrl");if(!f||!h||!m){u("Token, instanceName e apiUrl são obrigatórios"),o(!1);return}try{const g=m.endsWith("/")?m.slice(0,-1):m;localStorage.setItem(jn.API_URL,g),localStorage.setItem(jn.INSTANCE_TOKEN,f);const{data:x}=await sn.get(`${g}/instance/fetchInstances?instanceName=${h}`,{headers:{apikey:f}});console.log("API Response:",x),x&&Array.isArray(x)&&x.length>0?r(x[0]):u("Instância não encontrada")}catch{u("Erro ao validar token ou buscar instância")}finally{o(!1)}})()},[t]),i.jsx(EI.Provider,{value:{instance:n,isLoading:s,error:l},children:e})}const cw=()=>y.useContext(EI),uw=y.createContext({}),tte=({children:e})=>{const[t,n]=y.useState(null);return i.jsx(uw.Provider,{value:{replyingMessage:t,setReplyingMessage:n},children:e})},nte=e=>{const t=Math.floor(e/60),n=e%60,r=t<10?`${t}`:t,s=n<10?`0${n}`:n;return`${r}:${s}`},wk=200,rte=({imageMessage:e})=>i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:e?.mediaUrl,alt:"Quoted message",width:100,height:100}),i.jsx(cB,{className:"mr-2 h-4 w-4 text-muted-foreground"})]}),i.jsx("span",{className:"inline-block max-w-40 overflow-hidden overflow-ellipsis whitespace-nowrap text-sm text-muted-foreground",children:e.caption})]}),ste=({videoMessage:e})=>i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:e?.mediaUrl,alt:"Quoted message",width:100,height:100}),i.jsx(TB,{className:"mr-2 h-4 w-4 text-muted-foreground"})]}),i.jsx("span",{className:"inline-block max-w-40 overflow-hidden overflow-ellipsis whitespace-nowrap text-sm text-muted-foreground",children:e.caption})]}),ote=({audioMessage:e})=>i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hT,{className:"h-6 w-6 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:nte(e.seconds)})]}),i.jsx("span",{className:"inline-block max-w-40 overflow-hidden overflow-ellipsis whitespace-nowrap text-sm text-muted-foreground",children:e.fileName})]}),ate=({stickerMessage:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:e.mediaUrl,alt:"Sticker",width:100,height:100}),i.jsx(CB,{className:"h-6 w-6 text-muted-foreground"})]}),ite=({documentMessage:e})=>i.jsx("div",{className:"flex flex-col gap-2",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hb,{className:"h-6 w-6 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:e.fileName})]})}),lte=({documentMessage:e})=>i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hb,{className:"h-6 w-6 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:e.fileName})]}),i.jsx("span",{className:"inline-block max-w-40 overflow-hidden overflow-ellipsis whitespace-nowrap text-sm text-muted-foreground",children:e.caption})]}),cte=({contactMessage:e})=>i.jsx("div",{className:"flex flex-col gap-2",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ap,{className:"h-6 w-6 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:e.displayName})]})}),ute=({locationMessage:e})=>i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(yB,{className:"h-6 w-6 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:e.name})]}),i.jsx("span",{className:"inline-block max-w-40 text-sm text-muted-foreground",children:e.address})]}),dte=({conversation:e})=>i.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm text-muted-foreground",children:e.length>wk?`${e.substring(0,wk)}...`:e}),fte=({chat:e})=>{const{replyingMessage:t,setReplyingMessage:n}=y.useContext(uw),r=()=>{n(null)},s=f=>f?.conversation?f.conversation:f?.viewOnceMessage?.message?.interactiveMessage?.body?.text?f.viewOnceMessage.message.interactiveMessage.body.text:"",o=()=>t?.key.fromMe?"Você":e?.pushName,l=()=>{if(t?.messageType==="imageMessage")return i.jsx(rte,{imageMessage:{caption:t?.message.imageMessage.caption,mediaUrl:t?.message.mediaUrl}});if(t?.messageType==="videoMessage")return i.jsx(ste,{videoMessage:{caption:t?.message.videoMessage.caption,mediaUrl:t?.message.mediaUrl}});if(t?.messageType==="audioMessage")return i.jsx(ote,{audioMessage:t?.message.audioMessage});if(t?.messageType==="stickerMessage")return i.jsx(ate,{stickerMessage:t?.message});if(t?.messageType==="documentMessage")return i.jsx(ite,{documentMessage:{name:t?.message.documentMessage.name,mediaUrl:t?.message.mediaUrl}});if(t?.messageType==="documentWithCaptionMessage")return i.jsx(lte,{documentMessage:{name:t?.message.documentWithCaptionMessage.message.documentMessage.name,caption:t?.message.documentWithCaptionMessage.message.documentMessage.caption,mediaUrl:t?.message.mediaUrl}});if(t?.messageType==="contactMessage")return i.jsx(cte,{contactMessage:t?.message.contactMessage});if(t?.messageType==="locationMessage")return i.jsx(ute,{locationMessage:t?.message.locationMessage});if(t?.messageType==="conversation"||t?.messageType==="interactiveMessage"||t?.messageType==="extendedTextMessage")return i.jsx(dte,{conversation:s(t?.message)})},{inputIconsMainColor:u,inputBackgroundColor:d}=La();return i.jsxs("div",{className:"relative flex items-center overflow-hidden rounded-lg dark:text-white",style:{backgroundColor:d},children:[i.jsx("div",{className:`absolute h-full w-1 rounded-l-lg ${t?.key.fromMe?"bg-blue-700 dark:bg-blue-300":"bg-blue-100"}`}),i.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2 p-2 pl-4",children:[i.jsx("span",{className:`text-sm font-bold ${t?.key.fromMe?"text-blue-700 dark:text-blue-300":"text-blue-600"}`,children:o()}),l()]}),i.jsx(se,{size:"icon",variant:"ghost",className:"ml-auto h-10 w-10 shrink-0 rounded-full",onClick:r,style:{backgroundColor:d,color:u},children:i.jsx(qb,{className:"h-6 w-6"})})]})},yy=[{name:"Smileys",icon:gT,emojis:["😀","😃","😄","😁","😆","😅","😂","🤣","😊","😇"]},{name:"Natureza",icon:HC,emojis:["🌿","🌱","🌳","🌴","🌵","🌷","🌸","🌹","🌺","🌻"]},{name:"Comida",icon:HC,emojis:["🍎","🍐","🍊","🍋","🍌","🍉","🍇","🍓","🍒","🍑"]},{name:"Atividades",icon:Y$,emojis:["⚽️","🏀","🏈","⚾️","🎾","🏐","🏉","🎱","🏓","🏸"]},{name:"Viagem",icon:K$,emojis:["🚗","🚕","🚙","🚌","🚎","🏎","🚓","🚑","🚒","🚐"]},{name:"Objetos",icon:gB,emojis:["💡","🔦","🕯","🧳","⌛️","⏳","🌡","🧪","🧬","🔬"]},{name:"Símbolos",icon:oB,emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","🤎","💔"]}];function pte({handleEmojiClick:e}){const{inputIconsMainColor:t}=La(),n=r=>yy.find(o=>o.name===r)?.emojis||[];return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{type:"button",variant:"ghost",size:"icon",className:"rounded-full p-2",children:[i.jsx(gT,{className:"h-6 w-6",style:{color:t}}),i.jsx("span",{className:"sr-only",children:"Emojis"})]})}),i.jsx(hr,{className:"bg-background p-2",align:"end",children:i.jsxs(Yx,{defaultValue:"Smileys",className:"w-full",children:[i.jsx(hg,{className:"grid grid-cols-8 gap-2",children:yy.map(r=>i.jsx(Jl,{value:r.name,children:i.jsx(r.icon,{className:"h-5 w-5"})},r.name))}),yy.map(r=>i.jsx(Ql,{value:r.name,children:i.jsx("div",{className:"grid grid-cols-8 gap-2",children:n(r.name).map((s,o)=>i.jsx(se,{variant:"ghost",className:"h-12 p-2 text-2xl",onClick:()=>e(s),children:s},o))})},r.name))]})})]})}const hte=({isSendingMessage:e,isRecording:t,audioBlob:n,elapsedTime:r,startRecording:s,stopRecording:o,clearRecording:l,sendAudioMessage:u,disabled:d})=>{const{inputIconsMainColor:f}=La();return i.jsxs("div",{className:"flex items-center gap-2",children:[t&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(se,{type:"button",size:"icon",variant:"ghost",className:"rounded-full p-2",onClick:o,children:i.jsx(SB,{className:"h-6 w-6 text-[#b03f3f]"})}),i.jsxs("span",{children:[r,"s"]})]}),n&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(se,{type:"button",size:"icon",variant:"ghost",className:"rounded-full p-2",disabled:e,onClick:l,children:i.jsx(kB,{className:"h-6 w-6 text-[#b03f3f]"})}),i.jsx("audio",{controls:!0,src:URL.createObjectURL(n)})]}),i.jsx(se,{type:"button",size:"icon",variant:"ghost",className:"rounded-full p-2",disabled:e||t||d,onClick:n?u:s,children:e?i.jsx(On,{className:"h-6 w-6",style:{color:f}}):n?i.jsx(Th,{className:"h-6 w-6",style:{color:f}}):i.jsx(hT,{className:"h-6 w-6",style:{color:f}})})]})},gte=({isSendingMessage:e,sendMessage:t,disabled:n})=>{const{inputIconsMainColor:r}=La();return i.jsx(se,{type:"button",size:"icon",variant:"ghost",className:"rounded-full p-2",onClick:t,disabled:e||n,children:e?i.jsx(On,{className:"h-6 w-6",style:{color:r}}):i.jsx(Th,{className:"h-6 w-6",style:{color:r}})})},mte=({chat:e})=>{const[t]=hd(),{inputBackgroundColor:n,inputTextForegroundColor:r}=La(),s=t.get("remoteJid"),{instance:o}=cw(),{sendText:l}=KO(),{sendMedia:u}=WO(),{sendAudio:d}=iX(),{replyingMessage:f,setReplyingMessage:h}=y.useContext(uw),m=y.useRef(null),g=y.useRef(null),x=y.useRef(null),[b,w]=y.useState(""),[C,k]=y.useState(!1),[j,M]=y.useState(null),[_,R]=y.useState(!1),[N,O]=y.useState(null),[D,z]=y.useState(0),{t:Q}=Ve();y.useEffect(()=>{h(null),M(null)},[s,h,M]);const pe=te=>{if(w(te.target.value),m.current){m.current.style.height="auto";const de=m.current.scrollHeight,Z=parseInt(getComputedStyle(m.current).lineHeight)*10;m.current.style.height=`${Math.min(de,Z)}px`}},V=te=>{if(w(de=>de+te),m.current){m.current.style.height="auto";const de=m.current.scrollHeight,Z=parseInt(getComputedStyle(m.current).lineHeight)*10;m.current.style.height=`${Math.min(de,Z)}px`}},G=async()=>{try{R(!0);const te=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,sampleRate:44100,echoCancellation:!0,noiseSuppression:!0}});let de="";const ge=["audio/aac","audio/mp4","audio/mpeg","audio/amr","audio/ogg","audio/opus"];for(const Re of ge)if(MediaRecorder.isTypeSupported(Re)){de=Re;break}if(!de)throw new Error("Nenhum formato aceito pela Meta disponível");const Z=new MediaRecorder(te,{mimeType:de,audioBitsPerSecond:128e3});x.current=Z;const ye=[];Z.ondataavailable=Re=>{Re.data.size>0&&ye.push(Re.data)},Z.onstop=()=>{const Re=new Blob(ye,{type:de}),$e=new File([Re],`audio.${de.split("/")[1]}`,{type:de,lastModified:Date.now()});O($e)},Z.start(),g.current=setInterval(()=>{z(Re=>Re+1)},1e3)}catch(te){console.error("Erro ao iniciar gravação:",te),me.error(Q("chat.toast.recordingError")),R(!1)}},W=()=>{x.current&&(x.current.stop(),g.current&&clearInterval(g.current),R(!1))},ie=()=>{O(null),z(0)},re=te=>{console.error("Error to send message",te),me.error(rT(te)?`${Q("chat.toast.error")}: ${te?.response?.data?.response?.message}`:Q("chat.toast.sendError"))},Y=()=>{k(!1),h(null)},H=async()=>{if(!o?.name||!o?.token||!s)return;const te={instanceName:o.name,token:o.token,data:{number:s,text:b}};await l(te,{onSuccess:()=>{w(""),m.current&&(m.current.style.height="auto")},onError:re,onSettled:Y})},q=async()=>{if(!(!o?.name||!o?.token||!j||!s)){k(!0);try{const te=await new Promise((ge,Z)=>{const ye=new FileReader;ye.readAsDataURL(j),ye.onload=()=>{const $e=ye.result.split(",")[1];ge($e)},ye.onerror=Z}),de={instanceName:o.name,token:o.token,data:{number:s,mediaMessage:{mediatype:j.type.split("/")[0]==="application"?"document":j.type.split("/")[0],mimetype:j.type,caption:b,media:te,fileName:j.name}}};await u(de,{onSuccess:()=>{M(null),w(""),m.current&&(m.current.style.height="auto")},onError:re,onSettled:Y})}catch(te){console.error("Error converting media to base64:",te),re(te),k(!1)}}},he=async()=>{if(!(!o?.name||!o?.token||!N||!s)){k(!0);try{const te=await new Promise((ge,Z)=>{const ye=new FileReader;ye.readAsDataURL(N),ye.onload=()=>{const $e=ye.result.split(",")[1];ge($e)},ye.onerror=Z}),de={instanceName:o.name,token:o.token,data:{number:s,audioMessage:{audio:te}}};await d(de,{onSuccess:()=>{O(null),z(0)},onError:re,onSettled:Y})}catch(te){console.error("Error converting audio to base64:",te),re(te),k(!1)}}},A=async()=>{k(!0),j?await q():await H()},F=()=>!b&&!j?i.jsx(hte,{isSendingMessage:C,isRecording:_,audioBlob:N,elapsedTime:D,startRecording:G,stopRecording:W,clearRecording:ie,sendAudioMessage:he}):i.jsx(gte,{isSendingMessage:C,sendMessage:A}),fe=()=>_||N?F():i.jsxs(i.Fragment,{children:[i.jsx(pte,{handleEmojiClick:V}),i.jsx(JO,{instance:o,setSelectedMedia:M}),i.jsx(bi,{placeholder:Q("chat.message.placeholder"),name:"message",id:"message",rows:1,ref:m,value:b,onChange:pe,onKeyDown:te=>{!te.shiftKey&&te.key==="Enter"&&!C&&(te.preventDefault(),A())},className:"min-h-0 w-full resize-none rounded-lg border-none p-3 focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-transparent focus-visible:ring-offset-0 focus-visible:ring-offset-transparent",style:{backgroundColor:n,color:r}}),F()]});return o?i.jsxs("div",{className:"input-container",children:[j&&i.jsx(QO,{selectedMedia:j,setSelectedMedia:M}),f&&i.jsx(fte,{chat:e}),i.jsx("div",{className:`flex items-end ${(_||N)&&"justify-end"} rounded-3xl px-4 py-1`,style:{backgroundColor:n,color:r},children:fe()})]}):i.jsx("div",{className:"flex h-full items-center justify-center",children:i.jsx("p",{className:"text-muted-foreground",children:Q("chat.noInstance")||"Nenhuma instância selecionada"})})},vte=P.object({remoteJid:P.string().min(1)});function yte({onSuccess:e}){const{t}=Ve(),{primaryColor:n}=La(),r=on({resolver:an(vte),defaultValues:{remoteJid:""}}),s=o=>{e(o)};return i.jsx(Fo,{...r,children:i.jsxs("form",{onSubmit:r.handleSubmit(s),children:[i.jsx(Lo,{control:r.control,name:"remoteJid",render:({field:o})=>i.jsxs(no,{children:[i.jsx(Nr,{children:t("chat.newChat.contact")}),i.jsx(_s,{children:i.jsx(ne,{type:"text",placeholder:t("chat.newChat.placeholder"),...o})})]})}),i.jsx("div",{className:"flex justify-end",children:i.jsx(se,{type:"submit",className:"mt-4",style:{backgroundColor:n},children:t("chat.newChat.submit")})})]})})}function bte({isOpen:e,setIsOpen:t}){const[n]=hd(),{t:r}=Ve(),s=dn(),o=l=>{const u=new URLSearchParams(n);u.set("remoteJid",l.remoteJid),s(`/manager/embed-chat?${u.toString()}`),t(!1)};return i.jsx(Pt,{open:e,onOpenChange:t,children:i.jsxs(Nt,{className:"max-w-2xl",children:[i.jsxs(Mt,{children:[i.jsx(zt,{children:r("chat.newChat.title")}),i.jsx(eo,{children:r("chat.newChat.description")})]}),i.jsx(yte,{onSuccess:o})]})})}const by=e=>e?e.replace("@s.whatsapp.net","").replace("@g.us",""):"";function xte(){const[e]=hd(),{backgroundColor:t,textForegroundColor:n,primaryColor:r}=La(),s=zo("(min-width: 768px)"),{t:o}=Ve(),l=dn(),u=e.get("token"),{remoteJid:d}=ls(),f=d||e.get("remoteJid"),[h,m]=y.useState([]),g=y.useRef(null),x=y.useRef(null),[b,w]=y.useState(null),[C,k]=y.useState(!1),{instance:j}=cw(),M=R=>{const N=new URLSearchParams(e);l(`/manager/embed-chat/${encodeURIComponent(R.remoteJid||R.id)}?${N.toString()}`)};y.useEffect(()=>{if(!j?.name)return;let R=!0;return(async()=>{try{const{data:O}=await Ee.post(`/chat/findChats/${j.name}`,{where:{}},{headers:{apikey:u||j.token}});R&&m(O||[])}catch(O){R&&(console.error("Erro ao buscar chats:",O),me.error("Erro ao buscar chats"))}})(),()=>{R=!1}},[j?.name,u]),y.useEffect(()=>{if(!j)return;const R=dr(jn.API_URL);if(!R){console.error("API URL not found in localStorage");return}const N=localStorage.getItem("accessToken");u&&localStorage.setItem("accessToken",u);const O=sw(R);function D(z,Q){j&&Q.instance===j.name&&m(pe=>{const V=Q?.data?.key?.remoteJid,G=pe.findIndex(re=>re.remoteJid&&re.remoteJid===V||re.id&&re.id===V),W=G!==-1?pe[G]:null,ie={id:V,remoteJid:V,pushName:W?.pushName||Q?.data?.pushName||by(V),profilePicUrl:W?.profilePicUrl||Q?.data?.key?.profilePictureUrl||"https://as2.ftcdn.net/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.jpg",updatedAt:new Date().toISOString(),labels:W?.labels||[],createdAt:W?.createdAt||new Date().toISOString(),instanceId:j.id};if(G!==-1){const re=[...pe];return re[G]={...W,updatedAt:ie.updatedAt},re}else return[...pe,ie]})}return O.on("messages.upsert",z=>{D("messages.upsert",z)}),O.on("send.message",z=>{D("send.message",z)}),O.on("messages.update",z=>{}),O.connect(),()=>{O.off("messages.upsert"),O.off("send.message"),O.off("messages.update"),ow(O),u?localStorage.setItem("accessToken",N||""):localStorage.removeItem("accessToken")}},[j,f,u]),y.useEffect(()=>{if(f){const R=h.find(N=>N.id===f);w(R||null)}},[f,h]);const _={backgroundColor:t,color:n};return i.jsx("div",{className:"relative h-full",style:_,children:i.jsxs($o,{direction:s?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:30,minSize:20,maxSize:60,children:i.jsxs("div",{className:"hidden flex-col gap-2 text-foreground md:flex",style:_,children:[i.jsx("div",{className:"sticky top-0 p-2",children:i.jsxs(se,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",onClick:()=>k(!0),style:{backgroundColor:r,color:n},children:[i.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:i.jsx(Bl,{className:"h-4 w-4"})}),i.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:o("chat.title")}),i.jsx(cs,{className:"h-4 w-4"})]})}),i.jsxs(Yx,{defaultValue:"contacts",children:[i.jsxs(hg,{className:"tabs-chat",children:[i.jsx(Jl,{value:"contacts",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",style:{"--primary":r||"#e2e8f0","--primary-foreground":n||"#000000"},children:o("chat.contacts")}),i.jsx(Jl,{value:"groups",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",style:{"--primary":r||"#e2e8f0","--primary-foreground":n||"#000000"},children:o("chat.groups")})]}),i.jsx(Ql,{value:"contacts",children:i.jsx("div",{className:"contacts-container",children:i.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[i.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:o("chat.contacts")}),h?.sort((R,N)=>new Date(N.lastMessage.messageTimestamp).getTime()-new Date(R.lastMessage.messageTimestamp).getTime()).map(R=>R?.id&&!R.id.includes("@g.us")&&i.jsxs("div",{onClick:()=>M(R),className:"chat-item flex cursor-pointer items-center overflow-hidden rounded-md p-2 text-sm transition-colors",style:{backgroundColor:f===R.id?r:""},children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:R.profilePicUrl||"https://as2.ftcdn.net/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.jpg",alt:"Avatar",className:"h-12 w-12 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"chat-title font-medium",style:{color:n},children:R.pushName||by(R.id)}),i.jsx("span",{className:"text-xs",style:{color:n}})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("span",{className:"text-xs font-bold",style:{color:n},children:[o("chat.recent"),":"," "]}),i.jsx("span",{className:"block truncate text-xs",style:{color:n}})]})]})]},R.id))]})})}),i.jsx(Ql,{value:"groups",children:i.jsx("div",{className:"contacts-container",children:i.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[i.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:o("chat.groups")}),h?.sort((R,N)=>new Date(N.lastMessage.messageTimestamp).getTime()-new Date(R.lastMessage.messageTimestamp).getTime()).map(R=>R?.id&&R.id.includes("@g.us")&&i.jsxs("div",{onClick:()=>M(R),className:"chat-item flex cursor-pointer items-center overflow-hidden rounded-md p-2 text-sm transition-colors",style:{backgroundColor:f===R.id?r:""},children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:R.profilePicUrl||"https://as2.ftcdn.net/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.jpg",alt:"Avatar",className:"h-12 w-12 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"chat-title font-medium",children:R.pushName}),i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400"})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("span",{className:"text-xs font-bold text-gray-500 dark:text-gray-400",children:[o("chat.recent")," "]}),i.jsx("span",{className:"block truncate text-xs text-gray-500"})]})]})]},R.id))]})})})]})]})}),i.jsx(Bo,{withHandle:!0}),i.jsxs(Hn,{style:_,children:[f&&i.jsx(tte,{children:i.jsxs("div",{className:"flex h-full flex-col justify-between",style:_,children:[i.jsx("div",{className:"flex items-center gap-3 p-3",children:i.jsxs("div",{className:"flex flex-1 items-center gap-3",children:[i.jsx("img",{src:b?.profilePicUrl||"https://as2.ftcdn.net/jpg/05/89/93/27/1000_F_589932782_vQAEAZhHnq1QCGu5ikwrYaQD0Mmurm0N.jpg",alt:"Avatar",className:"h-10 w-10 rounded-full"}),i.jsx("div",{className:"flex flex-col",children:i.jsx("span",{className:"font-medium",children:b?.pushName||by(f)})})]})}),i.jsx(ZO,{textareaRef:g,handleTextareaChange:()=>{},textareaHeight:"auto",lastMessageRef:x,scrollToBottom:()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})}}),i.jsx(mte,{chat:b})]})}),i.jsx(bte,{isOpen:C,setIsOpen:k})]})]})})}function wte(){const{instance:e,isLoading:t,error:n}=cw();return t?i.jsx("div",{className:"flex h-screen items-center justify-center",children:i.jsx(On,{})}):n?i.jsx("div",{className:"flex h-screen items-center justify-center",children:i.jsx("div",{className:"rounded-md bg-red-50 p-4 dark:bg-red-900",children:i.jsx("span",{className:"text-red-800 dark:text-red-200",children:n})})}):e?i.jsx("div",{className:"h-screen",children:i.jsx(xte,{})}):null}function Sk(){return i.jsx(Yk,{client:_j,children:i.jsx(VM,{children:i.jsx(ete,{children:i.jsx(lX,{children:i.jsx(wte,{})})})})})}const Ste=e=>["evoai","fetchEvoai",JSON.stringify(e)],Cte=async({instanceName:e,token:t})=>(await Ee.get(`/evoai/find/${e}`,{headers:{apikey:t}})).data,kI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Ste({instanceName:t,token:n}),queryFn:()=>Cte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Ete=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/evoai/create/${e}`,n,{headers:{apikey:t}})).data,kte=async({instanceName:e,evoaiId:t,data:n})=>(await Ee.put(`/evoai/update/${t}/${e}`,n)).data,jte=async({instanceName:e,evoaiId:t})=>(await Ee.delete(`/evoai/delete/${t}/${e}`)).data,Tte=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/evoai/settings/${e}`,n,{headers:{apikey:t}})).data,Nte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/evoai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function xg(){const e=nt(Tte,{invalidateKeys:[["evoai","fetchDefaultSettings"]]}),t=nt(Nte,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchSessions"]]}),n=nt(jte,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchEvoai"],["evoai","fetchSessions"]]}),r=nt(kte,{invalidateKeys:[["evoai","getEvoai"],["evoai","fetchEvoai"],["evoai","fetchSessions"]]}),s=nt(Ete,{invalidateKeys:[["evoai","fetchEvoai"]]});return{setDefaultSettingsEvoai:e,changeStatusEvoai:t,deleteEvoai:n,updateEvoai:r,createEvoai:s}}const Mte=e=>["evoai","fetchDefaultSettings",JSON.stringify(e)],_te=async({instanceName:e,token:t})=>(await Ee.get(`/evoai/fetchSettings/${e}`,{headers:{apikey:t}})).data,Rte=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Mte({instanceName:t,token:n}),queryFn:()=>_te({instanceName:t,token:n}),enabled:!!t})},Pte=P.object({expire:P.string(),keywordFinish:P.string(),delayMessage:P.string(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.string(),ignoreJids:P.array(P.string()).default([]),evoaiIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean(),timePerChar:P.string()});function Ote(){const{t:e}=Ve(),{instance:t}=ct(),{setDefaultSettingsEvoai:n}=xg(),[r,s]=y.useState(!1),{data:o,refetch:l}=kI({instanceName:t?.name,token:t?.token,enabled:r}),{data:u,refetch:d}=Rte({instanceName:t?.name,token:t?.token}),f=on({resolver:an(Pte),defaultValues:{expire:"0",keywordFinish:e("evoai.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evoai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],evoaiIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});y.useEffect(()=>{u&&f.reset({expire:u?.expire?u.expire.toString():"0",keywordFinish:u.keywordFinish,delayMessage:u.delayMessage?u.delayMessage.toString():"0",unknownMessage:u.unknownMessage,listeningFromMe:u.listeningFromMe,stopBotFromMe:u.stopBotFromMe,keepOpen:u.keepOpen,debounceTime:u.debounceTime?u.debounceTime.toString():"0",ignoreJids:u.ignoreJids,evoaiIdFallback:u.evoaiIdFallback,splitMessages:u.splitMessages,timePerChar:u.timePerChar?u.timePerChar.toString():"0"})},[u]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),evoaiIdFallback:g.evoaiIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:parseInt(g.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),me.success(e("evoai.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){d(),l()}return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("evoai.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("evoai.defaultSettings")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"evoaiIdFallback",label:e("evoai.form.evoaiIdFallback.label"),options:o?.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id}))??[]}),i.jsx(le,{name:"expire",label:e("evoai.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("evoai.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("evoai.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("evoai.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("evoai.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("evoai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("evoai.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("evoai.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("evoai.form.splitMessages.label"),reverse:!0}),i.jsx(le,{name:"timePerChar",label:e("evoai.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("evoai.form.ignoreJids.label"),placeholder:e("evoai.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("evoai.button.save")})})]})})]})]})}const Ite=e=>["evoai","fetchSessions",JSON.stringify(e)],Ate=async({evoaiId:e,instanceName:t})=>(await Ee.get(`/evoai/fetchSessions/${e}/${t}`)).data,Dte=e=>{const{evoaiId:t,instanceName:n,...r}=e;return mt({...r,queryKey:Ite({evoaiId:t,instanceName:n}),queryFn:()=>Ate({evoaiId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function jI({evoaiId:e}){const{t}=Ve(),{instance:n}=ct(),{changeStatusEvoai:r}=xg(),[s,o]=y.useState([]),{data:l,refetch:u}=Dte({evoaiId:e,instanceName:n?.name}),[d,f]=y.useState(!1),[h,m]=y.useState("");function g(){u()}const x=async(w,C)=>{try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("evoai.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("evoai.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("evoai.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("evoai.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("evoai.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("evoai.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("evoai.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("evoai.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:d,onOpenChange:f,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("evoai.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("evoai.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("evoai.sessions.search"),value:h,onChange:w=>m(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{})})]}),i.jsx($a,{columns:b,data:l??[],onSortingChange:o,state:{sorting:s,globalFilter:h},onGlobalFilterChange:m,enableGlobalFilter:!0,noResultsMessage:t("evoai.sessions.table.none")})]})]})]})}const Fte=P.object({enabled:P.boolean(),description:P.string(),agentUrl:P.string(),apiKey:P.string(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function TI({initialData:e,onSubmit:t,handleDelete:n,evoaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(Fte),defaultValues:e||{enabled:!0,description:"",agentUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("evoai.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("evoai.form.description.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evoai.form.evoaiSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"agentUrl",label:d("evoai.form.agentUrl.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"apiKey",label:d("evoai.form.apiKey.label"),className:"flex-1",children:i.jsx(ne,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evoai.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("evoai.form.triggerType.label"),options:[{label:d("evoai.form.triggerType.keyword"),value:"keyword"},{label:d("evoai.form.triggerType.all"),value:"all"},{label:d("evoai.form.triggerType.advanced"),value:"advanced"},{label:d("evoai.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("evoai.form.triggerOperator.label"),options:[{label:d("evoai.form.triggerOperator.contains"),value:"contains"},{label:d("evoai.form.triggerOperator.equals"),value:"equals"},{label:d("evoai.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("evoai.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("evoai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("evoai.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("evoai.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evoai.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("evoai.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("evoai.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("evoai.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("evoai.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("evoai.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("evoai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("evoai.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("evoai.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:d("evoai.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:d("evoai.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"evoai.button.saving":"evoai.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(jI,{evoaiId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("evoai.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"evoai.button.saving":"evoai.button.update")})]})]})]})})}function Lte({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState(!1),[o,l]=y.useState(!1),{createEvoai:u}=xg(),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:f.enabled,description:f.description,agentUrl:f.agentUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar||0};await u({instanceName:n.name,token:n.token,data:h}),me.success(t("evoai.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{s(!1)}};return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("evoai.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("evoai.form.title")})}),i.jsx(TI,{onSubmit:d,isModal:!0,isLoading:r})]})]})}const $te=e=>["evoai","getEvoai",JSON.stringify(e)],Bte=async({evoaiId:e,instanceName:t})=>(await Ee.get(`/evoai/fetch/${e}/${t}`)).data,zte=e=>{const{evoaiId:t,instanceName:n,...r}=e;return mt({...r,queryKey:$te({evoaiId:t,instanceName:n}),queryFn:()=>Bte({evoaiId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function Ute({evoaiId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteEvoai:u,updateEvoai:d}=xg(),{data:f,isLoading:h}=zte({evoaiId:e,instanceName:r?.name}),m=y.useMemo(()=>({enabled:!!f?.enabled,description:f?.description??"",agentUrl:f?.agentUrl??"",apiKey:f?.apiKey??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue??"",expire:f?.expire??0,keywordFinish:f?.keywordFinish??"",delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage??"",listeningFromMe:!!f?.listeningFromMe,stopBotFromMe:!!f?.stopBotFromMe,keepOpen:!!f?.keepOpen,debounceTime:f?.debounceTime??0,splitMessages:f?.splitMessages??!1,timePerChar:f?.timePerChar??0}),[f?.agentUrl,f?.apiKey,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,agentUrl:b.agentUrl,apiKey:b.apiKey,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar||0};await d({instanceName:r.name,evoaiId:e,data:w}),me.success(n("evoai.toast.success.update")),t(),s(`/manager/instance/${r.id}/evoai/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,evoaiId:e}),me.success(n("evoai.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/evoai`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir evoai:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(TI,{initialData:m,onSubmit:g,evoaiId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function Ck(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{evoaiId:r}=ls(),{data:s,refetch:o,isLoading:l}=kI({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/evoai/${h}`)},f=()=>{o()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("evoai.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(jI,{}),i.jsx(Ote,{}),i.jsx(Lte,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:l?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsx(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:h.description||h.id})},h.id)):i.jsx(se,{variant:"link",children:e("evoai.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(Ute,{evoaiId:r,resetTable:f})})]})]})]})}const Vte=e=>["evolutionBot","findEvolutionBot",JSON.stringify(e)],Hte=async({instanceName:e,token:t})=>(await Ee.get(`/evolutionBot/find/${e}`,{headers:{apiKey:t}})).data,NI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Vte({instanceName:t}),queryFn:()=>Hte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},qte=e=>["evolutionBot","fetchDefaultSettings",JSON.stringify(e)],Kte=async({instanceName:e,token:t})=>{const n=await Ee.get(`/evolutionBot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},Wte=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:qte({instanceName:t}),queryFn:()=>Kte({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},Gte=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/evolutionBot/create/${e}`,n,{headers:{apikey:t}})).data,Jte=async({instanceName:e,token:t,evolutionBotId:n,data:r})=>(await Ee.put(`/evolutionBot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,Qte=async({instanceName:e,evolutionBotId:t})=>(await Ee.delete(`/evolutionBot/delete/${t}/${e}`)).data,Zte=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/evolutionBot/settings/${e}`,n,{headers:{apikey:t}})).data,Yte=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/evolutionBot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function wg(){const e=nt(Zte,{invalidateKeys:[["evolutionBot","fetchDefaultSettings"]]}),t=nt(Yte,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","fetchSessions"]]}),n=nt(Qte,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),r=nt(Jte,{invalidateKeys:[["evolutionBot","getEvolutionBot"],["evolutionBot","findEvolutionBot"],["evolutionBot","fetchSessions"]]}),s=nt(Gte,{invalidateKeys:[["evolutionBot","findEvolutionBot"]]});return{setDefaultSettingsEvolutionBot:e,changeStatusEvolutionBot:t,deleteEvolutionBot:n,updateEvolutionBot:r,createEvolutionBot:s}}const Xte=P.object({expire:P.string(),keywordFinish:P.string(),delayMessage:P.string(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.string(),ignoreJids:P.array(P.string()).default([]),botIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean(),timePerChar:P.string()});function ene(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{data:s,refetch:o}=Wte({instanceName:t?.name,enabled:n}),{data:l,refetch:u}=NI({instanceName:t?.name,enabled:n}),{setDefaultSettingsEvolutionBot:d}=wg(),f=on({resolver:an(Xte),defaultValues:{expire:"0",keywordFinish:e("evolutionBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("evolutionBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});y.useEffect(()=>{s&&f.reset({expire:s?.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback,splitMessages:s.splitMessages,timePerChar:s.timePerChar?s.timePerChar.toString():"0"})},[s]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),botIdFallback:g.botIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:parseInt(g.timePerChar)};await d({instanceName:t.name,token:t.token,data:x}),me.success(e("evolutionBot.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){o(),u()}return i.jsxs(Pt,{open:n,onOpenChange:r,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("evolutionBot.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("evolutionBot.defaultSettings")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"botIdFallback",label:e("evolutionBot.form.botIdFallback.label"),options:l?.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id}))??[]}),i.jsx(le,{name:"expire",label:e("evolutionBot.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("evolutionBot.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("evolutionBot.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("evolutionBot.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("evolutionBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("evolutionBot.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("evolutionBot.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("evolutionBot.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:e("evolutionBot.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("evolutionBot.form.ignoreJids.label"),placeholder:e("evolutionBot.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("evolutionBot.button.save")})})]})})]})]})}const tne=e=>["evolutionBot","fetchSessions",JSON.stringify(e)],nne=async({instanceName:e,evolutionBotId:t,token:n})=>(await Ee.get(`/evolutionBot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,rne=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return mt({...s,queryKey:tne({instanceName:t}),queryFn:()=>nne({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function MI({evolutionBotId:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState([]),[o,l]=y.useState(!1),[u,d]=y.useState(""),{data:f,refetch:h}=rne({instanceName:n?.name,evolutionBotId:e,enabled:o}),{changeStatusEvolutionBot:m}=wg();function g(){h()}const x=async(w,C)=>{try{if(!n)return;await m({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("evolutionBot.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("evolutionBot.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("evolutionBot.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("evolutionBot.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("evolutionBot.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("evolutionBot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("evolutionBot.sessions.search"),value:u,onChange:w=>d(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{})})]}),i.jsx($a,{columns:b,data:f??[],onSortingChange:s,state:{sorting:r,globalFilter:u},onGlobalFilterChange:d,enableGlobalFilter:!0,noResultsMessage:t("evolutionBot.sessions.table.none")})]})]})]})}const sne=P.object({enabled:P.boolean(),description:P.string(),apiUrl:P.string(),apiKey:P.string().optional(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function _I({initialData:e,onSubmit:t,handleDelete:n,evolutionBotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(sne),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("evolutionBot.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("evolutionBot.form.description.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evolutionBot.form.evolutionBotSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"apiUrl",label:d("evolutionBot.form.apiUrl.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"apiKey",label:d("evolutionBot.form.apiKey.label"),children:i.jsx(ne,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evolutionBot.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("evolutionBot.form.triggerType.label"),options:[{label:d("evolutionBot.form.triggerType.keyword"),value:"keyword"},{label:d("evolutionBot.form.triggerType.all"),value:"all"},{label:d("evolutionBot.form.triggerType.advanced"),value:"advanced"},{label:d("evolutionBot.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("evolutionBot.form.triggerOperator.label"),options:[{label:d("evolutionBot.form.triggerOperator.contains"),value:"contains"},{label:d("evolutionBot.form.triggerOperator.equals"),value:"equals"},{label:d("evolutionBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("evolutionBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("evolutionBot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("evolutionBot.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("evolutionBot.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("evolutionBot.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("evolutionBot.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("evolutionBot.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("evolutionBot.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("evolutionBot.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("evolutionBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("evolutionBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("evolutionBot.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("evolutionBot.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:d("evolutionBot.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:d("evolutionBot.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"evolutionBot.button.saving":"evolutionBot.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(MI,{evolutionBotId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("dify.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"evolutionBot.button.saving":"evolutionBot.button.update")})]})]})]})})}function one({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState(!1),[o,l]=y.useState(!1),{createEvolutionBot:u}=wg(),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar?f.timePerChar:0};await u({instanceName:n.name,token:n.token,data:h}),me.success(t("evolutionBot.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{s(!1)}};return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("evolutionBot.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("evolutionBot.form.title")})}),i.jsx(_I,{onSubmit:d,isModal:!0,isLoading:r})]})]})}const ane=e=>["evolutionBot","getEvolutionBot",JSON.stringify(e)],ine=async({instanceName:e,token:t,evolutionBotId:n})=>{const r=await Ee.get(`/evolutionBot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},lne=e=>{const{instanceName:t,token:n,evolutionBotId:r,...s}=e;return mt({...s,queryKey:ane({instanceName:t}),queryFn:()=>ine({instanceName:t,token:n,evolutionBotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function cne({evolutionBotId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteEvolutionBot:u,updateEvolutionBot:d}=wg(),{data:f,isLoading:h}=lne({instanceName:r?.name,evolutionBotId:e}),m=y.useMemo(()=>({enabled:f?.enabled??!0,description:f?.description??"",apiUrl:f?.apiUrl??"",apiKey:f?.apiKey??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue,expire:f?.expire??0,keywordFinish:f?.keywordFinish,delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage,listeningFromMe:f?.listeningFromMe,stopBotFromMe:!!f?.stopBotFromMe,keepOpen:!!f?.keepOpen,debounceTime:f?.debounceTime??0,splitMessages:f?.splitMessages??!1,timePerChar:f?.timePerChar?f?.timePerChar:0}),[f?.apiKey,f?.apiUrl,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,apiUrl:b.apiUrl,apiKey:b.apiKey,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar?b.timePerChar:0};await d({instanceName:r.name,evolutionBotId:e,data:w}),me.success(n("evolutionBot.toast.success.update")),t(),s(`/manager/instance/${r.id}/evolutionBot/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,evolutionBotId:e}),me.success(n("evolutionBot.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/evolutionBot`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir evolutionBot:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(_I,{initialData:m,onSubmit:g,evolutionBotId:e,handleDelete:x,isModal:!1,openDeletionDialog:o,setOpenDeletionDialog:l})})}function Ek(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{evolutionBotId:r}=ls(),{data:s,isLoading:o,refetch:l}=NI({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/evolutionBot/${h}`)},f=()=>{l()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("evolutionBot.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(MI,{}),i.jsx(ene,{}),i.jsx(one,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:o?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsx(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:h.description||h.id})},h.id)):i.jsx(se,{variant:"link",children:e("evolutionBot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(cne,{evolutionBotId:r,resetTable:f})})]})]})]})}const une=e=>["flowise","findFlowise",JSON.stringify(e)],dne=async({instanceName:e,token:t})=>(await Ee.get(`/flowise/find/${e}`,{headers:{apiKey:t}})).data,RI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:une({instanceName:t}),queryFn:()=>dne({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},fne=e=>["flowise","fetchDefaultSettings",JSON.stringify(e)],pne=async({instanceName:e,token:t})=>{const n=await Ee.get(`/flowise/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},hne=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:fne({instanceName:t}),queryFn:()=>pne({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},gne=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,mne=async({instanceName:e,flowiseId:t,data:n})=>(await Ee.put(`/flowise/update/${t}/${e}`,n)).data,vne=async({instanceName:e,flowiseId:t})=>(await Ee.delete(`/flowise/delete/${t}/${e}`)).data,yne=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,bne=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data;function Sg(){const e=nt(bne,{invalidateKeys:[["flowise","fetchDefaultSettings"]]}),t=nt(yne,{invalidateKeys:[["flowise","getFlowise"],["flowise","fetchSessions"]]}),n=nt(vne,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),r=nt(mne,{invalidateKeys:[["flowise","getFlowise"],["flowise","findFlowise"],["flowise","fetchSessions"]]}),s=nt(gne,{invalidateKeys:[["flowise","findFlowise"]]});return{setDefaultSettingsFlowise:e,changeStatusFlowise:t,deleteFlowise:n,updateFlowise:r,createFlowise:s}}const xne=P.object({expire:P.string(),keywordFinish:P.string(),delayMessage:P.string(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.string(),ignoreJids:P.array(P.string()).default([]),flowiseIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean(),timePerChar:P.string()});function wne(){const{t:e}=Ve(),{instance:t}=ct(),{setDefaultSettingsFlowise:n}=Sg(),[r,s]=y.useState(!1),{data:o,refetch:l}=hne({instanceName:t?.name,enabled:r}),{data:u,refetch:d}=RI({instanceName:t?.name,enabled:r}),f=on({resolver:an(xne),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});y.useEffect(()=>{o&&f.reset({expire:o?.expire?o.expire.toString():"0",keywordFinish:o.keywordFinish,delayMessage:o.delayMessage?o.delayMessage.toString():"0",unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime?o.debounceTime.toString():"0",ignoreJids:o.ignoreJids,flowiseIdFallback:o.flowiseIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar?o.timePerChar.toString():"0"})},[o]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),flowiseIdFallback:g.flowiseIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:parseInt(g.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),me.success(e("flowise.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){l(),d()}return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("flowise.defaultSettings")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:u?.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id}))??[]}),i.jsx(le,{name:"expire",label:e("flowise.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("flowise.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:e("flowise.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const Sne=e=>["flowise","fetchSessions",JSON.stringify(e)],Cne=async({instanceName:e,flowiseId:t,token:n})=>(await Ee.get(`/flowise/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,Ene=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return mt({...s,queryKey:Sne({instanceName:t}),queryFn:()=>Cne({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function PI({flowiseId:e}){const{t}=Ve(),{instance:n}=ct(),{changeStatusFlowise:r}=Sg(),[s,o]=y.useState([]),[l,u]=y.useState(!1),[d,f]=y.useState(""),{data:h,refetch:m}=Ene({instanceName:n?.name,flowiseId:e,enabled:l});function g(){m()}const x=async(w,C)=>{try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("flowise.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("flowise.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("flowise.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("flowise.sessions.search"),value:d,onChange:w=>f(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{})})]}),i.jsx($a,{columns:b,data:h??[],onSortingChange:o,state:{sorting:s,globalFilter:d},onGlobalFilterChange:f,enableGlobalFilter:!0,noResultsMessage:t("flowise.sessions.table.none")})]})]})]})}const kne=P.object({enabled:P.boolean(),description:P.string(),apiUrl:P.string(),apiKey:P.string().optional(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function OI({initialData:e,onSubmit:t,handleDelete:n,flowiseId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(kne),defaultValues:e||{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("flowise.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("flowise.form.description.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("flowise.form.flowiseSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"apiUrl",label:d("flowise.form.apiUrl.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"apiKey",label:d("flowise.form.apiKey.label"),children:i.jsx(ne,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("flowise.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("flowise.form.triggerType.label"),options:[{label:d("flowise.form.triggerType.keyword"),value:"keyword"},{label:d("flowise.form.triggerType.all"),value:"all"},{label:d("flowise.form.triggerType.advanced"),value:"advanced"},{label:d("flowise.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("flowise.form.triggerOperator.label"),options:[{label:d("flowise.form.triggerOperator.contains"),value:"contains"},{label:d("flowise.form.triggerOperator.equals"),value:"equals"},{label:d("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("flowise.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("flowise.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("flowise.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("flowise.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("flowise.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("flowise.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("flowise.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("flowise.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("flowise.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:d("flowise.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:d("flowise.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"flowise.button.saving":"flowise.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(PI,{flowiseId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("dify.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"flowise.button.saving":"flowise.button.update")})]})]})]})})}function jne({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),{createFlowise:r}=Sg(),[s,o]=y.useState(!1),[l,u]=y.useState(!1),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),me.success(t("flowise.toast.success.create")),u(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{o(!1)}};return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("flowise.form.title")})}),i.jsx(OI,{onSubmit:d,isModal:!0,isLoading:s})]})]})}const Tne=e=>["flowise","getFlowise",JSON.stringify(e)],Nne=async({instanceName:e,token:t,flowiseId:n})=>{const r=await Ee.get(`/flowise/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},Mne=e=>{const{instanceName:t,token:n,flowiseId:r,...s}=e;return mt({...s,queryKey:Tne({instanceName:t}),queryFn:()=>Nne({instanceName:t,token:n,flowiseId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function _ne({flowiseId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteFlowise:u,updateFlowise:d}=Sg(),{data:f,isLoading:h}=Mne({instanceName:r?.name,flowiseId:e}),m=y.useMemo(()=>({enabled:f?.enabled??!0,description:f?.description??"",apiUrl:f?.apiUrl??"",apiKey:f?.apiKey??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue,expire:f?.expire??0,keywordFinish:f?.keywordFinish,delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage,listeningFromMe:f?.listeningFromMe,stopBotFromMe:f?.stopBotFromMe,keepOpen:f?.keepOpen,debounceTime:f?.debounceTime??0,splitMessages:f?.splitMessages??!1,timePerChar:f?.timePerChar??0}),[f?.apiKey,f?.apiUrl,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,apiUrl:b.apiUrl,apiKey:b.apiKey,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar||0};await d({instanceName:r.name,flowiseId:e,data:w}),me.success(n("flowise.toast.success.update")),t(),s(`/manager/instance/${r.id}/flowise/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,flowiseId:e}),me.success(n("flowise.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/flowise`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir dify:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(OI,{initialData:m,onSubmit:g,flowiseId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function kk(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{flowiseId:r}=ls(),{data:s,isLoading:o,refetch:l}=RI({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/flowise/${h}`)},f=()=>{l()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(PI,{}),i.jsx(wne,{}),i.jsx(jne,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:o?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsx(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:h.description||h.id})},h.id)):i.jsx(se,{variant:"link",children:e("flowise.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(_ne,{flowiseId:r,resetTable:f})})]})]})]})}const Rne=e=>["n8n","fetchN8n",JSON.stringify(e)],Pne=async({instanceName:e,token:t})=>(await Ee.get(`/n8n/find/${e}`,{headers:{apikey:t}})).data,II=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Rne({instanceName:t,token:n}),queryFn:()=>Pne({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},One=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/n8n/create/${e}`,n,{headers:{apikey:t}})).data,Ine=async({instanceName:e,n8nId:t,data:n})=>(await Ee.put(`/n8n/update/${t}/${e}`,n)).data,Ane=async({instanceName:e,n8nId:t})=>(await Ee.delete(`/n8n/delete/${t}/${e}`)).data,Dne=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/n8n/settings/${e}`,n,{headers:{apikey:t}})).data,Fne=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/n8n/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Cg(){const e=nt(Dne,{invalidateKeys:[["n8n","fetchDefaultSettings"]]}),t=nt(Fne,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchSessions"]]}),n=nt(Ane,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchN8n"],["n8n","fetchSessions"]]}),r=nt(Ine,{invalidateKeys:[["n8n","getN8n"],["n8n","fetchN8n"],["n8n","fetchSessions"]]}),s=nt(One,{invalidateKeys:[["n8n","fetchN8n"]]});return{setDefaultSettingsN8n:e,changeStatusN8n:t,deleteN8n:n,updateN8n:r,createN8n:s}}const Lne=e=>["n8n","fetchDefaultSettings",JSON.stringify(e)],$ne=async({instanceName:e,token:t})=>(await Ee.get(`/n8n/fetchSettings/${e}`,{headers:{apikey:t}})).data,Bne=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Lne({instanceName:t,token:n}),queryFn:()=>$ne({instanceName:t,token:n}),enabled:!!t})},zne=P.object({expire:P.string(),keywordFinish:P.string(),delayMessage:P.string(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.string(),ignoreJids:P.array(P.string()).default([]),n8nIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean(),timePerChar:P.string()});function Une(){const{t:e}=Ve(),{instance:t}=ct(),{setDefaultSettingsN8n:n}=Cg(),[r,s]=y.useState(!1),{data:o,refetch:l}=II({instanceName:t?.name,token:t?.token,enabled:r}),{data:u,refetch:d}=Bne({instanceName:t?.name,token:t?.token}),f=on({resolver:an(zne),defaultValues:{expire:"0",keywordFinish:e("n8n.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("n8n.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],n8nIdFallback:void 0,splitMessages:!1,timePerChar:"0"}});y.useEffect(()=>{u&&f.reset({expire:u?.expire?u.expire.toString():"0",keywordFinish:u.keywordFinish,delayMessage:u.delayMessage?u.delayMessage.toString():"0",unknownMessage:u.unknownMessage,listeningFromMe:u.listeningFromMe,stopBotFromMe:u.stopBotFromMe,keepOpen:u.keepOpen,debounceTime:u.debounceTime?u.debounceTime.toString():"0",ignoreJids:u.ignoreJids,n8nIdFallback:u.n8nIdFallback,splitMessages:u.splitMessages,timePerChar:u.timePerChar?u.timePerChar.toString():"0"})},[u]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:parseInt(g.expire),keywordFinish:g.keywordFinish,delayMessage:parseInt(g.delayMessage),unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:parseInt(g.debounceTime),n8nIdFallback:g.n8nIdFallback||void 0,ignoreJids:g.ignoreJids,splitMessages:g.splitMessages,timePerChar:parseInt(g.timePerChar)};await n({instanceName:t.name,token:t.token,data:x}),me.success(e("n8n.toast.defaultSettings.success"))}catch(x){console.error("Error:",x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){d(),l()}return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("n8n.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("n8n.defaultSettings")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"n8nIdFallback",label:e("n8n.form.n8nIdFallback.label"),options:o?.filter(g=>!!g.id).map(g=>({label:g.description,value:g.id}))??[]}),i.jsx(le,{name:"expire",label:e("n8n.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("n8n.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("n8n.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("n8n.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("n8n.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("n8n.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("n8n.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("n8n.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("n8n.form.splitMessages.label"),reverse:!0}),i.jsx(le,{name:"timePerChar",label:e("n8n.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("n8n.form.ignoreJids.label"),placeholder:e("n8n.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("n8n.button.save")})})]})})]})]})}const Vne=e=>["n8n","fetchSessions",JSON.stringify(e)],Hne=async({n8nId:e,instanceName:t})=>(await Ee.get(`/n8n/fetchSessions/${e}/${t}`)).data,qne=e=>{const{n8nId:t,instanceName:n,...r}=e;return mt({...r,queryKey:Vne({n8nId:t,instanceName:n}),queryFn:()=>Hne({n8nId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0),staleTime:1e3*10})};function AI({n8nId:e}){const{t}=Ve(),{instance:n}=ct(),{changeStatusN8n:r}=Cg(),[s,o]=y.useState([]),{data:l,refetch:u}=qne({n8nId:e,instanceName:n?.name}),[d,f]=y.useState(!1),[h,m]=y.useState("");function g(){u()}const x=async(w,C)=>{try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("n8n.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("n8n.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("n8n.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("n8n.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("n8n.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("n8n.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("n8n.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("n8n.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:d,onOpenChange:f,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("n8n.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("n8n.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("n8n.sessions.search"),value:h,onChange:w=>m(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{})})]}),i.jsx($a,{columns:b,data:l??[],onSortingChange:o,state:{sorting:s,globalFilter:h},onGlobalFilterChange:m,enableGlobalFilter:!0,noResultsMessage:t("n8n.sessions.table.none")})]})]})]})}const Kne=P.object({enabled:P.boolean(),description:P.string(),webhookUrl:P.string(),basicAuthUser:P.string(),basicAuthPass:P.string(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function DI({initialData:e,onSubmit:t,handleDelete:n,n8nId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(Kne),defaultValues:e||{enabled:!0,description:"",webhookUrl:"",basicAuthUser:"",basicAuthPass:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("n8n.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("n8n.form.description.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("n8n.form.n8nSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"webhookUrl",label:d("n8n.form.webhookUrl.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("n8n.form.basicAuth.label")}),i.jsx($t,{})]}),i.jsxs("div",{className:"flex w-full flex-row gap-4",children:[i.jsx(le,{name:"basicAuthUser",label:d("n8n.form.basicAuthUser.label"),className:"flex-1",children:i.jsx(ne,{})}),i.jsx(le,{name:"basicAuthPass",label:d("n8n.form.basicAuthPass.label"),className:"flex-1",children:i.jsx(ne,{type:"password"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("n8n.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("n8n.form.triggerType.label"),options:[{label:d("n8n.form.triggerType.keyword"),value:"keyword"},{label:d("n8n.form.triggerType.all"),value:"all"},{label:d("n8n.form.triggerType.advanced"),value:"advanced"},{label:d("n8n.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("n8n.form.triggerOperator.label"),options:[{label:d("n8n.form.triggerOperator.contains"),value:"contains"},{label:d("n8n.form.triggerOperator.equals"),value:"equals"},{label:d("n8n.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("n8n.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("n8n.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("n8n.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("n8n.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("n8n.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("n8n.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("n8n.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("n8n.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("n8n.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("n8n.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("n8n.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("n8n.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("n8n.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:d("n8n.form.splitMessages.label"),reverse:!0}),f.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:d("n8n.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"n8n.button.saving":"n8n.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(AI,{n8nId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("n8n.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"n8n.button.saving":"n8n.button.update")})]})]})]})})}function Wne({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState(!1),[o,l]=y.useState(!1),{createN8n:u}=Cg(),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");s(!0);const h={enabled:f.enabled,description:f.description,webhookUrl:f.webhookUrl,basicAuthUser:f.basicAuthUser,basicAuthPass:f.basicAuthPass,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar||0};await u({instanceName:n.name,token:n.token,data:h}),me.success(t("n8n.toast.success.create")),l(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{s(!1)}};return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("n8n.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("n8n.form.title")})}),i.jsx(DI,{onSubmit:d,isModal:!0,isLoading:r})]})]})}const Gne=e=>["n8n","getN8n",JSON.stringify(e)],Jne=async({n8nId:e,instanceName:t})=>(await Ee.get(`/n8n/fetch/${e}/${t}`)).data,Qne=e=>{const{n8nId:t,instanceName:n,...r}=e;return mt({...r,queryKey:Gne({n8nId:t,instanceName:n}),queryFn:()=>Jne({n8nId:t,instanceName:n}),enabled:!!n&&!!t&&(e.enabled??!0)})};function Zne({n8nId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteN8n:u,updateN8n:d}=Cg(),{data:f,isLoading:h}=Qne({n8nId:e,instanceName:r?.name}),m=y.useMemo(()=>({enabled:!!f?.enabled,description:f?.description??"",webhookUrl:f?.webhookUrl??"",basicAuthUser:f?.basicAuthUser??"",basicAuthPass:f?.basicAuthPass??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue??"",expire:f?.expire??0,keywordFinish:f?.keywordFinish??"",delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage??"",listeningFromMe:!!f?.listeningFromMe,stopBotFromMe:!!f?.stopBotFromMe,keepOpen:!!f?.keepOpen,debounceTime:f?.debounceTime??0,splitMessages:f?.splitMessages??!1,timePerChar:f?.timePerChar??0}),[f?.webhookUrl,f?.basicAuthUser,f?.basicAuthPass,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,webhookUrl:b.webhookUrl,basicAuthUser:b.basicAuthUser,basicAuthPass:b.basicAuthPass,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar||0};await d({instanceName:r.name,n8nId:e,data:w}),me.success(n("n8n.toast.success.update")),t(),s(`/manager/instance/${r.id}/n8n/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,n8nId:e}),me.success(n("n8n.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/n8n`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir n8n:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(DI,{initialData:m,onSubmit:g,n8nId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function jk(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{n8nId:r}=ls(),{data:s,refetch:o,isLoading:l}=II({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/n8n/${h}`)},f=()=>{o()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("n8n.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(AI,{}),i.jsx(Une,{}),i.jsx(Wne,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:l?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsx(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:h.description||h.id})},h.id)):i.jsx(se,{variant:"link",children:e("n8n.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(Zne,{n8nId:r,resetTable:f})})]})]})]})}const Yne=e=>["openai","findOpenai",JSON.stringify(e)],Xne=async({instanceName:e,token:t})=>(await Ee.get(`/openai/find/${e}`,{headers:{apiKey:t}})).data,FI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Yne({instanceName:t}),queryFn:()=>Xne({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},ere=e=>["openai","findOpenaiCreds",JSON.stringify(e)],tre=async({instanceName:e,token:t})=>(await Ee.get(`/openai/creds/${e}`,{headers:{apiKey:t}})).data,dw=e=>{const{instanceName:t,token:n,...r}=e;return mt({staleTime:1e3*60*60*6,...r,queryKey:ere({instanceName:t}),queryFn:()=>tre({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},nre=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,rre=async({openaiCredsId:e,instanceName:t})=>(await Ee.delete(`/openai/creds/${e}/${t}`)).data,sre=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,ore=async({instanceName:e,token:t,openaiId:n,data:r})=>(await Ee.put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,are=async({instanceName:e,token:t,openaiId:n})=>(await Ee.delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,ire=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,lre=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Md(){const e=nt(ire,{invalidateKeys:[["openai","fetchDefaultSettings"]]}),t=nt(lre,{invalidateKeys:[["openai","getOpenai"],["openai","fetchSessions"]]}),n=nt(are,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),r=nt(ore,{invalidateKeys:[["openai","getOpenai"],["openai","findOpenai"],["openai","fetchSessions"]]}),s=nt(sre,{invalidateKeys:[["openai","findOpenai"]]}),o=nt(nre,{invalidateKeys:[["openai","findOpenaiCreds"]]}),l=nt(rre,{invalidateKeys:[["openai","findOpenaiCreds"]]});return{setDefaultSettingsOpenai:e,changeStatusOpenai:t,deleteOpenai:n,updateOpenai:r,createOpenai:s,createOpenaiCreds:o,deleteOpenaiCreds:l}}const cre=P.object({name:P.string(),apiKey:P.string()});function LI({onCredentialsUpdate:e,showText:t=!0}){const{t:n}=Ve(),{instance:r}=ct(),{createOpenaiCreds:s,deleteOpenaiCreds:o}=Md(),[l,u]=y.useState(!1),[d,f]=y.useState([]),{data:h}=dw({instanceName:r?.name,enabled:l}),m=on({resolver:an(cre),defaultValues:{name:"",apiKey:""}}),g=async w=>{try{if(!r||!r.name)throw new Error("instance not found.");const C={name:w.name,apiKey:w.apiKey};await s({instanceName:r.name,token:r.token,data:C}),me.success(n("openai.toast.success.credentialsCreate")),m.reset(),e&&e()}catch(C){console.error("Error:",C),me.error(`Error: ${C?.response?.data?.response?.message}`)}},x=async w=>{if(!r?.name){me.error("Instance not found.");return}try{await o({openaiCredsId:w,instanceName:r?.name}),me.success(n("openai.toast.success.credentialsDelete")),e&&e()}catch(C){console.error("Error:",C),me.error(`Error: ${C?.response?.data?.response?.message}`)}},b=[{accessorKey:"name",header:({column:w})=>i.jsxs(se,{variant:"ghost",onClick:()=>w.toggleSorting(w.getIsSorted()==="asc"),children:[n("openai.credentials.table.name"),i.jsx(q$,{className:"ml-2 h-4 w-4"})]}),cell:({row:w})=>i.jsx("div",{children:w.getValue("name")})},{accessorKey:"apiKey",header:()=>i.jsx("div",{className:"text-right",children:n("openai.credentials.table.apiKey")}),cell:({row:w})=>i.jsxs("div",{children:[`${w.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:n("openai.credentials.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:n("openai.credentials.table.actions.title")}),i.jsx(Xs,{}),i.jsx(wt,{onClick:()=>x(C.id),children:n("openai.credentials.table.actions.delete")})]})]})}}];return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"secondary",size:"sm",type:"button",children:t?i.jsxs(i.Fragment,{children:[i.jsx(mB,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:n("openai.credentials.title")})]}):i.jsx(cs,{size:16})})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:n("openai.credentials.title")})}),i.jsx(Gn,{...m,children:i.jsx("div",{onClick:w=>w.stopPropagation(),onSubmit:w=>w.stopPropagation(),onKeyDown:w=>w.stopPropagation(),children:i.jsxs("form",{onSubmit:w=>{w.preventDefault(),w.stopPropagation(),m.handleSubmit(g)(w)},className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[i.jsx(le,{name:"name",label:n("openai.credentials.table.name"),children:i.jsx(ne,{})}),i.jsx(le,{name:"apiKey",label:n("openai.credentials.table.apiKey"),children:i.jsx(ne,{type:"password"})})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:n("openai.button.save")})})]})})}),i.jsx($t,{}),i.jsx("div",{children:i.jsx($a,{columns:b,data:h??[],onSortingChange:f,state:{sorting:d},noResultsMessage:n("openai.credentials.table.none")})})]})]})}const ure=e=>["openai","fetchDefaultSettings",JSON.stringify(e)],dre=async({instanceName:e,token:t})=>{const n=await Ee.get(`/openai/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},fre=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:ure({instanceName:t}),queryFn:()=>dre({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},pre=P.object({openaiCredsId:P.string(),expire:P.coerce.number(),keywordFinish:P.string(),delayMessage:P.coerce.number().default(0),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.coerce.number(),speechToText:P.boolean(),ignoreJids:P.array(P.string()).default([]),openaiIdFallback:P.union([P.null(),P.string()]).optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function hre(){const{t:e}=Ve(),{instance:t}=ct(),{setDefaultSettingsOpenai:n}=Md(),[r,s]=y.useState(!1),{data:o,refetch:l}=fre({instanceName:t?.name,enabled:r}),{data:u,refetch:d}=FI({instanceName:t?.name,enabled:r}),{data:f}=dw({instanceName:t?.name,enabled:r}),h=on({resolver:an(pre),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0,splitMessages:!1,timePerChar:0}});y.useEffect(()=>{o&&h.reset({openaiCredsId:o.openaiCredsId,expire:o?.expire??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0,speechToText:o.speechToText,ignoreJids:o.ignoreJids,openaiIdFallback:o.openaiIdFallback,splitMessages:o.splitMessages,timePerChar:o.timePerChar??0})},[o]);const m=async x=>{try{if(!t||!t.name)throw new Error("instance not found.");const b={openaiCredsId:x.openaiCredsId,expire:x.expire,keywordFinish:x.keywordFinish,delayMessage:x.delayMessage,unknownMessage:x.unknownMessage,listeningFromMe:x.listeningFromMe,stopBotFromMe:x.stopBotFromMe,keepOpen:x.keepOpen,debounceTime:x.debounceTime,speechToText:x.speechToText,openaiIdFallback:x.openaiIdFallback||void 0,ignoreJids:x.ignoreJids,splitMessages:x.splitMessages,timePerChar:x.timePerChar};await n({instanceName:t.name,token:t.token,data:b}),me.success(e("openai.toast.defaultSettings.success"))}catch(b){console.error("Error:",b),me.error(`Error: ${b?.response?.data?.response?.message}`)}};function g(){l(),d()}return i.jsxs(Pt,{open:r,onOpenChange:s,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("openai.defaultSettings")})}),i.jsx(Gn,{...h,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:h.handleSubmit(m),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:f?.filter(x=>!!x.id).map(x=>({label:x.name?x.name:x.apiKey.substring(0,15)+"...",value:x.id}))||[]}),i.jsx(Jt,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:u?.filter(x=>!!x.id).map(x=>({label:x.description,value:x.id}))??[]}),i.jsx(le,{name:"expire",label:e("openai.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),i.jsx(Pe,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:e("openai.form.splitMessages.label"),reverse:!0}),h.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:e("openai.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const gre=e=>["openai","getModels",JSON.stringify(e)],mre=async({instanceName:e,openaiCredsId:t,token:n})=>{const r=t?{openaiCredsId:t}:{};return(await Ee.get(`/openai/getModels/${e}`,{headers:{apiKey:n},params:r})).data},vre=e=>{const{instanceName:t,openaiCredsId:n,token:r,...s}=e;return mt({staleTime:1e3*60*60*6,...s,queryKey:gre({instanceName:t,openaiCredsId:n}),queryFn:()=>mre({instanceName:t,openaiCredsId:n,token:r}),enabled:!!t&&!!n&&(e.enabled??!0)})},yre=e=>["openai","fetchSessions",JSON.stringify(e)],bre=async({instanceName:e,openaiId:t,token:n})=>(await Ee.get(`/openai/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,xre=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return mt({...s,queryKey:yre({instanceName:t}),queryFn:()=>bre({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function $I({openaiId:e}){const{t}=Ve(),{instance:n}=ct(),{changeStatusOpenai:r}=Md(),[s,o]=y.useState([]),[l,u]=y.useState(!1),{data:d,refetch:f}=xre({instanceName:n?.name,openaiId:e,enabled:l}),[h,m]=y.useState("");function g(){f()}const x=async(w,C)=>{try{if(!n)return;await r({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("openai.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",size:"icon",children:[i.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:t("openai.sessions.table.actions.title")}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("openai.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("openai.sessions.search"),value:h,onChange:w=>m(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{size:16})})]}),i.jsx($a,{columns:b,data:d??[],onSortingChange:o,state:{sorting:s,globalFilter:h},onGlobalFilterChange:m,enableGlobalFilter:!0,noResultsMessage:t("openai.sessions.table.none")})]})]})]})}const wre=P.object({enabled:P.boolean(),description:P.string(),openaiCredsId:P.string(),botType:P.string(),assistantId:P.string().optional(),functionUrl:P.string().optional(),model:P.string().optional(),systemMessages:P.string().optional(),assistantMessages:P.string().optional(),userMessages:P.string().optional(),maxTokens:P.coerce.number().optional(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional(),splitMessages:P.boolean().optional(),timePerChar:P.coerce.number().optional()});function BI({initialData:e,onSubmit:t,handleDelete:n,openaiId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{},open:d}){const{t:f}=Ve(),{instance:h}=ct(),[m,g]=y.useState(!1),{data:x,refetch:b}=dw({instanceName:h?.name,enabled:d}),w=on({resolver:an(wre),defaultValues:e||{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:0,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,splitMessages:!1,timePerChar:0}}),C=w.watch("botType"),k=w.watch("triggerType"),j=w.watch("openaiCredsId"),{data:M,isLoading:_,refetch:R}=vre({instanceName:h?.name,openaiCredsId:j,token:h?.token,enabled:m&&!!j}),N=()=>{j&&(g(!0),R())},O=()=>{b()};return i.jsx(Gn,{...w,children:i.jsxs("form",{onSubmit:w.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:f("openai.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:f("openai.form.description.label"),required:!0,children:i.jsx(ne,{})}),i.jsx("div",{className:"space-y-2",children:i.jsxs("div",{className:"flex items-end gap-2",children:[i.jsx("div",{className:"flex-1",children:i.jsx(Jt,{name:"openaiCredsId",label:f("openai.form.openaiCredsId.label"),required:!0,options:x?.filter(D=>!!D.id).map(D=>({label:D.name?D.name:D.apiKey.substring(0,15)+"...",value:D.id}))??[]})}),i.jsx(LI,{onCredentialsUpdate:O,showText:!1})]})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:f("openai.form.openaiSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"botType",label:f("openai.form.botType.label"),required:!0,options:[{label:f("openai.form.botType.assistant"),value:"assistant"},{label:f("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),C==="assistant"&&i.jsxs(i.Fragment,{children:[i.jsx(le,{name:"assistantId",label:f("openai.form.assistantId.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"functionUrl",label:f("openai.form.functionUrl.label"),required:!0,children:i.jsx(ne,{})})]}),C==="chatCompletion"&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"space-y-2",children:i.jsxs("div",{className:"flex items-end gap-2",children:[i.jsx("div",{className:"flex-1",children:i.jsx(Jt,{name:"model",label:f("openai.form.model.label"),required:!0,disabled:!M||M.length===0,options:M?.map(D=>({label:D.id,value:D.id}))??[]})}),i.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:!j||_,onClick:N,className:"mb-2",children:_?i.jsxs(i.Fragment,{children:[i.jsx(Ip,{className:"mr-2 h-4 w-4 animate-spin"}),f("openai.button.loading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ip,{className:"mr-2 h-4 w-4"}),f("openai.button.loadModels")]})})]})}),i.jsx(le,{name:"systemMessages",label:f("openai.form.systemMessages.label"),children:i.jsx(bi,{})}),i.jsx(le,{name:"assistantMessages",label:f("openai.form.assistantMessages.label"),children:i.jsx(bi,{})}),i.jsx(le,{name:"userMessages",label:f("openai.form.userMessages.label"),children:i.jsx(bi,{})}),i.jsx(le,{name:"maxTokens",label:f("openai.form.maxTokens.label"),children:i.jsx(ne,{type:"number"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:f("openai.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:f("openai.form.triggerType.label"),required:!0,options:[{label:f("openai.form.triggerType.keyword"),value:"keyword"},{label:f("openai.form.triggerType.all"),value:"all"},{label:f("openai.form.triggerType.advanced"),value:"advanced"},{label:f("openai.form.triggerType.none"),value:"none"}]}),k==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:f("openai.form.triggerOperator.label"),required:!0,options:[{label:f("openai.form.triggerOperator.contains"),value:"contains"},{label:f("openai.form.triggerOperator.equals"),value:"equals"},{label:f("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:f("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:f("openai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:f("openai.form.triggerValue.label"),required:!0,children:i.jsx(ne,{})})]}),k==="advanced"&&i.jsx(le,{name:"triggerValue",label:f("openai.form.triggerConditions.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:f("openai.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:f("openai.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:f("openai.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:f("openai.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:f("openai.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:f("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:f("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:f("openai.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:f("openai.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Pe,{name:"splitMessages",label:f("openai.form.splitMessages.label"),reverse:!0}),w.watch("splitMessages")&&i.jsx(le,{name:"timePerChar",label:f("openai.form.timePerChar.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:f(o?"openai.button.saving":"openai.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx($I,{openaiId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:f("dify.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:f("modal.delete.title")}),i.jsx(eo,{children:f("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:f("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:f("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:f(o?"openai.button.saving":"openai.button.update")})]})]})]})})}function Sre({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),{createOpenai:r}=Md(),[s,o]=y.useState(!1),[l,u]=y.useState(!1),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:f.enabled,description:f.description,openaiCredsId:f.openaiCredsId,botType:f.botType,assistantId:f.assistantId||"",functionUrl:f.functionUrl||"",model:f.model||"",systemMessages:[f.systemMessages||""],assistantMessages:[f.assistantMessages||""],userMessages:[f.userMessages||""],maxTokens:f.maxTokens||0,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0,splitMessages:f.splitMessages||!1,timePerChar:f.timePerChar||0};await r({instanceName:n.name,token:n.token,data:h}),me.success(t("openai.toast.success.create")),u(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{o(!1)}};return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("openai.form.title")})}),i.jsx(BI,{onSubmit:d,isModal:!0,isLoading:s,open:l})]})]})}const Cre=e=>["openai","getOpenai",JSON.stringify(e)],Ere=async({instanceName:e,token:t,openaiId:n})=>{const r=await Ee.get(`/openai/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},kre=e=>{const{instanceName:t,token:n,openaiId:r,...s}=e;return mt({...s,queryKey:Cre({instanceName:t}),queryFn:()=>Ere({instanceName:t,token:n,openaiId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function jre({openaiId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteOpenai:u,updateOpenai:d}=Md(),{data:f,isLoading:h}=kre({instanceName:r?.name,openaiId:e}),m=y.useMemo(()=>({enabled:f?.enabled??!0,description:f?.description??"",openaiCredsId:f?.openaiCredsId??"",botType:f?.botType??"",assistantId:f?.assistantId||"",functionUrl:f?.functionUrl||"",model:f?.model||"",systemMessages:Array.isArray(f?.systemMessages)?f?.systemMessages.join(", "):f?.systemMessages||"",assistantMessages:Array.isArray(f?.assistantMessages)?f?.assistantMessages.join(", "):f?.assistantMessages||"",userMessages:Array.isArray(f?.userMessages)?f?.userMessages.join(", "):f?.userMessages||"",maxTokens:f?.maxTokens||0,triggerType:f?.triggerType||"",triggerOperator:f?.triggerOperator||"",triggerValue:f?.triggerValue,expire:f?.expire||0,keywordFinish:f?.keywordFinish,delayMessage:f?.delayMessage||0,unknownMessage:f?.unknownMessage,listeningFromMe:f?.listeningFromMe,stopBotFromMe:f?.stopBotFromMe,keepOpen:f?.keepOpen,debounceTime:f?.debounceTime||0,splitMessages:f?.splitMessages||!1,timePerChar:f?.timePerChar||0}),[f?.assistantId,f?.assistantMessages,f?.botType,f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.functionUrl,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.maxTokens,f?.model,f?.openaiCredsId,f?.stopBotFromMe,f?.systemMessages,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.unknownMessage,f?.userMessages,f?.splitMessages,f?.timePerChar]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,openaiCredsId:b.openaiCredsId,botType:b.botType,assistantId:b.assistantId||"",functionUrl:b.functionUrl||"",model:b.model||"",systemMessages:[b.systemMessages||""],assistantMessages:[b.assistantMessages||""],userMessages:[b.userMessages||""],maxTokens:b.maxTokens||0,triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0,splitMessages:b.splitMessages||!1,timePerChar:b.timePerChar||0};await d({instanceName:r.name,openaiId:e,data:w}),me.success(n("openai.toast.success.update")),t(),s(`/manager/instance/${r.id}/openai/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,openaiId:e}),me.success(n("openai.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/openai`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir dify:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(BI,{initialData:m,onSubmit:g,openaiId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function Tk(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{botId:r}=ls(),{data:s,isLoading:o,refetch:l}=FI({instanceName:n?.name}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/openai/${h}`)},f=()=>{l()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx($I,{}),i.jsx(hre,{}),i.jsx(LI,{}),i.jsx(Sre,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:o?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsxs(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:h.description||h.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:h.botType})]},h.id)):i.jsx(se,{variant:"link",children:e("openai.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-border"}),i.jsx(Hn,{children:i.jsx(jre,{openaiId:r,resetTable:f})})]})]})]})}const Tre=e=>["proxy","fetchProxy",JSON.stringify(e)],Nre=async({instanceName:e,token:t})=>(await Ee.get(`/proxy/find/${e}`,{headers:{apiKey:t}})).data,Mre=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Tre({instanceName:t,token:n}),queryFn:()=>Nre({instanceName:t,token:n}),enabled:!!t})},_re=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data;function Rre(){return{createProxy:nt(_re,{invalidateKeys:[["proxy","fetchProxy"]]})}}const Pre=P.object({enabled:P.boolean(),host:P.string(),port:P.string(),protocol:P.string(),username:P.string(),password:P.string()});function Ore(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{createProxy:s}=Rre(),{data:o}=Mre({instanceName:t?.name}),l=on({resolver:an(Pre),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});y.useEffect(()=>{o&&l.reset({enabled:o.enabled,host:o.host,port:o.port,protocol:o.protocol,username:o.username,password:o.password})},[o]);const u=async d=>{if(t){r(!0);try{const f={enabled:d.enabled,host:d.host,port:d.port,protocol:d.protocol,username:d.username,password:d.password};await s({instanceName:t.name,token:t.token,data:f}),me.success(e("proxy.toast.success"))}catch(f){console.error(e("proxy.toast.error"),f),me.error(`Error : ${f?.response?.data?.response?.message}`)}finally{r(!1)}}};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...l,children:i.jsx("form",{onSubmit:l.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(Pe,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[i.jsx(le,{name:"protocol",label:e("proxy.form.protocol.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"host",label:e("proxy.form.host.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"port",label:e("proxy.form.port.label"),children:i.jsx(ne,{type:"number"})})]}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[i.jsx(le,{name:"username",label:e("proxy.form.username.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"password",label:e("proxy.form.password.label"),children:i.jsx(ne,{type:"password"})})]}),i.jsx("div",{className:"flex justify-end px-4 pt-6",children:i.jsx(se,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const Ire=e=>["rabbitmq","fetchRabbitmq",JSON.stringify(e)],Are=async({instanceName:e,token:t})=>(await Ee.get(`/rabbitmq/find/${e}`,{headers:{apiKey:t}})).data,Dre=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Ire({instanceName:t,token:n}),queryFn:()=>Are({instanceName:t,token:n}),enabled:!!t})},Fre=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/rabbitmq/set/${e}`,{rabbitmq:n},{headers:{apikey:t}})).data;function Lre(){return{createRabbitmq:nt(Fre,{invalidateKeys:[["rabbitmq","fetchRabbitmq"]]})}}const $re=P.object({enabled:P.boolean(),events:P.array(P.string())});function Bre(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{createRabbitmq:s}=Lre(),{data:o}=Dre({instanceName:t?.name,token:t?.token}),l=on({resolver:an($re),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{o&&l.reset({enabled:o.enabled,events:o.events})},[o]);const u=async m=>{if(t){r(!0);try{const g={enabled:m.enabled,events:m.events};await s({instanceName:t.name,token:t.token,data:g}),me.success(e("rabbitmq.toast.success"))}catch(g){console.error(e("rabbitmq.toast.error"),g),me.error(`Error: ${g?.response?.data?.response?.message}`)}finally{r(!1)}}},d=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],f=()=>{l.setValue("events",d)},h=()=>{l.setValue("events",[])};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...l,children:i.jsx("form",{onSubmit:l.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(Pe,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),i.jsxs("div",{className:"mb-4 flex justify-between",children:[i.jsx(se,{variant:"outline",type:"button",onClick:f,children:e("button.markAll")}),i.jsx(se,{variant:"outline",type:"button",onClick:h,children:e("button.unMarkAll")})]}),i.jsx(Lo,{control:l.control,name:"events",render:({field:m})=>i.jsxs(no,{className:"flex flex-col",children:[i.jsx(Nr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),i.jsx(_s,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:d.sort((g,x)=>g.localeCompare(x)).map(g=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(Nr,{className:Ie("break-all",m.value.includes(g)?"text-foreground":"text-muted-foreground"),children:g}),i.jsx(gc,{checked:m.value.includes(g),onCheckedChange:x=>{x?m.onChange([...m.value,g]):m.onChange(m.value.filter(b=>b!==g))}})]},g))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(se,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const zre=e=>["instance","fetchSettings",JSON.stringify(e)],Ure=async({instanceName:e,token:t})=>(await Ee.get(`/settings/find/${e}`,{headers:{apikey:t}})).data,Vre=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:zre({instanceName:t,token:n}),queryFn:()=>Ure({instanceName:t,token:n}),enabled:!!t})},Hre=P.object({rejectCall:P.boolean(),msgCall:P.string().optional(),groupsIgnore:P.boolean(),alwaysOnline:P.boolean(),readMessages:P.boolean(),syncFullHistory:P.boolean(),readStatus:P.boolean()});function qre(){const{t:e}=Ve(),[t,n]=y.useState(!1),{instance:r}=ct(),{updateSettings:s}=Hh(),{data:o,isLoading:l}=Vre({instanceName:r?.name,token:r?.token}),u=on({resolver:an(Hre),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});y.useEffect(()=>{o&&u.reset({rejectCall:o.rejectCall,msgCall:o.msgCall||"",groupsIgnore:o.groupsIgnore,alwaysOnline:o.alwaysOnline,readMessages:o.readMessages,syncFullHistory:o.syncFullHistory,readStatus:o.readStatus})},[u,o]);const d=async m=>{try{if(!r||!r.name)throw new Error("instance not found");n(!0);const g={rejectCall:m.rejectCall,msgCall:m.msgCall,groupsIgnore:m.groupsIgnore,alwaysOnline:m.alwaysOnline,readMessages:m.readMessages,syncFullHistory:m.syncFullHistory,readStatus:m.readStatus};await s({instanceName:r.name,token:r.token,data:g}),me.success(e("settings.toast.success"))}catch(g){console.error(e("settings.toast.success"),g),me.error(e("settings.toast.error"))}finally{n(!1)}},f=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],h=u.watch("rejectCall");return l?i.jsx(On,{}):i.jsx(i.Fragment,{children:i.jsx(Fo,{...u,children:i.jsx("form",{onSubmit:u.handleSubmit(d),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),i.jsx($t,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[i.jsxs("div",{className:"flex flex-col p-4",children:[i.jsx(Pe,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),h&&i.jsx("div",{className:"mr-16 mt-2",children:i.jsx(le,{name:"msgCall",children:i.jsx(bi,{placeholder:e("settings.form.msgCall.description")})})})]}),f.map(m=>i.jsx("div",{className:"flex p-4",children:i.jsx(Pe,{name:m.name,label:m.label,className:"w-full justify-between",helper:m.description})},m.name)),i.jsx("div",{className:"flex justify-end pt-6",children:i.jsx(se,{type:"submit",disabled:t,children:e(t?"settings.button.saving":"settings.button.save")})})]})]})})})})}const Kre=e=>["sqs","fetchSqs",JSON.stringify(e)],Wre=async({instanceName:e,token:t})=>(await Ee.get(`/sqs/find/${e}`,{headers:{apiKey:t}})).data,Gre=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Kre({instanceName:t,token:n}),queryFn:()=>Wre({instanceName:t,token:n}),enabled:!!t})},Jre=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/sqs/set/${e}`,{sqs:n},{headers:{apikey:t}})).data;function Qre(){return{createSqs:nt(Jre,{invalidateKeys:[["sqs","fetchSqs"]]})}}const Zre=P.object({enabled:P.boolean(),events:P.array(P.string())});function Yre(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{createSqs:s}=Qre(),{data:o}=Gre({instanceName:t?.name,token:t?.token}),l=on({resolver:an(Zre),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{o&&l.reset({enabled:o.enabled,events:o.events})},[o]);const u=async m=>{if(t){r(!0);try{const g={enabled:m.enabled,events:m.events};await s({instanceName:t.name,token:t.token,data:g}),me.success(e("sqs.toast.success"))}catch(g){console.error(e("sqs.toast.error"),g),me.error(`Error: ${g?.response?.data?.response?.message}`)}finally{r(!1)}}},d=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],f=()=>{l.setValue("events",d)},h=()=>{l.setValue("events",[])};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...l,children:i.jsx("form",{onSubmit:l.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(Pe,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),i.jsxs("div",{className:"mb-4 flex justify-between",children:[i.jsx(se,{variant:"outline",type:"button",onClick:f,children:e("button.markAll")}),i.jsx(se,{variant:"outline",type:"button",onClick:h,children:e("button.unMarkAll")})]}),i.jsx(Lo,{control:l.control,name:"events",render:({field:m})=>i.jsxs(no,{className:"flex flex-col",children:[i.jsx(Nr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),i.jsx(_s,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:d.sort((g,x)=>g.localeCompare(x)).map(g=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(Nr,{className:Ie("break-all",m.value.includes(g)?"text-foreground":"text-muted-foreground"),children:g}),i.jsx(gc,{checked:m.value.includes(g),onCheckedChange:x=>{x?m.onChange([...m.value,g]):m.onChange(m.value.filter(b=>b!==g))}})]},g))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(se,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const Xre=e=>["typebot","findTypebot",JSON.stringify(e)],ese=async({instanceName:e,token:t})=>(await Ee.get(`/typebot/find/${e}`,{headers:{apiKey:t}})).data,zI=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Xre({instanceName:t}),queryFn:()=>ese({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},tse=e=>["typebot","fetchDefaultSettings",JSON.stringify(e)],nse=async({instanceName:e,token:t})=>{const n=await Ee.get(`/typebot/fetchSettings/${e}`,{headers:{apiKey:t}});return Array.isArray(n.data)?n.data[0]:n.data},rse=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:tse({instanceName:t}),queryFn:()=>nse({instanceName:t,token:n}),enabled:!!t&&(e.enabled??!0)})},sse=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,ose=async({instanceName:e,token:t,typebotId:n,data:r})=>(await Ee.put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,ase=async({instanceName:e,typebotId:t})=>(await Ee.delete(`/typebot/delete/${t}/${e}`)).data,ise=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,lse=async({instanceName:e,token:t,remoteJid:n,status:r})=>(await Ee.post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data;function Eg(){const e=nt(ise,{invalidateKeys:[["typebot","fetchDefaultSettings"]]}),t=nt(lse,{invalidateKeys:[["typebot","getTypebot"],["typebot","fetchSessions"]]}),n=nt(ase,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),r=nt(ose,{invalidateKeys:[["typebot","getTypebot"],["typebot","findTypebot"],["typebot","fetchSessions"]]}),s=nt(sse,{invalidateKeys:[["typebot","findTypebot"]]});return{setDefaultSettingsTypebot:e,changeStatusTypebot:t,deleteTypebot:n,updateTypebot:r,createTypebot:s}}const cse=P.object({expire:P.coerce.number(),keywordFinish:P.string(),delayMessage:P.coerce.number(),unknownMessage:P.string(),listeningFromMe:P.boolean(),stopBotFromMe:P.boolean(),keepOpen:P.boolean(),debounceTime:P.coerce.number()});function use(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{setDefaultSettingsTypebot:s}=Eg(),{data:o,refetch:l}=rse({instanceName:t?.name,token:t?.token,enabled:n}),{data:u,refetch:d}=zI({instanceName:t?.name,token:t?.token,enabled:n}),f=on({resolver:an(cse),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});y.useEffect(()=>{o&&f.reset({expire:o?.expire??0,keywordFinish:o.keywordFinish,delayMessage:o.delayMessage??0,unknownMessage:o.unknownMessage,listeningFromMe:o.listeningFromMe,stopBotFromMe:o.stopBotFromMe,keepOpen:o.keepOpen,debounceTime:o.debounceTime??0})},[o]);const h=async g=>{try{if(!t||!t.name)throw new Error("instance not found.");const x={expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await s({instanceName:t.name,token:t.token,data:x}),me.success(e("typebot.toast.defaultSettings.success"))}catch(x){console.error(e("typebot.toast.defaultSettings.error"),x),me.error(`Error: ${x?.response?.data?.response?.message}`)}};function m(){l(),d()}return i.jsxs(Pt,{open:n,onOpenChange:r,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Oo,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:m,children:[i.jsx(Mt,{children:i.jsx(zt,{children:e("typebot.modal.defaultSettings.title")})}),i.jsx(Gn,{...f,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:f.handleSubmit(h),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(Jt,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:u?.filter(g=>!!g.id).map(g=>({label:g.typebot,value:g.description}))??[]}),i.jsx(le,{name:"expire",label:e("typebot.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(Da,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),i.jsx(Yt,{children:i.jsx(se,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const dse=e=>["typebot","fetchSessions",JSON.stringify(e)],fse=async({instanceName:e,typebotId:t,token:n})=>(await Ee.get(`/typebot/fetchSessions/${t}/${e}`,{headers:{apiKey:n}})).data,pse=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return mt({...s,queryKey:dse({instanceName:t}),queryFn:()=>fse({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function UI({typebotId:e}){const{t}=Ve(),{instance:n}=ct(),[r,s]=y.useState([]),[o,l]=y.useState(!1),[u,d]=y.useState(""),{changeStatusTypebot:f}=Eg(),{data:h,refetch:m}=pse({instanceName:n?.name,token:n?.token,typebotId:e});function g(){m()}const x=async(w,C)=>{try{if(!n)return;await f({instanceName:n.name,token:n.token,remoteJid:w,status:C}),me.success(t("typebot.toast.success.status")),g()}catch(k){console.error("Error:",k),me.error(`Error : ${k?.response?.data?.response?.message}`)}},b=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:w})=>i.jsx("div",{children:w.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:w})=>{const C=w.original;return i.jsxs(Kr,{children:[i.jsx(Wr,{asChild:!0,children:i.jsxs(se,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),i.jsx(Pa,{className:"h-4 w-4"})]})}),i.jsxs(hr,{align:"end",children:[i.jsx(Ao,{children:"Actions"}),i.jsx(Xs,{}),C.status!=="opened"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"opened"),children:[i.jsx(Fi,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),C.status!=="paused"&&C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"paused"),children:[i.jsx(Di,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),C.status!=="closed"&&i.jsxs(wt,{onClick:()=>x(C.remoteJid,"closed"),children:[i.jsx(Oi,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),i.jsxs(wt,{onClick:()=>x(C.remoteJid,"delete"),children:[i.jsx(Ii,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}];return i.jsxs(Pt,{open:o,onOpenChange:l,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{variant:"secondary",size:"sm",children:[i.jsx(Ai,{size:16,className:"mr-1"})," ",i.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:g,children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("typebot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(ne,{placeholder:t("typebot.sessions.search"),value:u,onChange:w=>d(w.target.value)}),i.jsx(se,{variant:"outline",onClick:g,size:"icon",children:i.jsx(Li,{size:16})})]}),i.jsx($a,{columns:b,data:h??[],onSortingChange:s,state:{sorting:r,globalFilter:u},onGlobalFilterChange:d,enableGlobalFilter:!0,noResultsMessage:t("typebot.sessions.table.none")})]})]})]})}const hse=P.object({enabled:P.boolean(),description:P.string(),url:P.string(),typebot:P.string().optional(),triggerType:P.string(),triggerOperator:P.string().optional(),triggerValue:P.string().optional(),expire:P.coerce.number().optional(),keywordFinish:P.string().optional(),delayMessage:P.coerce.number().optional(),unknownMessage:P.string().optional(),listeningFromMe:P.boolean().optional(),stopBotFromMe:P.boolean().optional(),keepOpen:P.boolean().optional(),debounceTime:P.coerce.number().optional()});function VI({initialData:e,onSubmit:t,handleDelete:n,typebotId:r,isModal:s=!1,isLoading:o=!1,openDeletionDialog:l=!1,setOpenDeletionDialog:u=()=>{}}){const{t:d}=Ve(),f=on({resolver:an(hse),defaultValues:e||{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}}),h=f.watch("triggerType");return i.jsx(Gn,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(t),className:"w-full space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[i.jsx(Pe,{name:"enabled",label:d("typebot.form.enabled.label"),reverse:!0}),i.jsx(le,{name:"description",label:d("typebot.form.description.label"),required:!0,children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("typebot.form.typebotSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"url",label:d("typebot.form.url.label"),required:!0,children:i.jsx(ne,{})}),i.jsx(le,{name:"typebot",label:d("typebot.form.typebot.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("typebot.form.triggerSettings.label")}),i.jsx($t,{})]}),i.jsx(Jt,{name:"triggerType",label:d("typebot.form.triggerType.label"),options:[{label:d("typebot.form.triggerType.keyword"),value:"keyword"},{label:d("typebot.form.triggerType.all"),value:"all"},{label:d("typebot.form.triggerType.advanced"),value:"advanced"},{label:d("typebot.form.triggerType.none"),value:"none"}]}),h==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{name:"triggerOperator",label:d("typebot.form.triggerOperator.label"),options:[{label:d("typebot.form.triggerOperator.contains"),value:"contains"},{label:d("typebot.form.triggerOperator.equals"),value:"equals"},{label:d("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:d("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:d("typebot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(le,{name:"triggerValue",label:d("typebot.form.triggerValue.label"),children:i.jsx(ne,{})})]}),h==="advanced"&&i.jsx(le,{name:"triggerValue",label:d("typebot.form.triggerConditions.label"),children:i.jsx(ne,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:d("typebot.form.generalSettings.label")}),i.jsx($t,{})]}),i.jsx(le,{name:"expire",label:d("typebot.form.expire.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"keywordFinish",label:d("typebot.form.keywordFinish.label"),children:i.jsx(ne,{})}),i.jsx(le,{name:"delayMessage",label:d("typebot.form.delayMessage.label"),children:i.jsx(ne,{type:"number"})}),i.jsx(le,{name:"unknownMessage",label:d("typebot.form.unknownMessage.label"),children:i.jsx(ne,{})}),i.jsx(Pe,{name:"listeningFromMe",label:d("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"stopBotFromMe",label:d("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(Pe,{name:"keepOpen",label:d("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(le,{name:"debounceTime",label:d("typebot.form.debounceTime.label"),children:i.jsx(ne,{type:"number"})})]}),s&&i.jsx(Yt,{children:i.jsx(se,{disabled:o,type:"submit",children:d(o?"typebot.button.saving":"typebot.button.save")})}),!s&&i.jsxs("div",{children:[i.jsx(UI,{typebotId:r}),i.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsx(se,{variant:"destructive",size:"sm",children:d("dify.button.delete")})}),i.jsx(Nt,{children:i.jsxs(Mt,{children:[i.jsx(zt,{children:d("modal.delete.title")}),i.jsx(eo,{children:d("modal.delete.messageSingle")}),i.jsxs(Yt,{children:[i.jsx(se,{size:"sm",variant:"outline",onClick:()=>u(!1),children:d("button.cancel")}),i.jsx(se,{variant:"destructive",onClick:n,children:d("button.delete")})]})]})})]}),i.jsx(se,{disabled:o,type:"submit",children:d(o?"typebot.button.saving":"typebot.button.update")})]})]})]})})}function gse({resetTable:e}){const{t}=Ve(),{instance:n}=ct(),{createTypebot:r}=Eg(),[s,o]=y.useState(!1),[l,u]=y.useState(!1),d=async f=>{try{if(!n||!n.name)throw new Error("instance not found");o(!0);const h={enabled:f.enabled,description:f.description,url:f.url,typebot:f.typebot||"",triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:f.expire||0,keywordFinish:f.keywordFinish||"",delayMessage:f.delayMessage||0,unknownMessage:f.unknownMessage||"",listeningFromMe:f.listeningFromMe||!1,stopBotFromMe:f.stopBotFromMe||!1,keepOpen:f.keepOpen||!1,debounceTime:f.debounceTime||0};await r({instanceName:n.name,token:n.token,data:h}),me.success(t("typebot.toast.success.create")),u(!1),e()}catch(h){console.error("Error:",h),me.error(`Error: ${h?.response?.data?.response?.message}`)}finally{o(!1)}};return i.jsxs(Pt,{open:l,onOpenChange:u,children:[i.jsx(Bt,{asChild:!0,children:i.jsxs(se,{size:"sm",children:[i.jsx(cs,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),i.jsxs(Nt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",children:[i.jsx(Mt,{children:i.jsx(zt,{children:t("typebot.form.title")})}),i.jsx(VI,{onSubmit:d,isModal:!0,isLoading:s})]})]})}const mse=e=>["typebot","getTypebot",JSON.stringify(e)],vse=async({instanceName:e,token:t,typebotId:n})=>{const r=await Ee.get(`/typebot/fetch/${n}/${e}`,{headers:{apiKey:t}});return Array.isArray(r.data)?r.data[0]:r.data},yse=e=>{const{instanceName:t,token:n,typebotId:r,...s}=e;return mt({...s,queryKey:mse({instanceName:t}),queryFn:()=>vse({instanceName:t,token:n,typebotId:r}),enabled:!!t&&!!r&&(e.enabled??!0)})};function bse({typebotId:e,resetTable:t}){const{t:n}=Ve(),{instance:r}=ct(),s=dn(),[o,l]=y.useState(!1),{deleteTypebot:u,updateTypebot:d}=Eg(),{data:f,isLoading:h}=yse({instanceName:r?.name,typebotId:e}),m=y.useMemo(()=>({enabled:!!f?.enabled,description:f?.description??"",url:f?.url??"",typebot:f?.typebot??"",triggerType:f?.triggerType??"",triggerOperator:f?.triggerOperator??"",triggerValue:f?.triggerValue,expire:f?.expire??0,keywordFinish:f?.keywordFinish,delayMessage:f?.delayMessage??0,unknownMessage:f?.unknownMessage,listeningFromMe:!!f?.listeningFromMe,stopBotFromMe:!!f?.stopBotFromMe,keepOpen:!!f?.keepOpen,debounceTime:f?.debounceTime??0}),[f?.debounceTime,f?.delayMessage,f?.description,f?.enabled,f?.expire,f?.keepOpen,f?.keywordFinish,f?.listeningFromMe,f?.stopBotFromMe,f?.triggerOperator,f?.triggerType,f?.triggerValue,f?.typebot,f?.unknownMessage,f?.url]),g=async b=>{try{if(r&&r.name&&e){const w={enabled:b.enabled,description:b.description,url:b.url,typebot:b.typebot||"",triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:b.expire||0,keywordFinish:b.keywordFinish||"",delayMessage:b.delayMessage||1e3,unknownMessage:b.unknownMessage||"",listeningFromMe:b.listeningFromMe||!1,stopBotFromMe:b.stopBotFromMe||!1,keepOpen:b.keepOpen||!1,debounceTime:b.debounceTime||0};await d({instanceName:r.name,typebotId:e,data:w}),me.success(n("typebot.toast.success.update")),t(),s(`/manager/instance/${r.id}/typebot/${e}`)}else console.error("Token not found")}catch(w){console.error("Error:",w),me.error(`Error: ${w?.response?.data?.response?.message}`)}},x=async()=>{try{r&&r.name&&e?(await u({instanceName:r.name,typebotId:e}),me.success(n("typebot.toast.success.delete")),l(!1),t(),s(`/manager/instance/${r.id}/typebot`)):console.error("instance not found")}catch(b){console.error("Erro ao excluir dify:",b)}};return h?i.jsx(On,{}):i.jsx("div",{className:"m-4",children:i.jsx(VI,{initialData:m,onSubmit:g,typebotId:e,handleDelete:x,isModal:!1,isLoading:h,openDeletionDialog:o,setOpenDeletionDialog:l})})}function Nk(){const{t:e}=Ve(),t=zo("(min-width: 768px)"),{instance:n}=ct(),{typebotId:r}=ls(),{data:s,isLoading:o,refetch:l}=zI({instanceName:n?.name,token:n?.token}),u=dn(),d=h=>{n&&u(`/manager/instance/${n.id}/typebot/${h}`)},f=()=>{l()};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),i.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[i.jsx(UI,{}),i.jsx(use,{}),i.jsx(gse,{resetTable:f})]})]}),i.jsx($t,{className:"my-4"}),i.jsxs($o,{direction:t?"horizontal":"vertical",children:[i.jsx(Hn,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:o?i.jsx(On,{}):i.jsx(i.Fragment,{children:s&&s.length>0&&Array.isArray(s)?s.map(h=>i.jsx(se,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>d(`${h.id}`),variant:r===h.id?"secondary":"outline",children:h.description?i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:h.description}),i.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[h.url," - ",h.typebot]})]}):i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:h.url}),i.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:h.typebot})]})},h.id)):i.jsx(se,{variant:"link",children:e("typebot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Bo,{withHandle:!0,className:"border border-black"}),i.jsx(Hn,{children:i.jsx(bse,{typebotId:r,resetTable:f})})]})]})]})}const xse=e=>["webhook","fetchWebhook",JSON.stringify(e)],wse=async({instanceName:e,token:t})=>(await Ee.get(`/webhook/find/${e}`,{headers:{apiKey:t}})).data,Sse=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:xse({instanceName:t,token:n}),queryFn:()=>wse({instanceName:t,token:n}),enabled:!!t})},Cse=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/webhook/set/${e}`,{webhook:n},{headers:{apikey:t}})).data;function Ese(){return{createWebhook:nt(Cse,{invalidateKeys:[["webhook","fetchWebhook"]]})}}const kse=P.object({enabled:P.boolean(),url:P.string().url("Invalid URL format"),events:P.array(P.string()),base64:P.boolean(),byEvents:P.boolean()});function jse(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{createWebhook:s}=Ese(),{data:o}=Sse({instanceName:t?.name,token:t?.token}),l=on({resolver:an(kse),defaultValues:{enabled:!1,url:"",events:[],base64:!1,byEvents:!1}});y.useEffect(()=>{o&&l.reset({enabled:o.enabled,url:o.url,events:o.events,base64:o.webhookBase64,byEvents:o.webhookByEvents})},[o]);const u=async m=>{if(t){r(!0);try{const g={enabled:m.enabled,url:m.url,events:m.events,base64:m.base64,byEvents:m.byEvents};await s({instanceName:t.name,token:t.token,data:g}),me.success(e("webhook.toast.success"))}catch(g){console.error(e("webhook.toast.error"),g),me.error(`Error: ${g?.response?.data?.response?.message}`)}finally{r(!1)}}},d=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],f=()=>{l.setValue("events",d)},h=()=>{l.setValue("events",[])};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...l,children:i.jsx("form",{onSubmit:l.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(Pe,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),i.jsx(le,{name:"url",label:"URL",children:i.jsx(ne,{})}),i.jsx(Pe,{name:"byEvents",label:e("webhook.form.byEvents.label"),className:"w-full justify-between",helper:e("webhook.form.byEvents.description")}),i.jsx(Pe,{name:"base64",label:e("webhook.form.base64.label"),className:"w-full justify-between",helper:e("webhook.form.base64.description")}),i.jsxs("div",{className:"mb-4 flex justify-between",children:[i.jsx(se,{variant:"outline",type:"button",onClick:f,children:e("button.markAll")}),i.jsx(se,{variant:"outline",type:"button",onClick:h,children:e("button.unMarkAll")})]}),i.jsx(Lo,{control:l.control,name:"events",render:({field:m})=>i.jsxs(no,{className:"flex flex-col",children:[i.jsx(Nr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),i.jsx(_s,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:d.sort((g,x)=>g.localeCompare(x)).map(g=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(Nr,{className:Ie("break-all",m.value.includes(g)?"text-foreground":"text-muted-foreground"),children:g}),i.jsx(gc,{checked:m.value.includes(g),onCheckedChange:x=>{x?m.onChange([...m.value,g]):m.onChange(m.value.filter(b=>b!==g))}})]},g))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(se,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const Tse=e=>["websocket","fetchWebsocket",JSON.stringify(e)],Nse=async({instanceName:e,token:t})=>(await Ee.get(`/websocket/find/${e}`,{headers:{apiKey:t}})).data,Mse=e=>{const{instanceName:t,token:n,...r}=e;return mt({...r,queryKey:Tse({instanceName:t,token:n}),queryFn:()=>Nse({instanceName:t,token:n}),enabled:!!t})},_se=async({instanceName:e,token:t,data:n})=>(await Ee.post(`/websocket/set/${e}`,{websocket:n},{headers:{apikey:t}})).data;function Rse(){return{createWebsocket:nt(_se,{invalidateKeys:[["websocket","fetchWebsocket"]]})}}const Pse=P.object({enabled:P.boolean(),events:P.array(P.string())});function Ose(){const{t:e}=Ve(),{instance:t}=ct(),[n,r]=y.useState(!1),{createWebsocket:s}=Rse(),{data:o}=Mse({instanceName:t?.name,token:t?.token}),l=on({resolver:an(Pse),defaultValues:{enabled:!1,events:[]}});y.useEffect(()=>{o&&l.reset({enabled:o.enabled,events:o.events})},[o]);const u=async m=>{if(t){r(!0);try{const g={enabled:m.enabled,events:m.events};await s({instanceName:t.name,token:t.token,data:g}),me.success(e("websocket.toast.success"))}catch(g){console.error(e("websocket.toast.error"),g),me.error(`Error: ${g?.response?.data?.response?.message}`)}finally{r(!1)}}},d=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"],f=()=>{l.setValue("events",d)},h=()=>{l.setValue("events",[])};return i.jsx(i.Fragment,{children:i.jsx(Fo,{...l,children:i.jsx("form",{onSubmit:l.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),i.jsx(Oa,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(Pe,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),i.jsxs("div",{className:"mb-4 flex justify-between",children:[i.jsx(se,{variant:"outline",type:"button",onClick:f,children:e("button.markAll")}),i.jsx(se,{variant:"outline",type:"button",onClick:h,children:e("button.unMarkAll")})]}),i.jsx(Lo,{control:l.control,name:"events",render:({field:m})=>i.jsxs(no,{className:"flex flex-col",children:[i.jsx(Nr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),i.jsx(_s,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:d.sort((g,x)=>g.localeCompare(x)).map(g=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(Nr,{className:Ie("break-all",m.value.includes(g)?"text-foreground":"text-muted-foreground"),children:g}),i.jsx(gc,{checked:m.value.includes(g),onCheckedChange:x=>{x?m.onChange([...m.value,g]):m.onChange(m.value.filter(b=>b!==g))}})]},g))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(se,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const Ise=async({url:e,token:t})=>{try{const{data:n}=await sn.post(`${e}/verify-creds`,{},{headers:{apikey:t}});return Rj({facebookAppId:n.facebookAppId,facebookConfigId:n.facebookConfigId,facebookUserToken:n.facebookUserToken}),n}catch{return null}},Ase=P.object({serverUrl:P.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:P.string({required_error:"ApiKey is required"})});function Dse(){const{t:e}=Ve(),t=dn(),{theme:n}=tc(),r=on({resolver:an(Ase),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),s=async o=>{const l=await sT({url:o.serverUrl});if(!l||!l.version){Pj(),r.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await Ise({token:o.apiKey,url:o.serverUrl})){r.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}Rj({version:l.version,clientName:l.clientName,url:o.serverUrl,token:o.apiKey}),t("/manager/")};return i.jsxs("div",{className:"flex min-h-screen flex-col",children:[i.jsx("div",{className:"flex items-center justify-center pt-2",children:i.jsx("img",{className:"h-10",src:n==="dark"?"https://evolution-api.com/files/evo/evolution-logo-white.svg":"https://evolution-api.com/files/evo/evolution-logo.svg",alt:"logo"})}),i.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:i.jsxs(So,{className:"b-none w-[350px] shadow-none",children:[i.jsxs(Co,{children:[i.jsx(gi,{className:"text-center",children:e("login.title")}),i.jsx(Kp,{className:"text-center",children:e("login.description")})]}),i.jsx(Fo,{...r,children:i.jsxs("form",{onSubmit:r.handleSubmit(s),children:[i.jsx(Eo,{children:i.jsxs("div",{className:"grid w-full items-center gap-4",children:[i.jsx(le,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:i.jsx(ne,{})}),i.jsx(le,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:i.jsx(ne,{type:"password"})})]})}),i.jsx(Vh,{className:"flex justify-center",children:i.jsx(se,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),i.jsx(Vb,{})]})}function Fse(){const e=dn(),{theme:t}=tc(),n=()=>{e("/manager")};return i.jsxs("div",{className:"min-h-screen bg-background",children:[i.jsxs("header",{className:"flex items-center justify-between px-4 py-2",children:[i.jsx("div",{className:"flex items-center",children:i.jsx("img",{src:t==="dark"?"https://evolution-api.com/files/evo/evolution-logo-white.svg":"https://evolution-api.com/files/evo/evolution-logo.svg",alt:"Evolution API Logo",className:"h-8"})}),i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(iM,{}),i.jsx(lM,{})]})]}),i.jsx("div",{className:"container mx-auto px-4 py-16",children:i.jsxs("div",{className:"max-w-4xl mx-auto",children:[i.jsxs("div",{className:"text-center mb-12",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:t==="dark"?"https://evolution-api.com/files/evo/evolution-logo-white.svg":"https://evolution-api.com/files/evo/evolution-logo.svg",alt:"Evolution Manager Logo",className:"h-10"})}),i.jsx("h1",{className:"text-4xl font-bold text-foreground mb-4",children:"Evolution Manager v2"}),i.jsx("p",{className:"text-xl text-muted-foreground mb-6",children:"Modern web interface for Evolution API management"}),i.jsx(vu,{variant:"secondary",className:"text-sm px-3 py-1",children:"Version 2.0.0"})]}),i.jsxs(So,{className:"mb-8",children:[i.jsxs(Co,{children:[i.jsxs(gi,{className:"flex items-center gap-2",children:[i.jsx(xB,{className:"w-5 h-5 text-primary"}),"Welcome to Evolution Manager"]}),i.jsx(Kp,{children:"A powerful, modern dashboard for managing your WhatsApp API instances with Evolution API"})]}),i.jsx(Eo,{className:"space-y-6",children:i.jsx("div",{className:"pt-6 border-t border-border",children:i.jsx("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center",children:i.jsxs(se,{onClick:n,size:"lg",className:"px-8 py-3",children:["Access Manager Dashboard",i.jsx(Th,{className:"w-4 h-4 ml-2"})]})})})})]}),i.jsxs(So,{children:[i.jsxs(Co,{children:[i.jsx(gi,{children:"Resources & Support"}),i.jsx(Kp,{children:"Get help, contribute, or learn more about Evolution API"})]}),i.jsx(Eo,{children:i.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[i.jsxs("a",{href:"https://github.com/EvolutionAPI/evolution-manager-v2",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-4 rounded-lg border border-border hover:bg-accent transition-colors",children:[i.jsx(aB,{className:"w-5 h-5 text-muted-foreground"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium text-foreground",children:"GitHub"}),i.jsx("div",{className:"text-sm text-muted-foreground",children:"Source code"})]})]}),i.jsxs("a",{href:"https://evolution-api.com",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-4 rounded-lg border border-border hover:bg-accent transition-colors",children:[i.jsx(iB,{className:"w-5 h-5 text-muted-foreground"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium text-foreground",children:"Website"}),i.jsx("div",{className:"text-sm text-muted-foreground",children:"Official site"})]})]}),i.jsxs("a",{href:"mailto:contato@evolution-api.com",className:"flex items-center gap-3 p-4 rounded-lg border border-border hover:bg-accent transition-colors",children:[i.jsx(vB,{className:"w-5 h-5 text-muted-foreground"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium text-foreground",children:"Contact"}),i.jsx("div",{className:"text-sm text-muted-foreground",children:"Get support"})]})]})]})})]}),i.jsx("div",{className:"text-center mt-12 text-sm text-muted-foreground",children:i.jsx("p",{children:"© 2025 Evolution API. Licensed under Apache 2.0 with Evolution API custom conditions."})})]})})]})}const Lse=Z2([{path:"/",element:i.jsx(Fse,{})},{path:"/manager/login",element:i.jsx(jL,{children:i.jsx(Dse,{})})},{path:"/manager/",element:i.jsx(tn,{children:i.jsx(B5,{children:i.jsx(CZ,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(PX,{})})})},{path:"/manager/instance/:instanceId/chat",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(tk,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(tk,{})})})},{path:"/manager/instance/:instanceId/settings",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(qre,{})})})},{path:"/manager/instance/:instanceId/openai",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Tk,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Tk,{})})})},{path:"/manager/instance/:instanceId/webhook",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(jse,{})})})},{path:"/manager/instance/:instanceId/websocket",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ose,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Bre,{})})})},{path:"/manager/instance/:instanceId/sqs",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Yre,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(yX,{})})})},{path:"/manager/instance/:instanceId/typebot",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Nk,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Nk,{})})})},{path:"/manager/instance/:instanceId/dify",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(xk,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(xk,{})})})},{path:"/manager/instance/:instanceId/n8n",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(jk,{})})})},{path:"/manager/instance/:instanceId/n8n/:n8nId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(jk,{})})})},{path:"/manager/instance/:instanceId/evoai",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ck,{})})})},{path:"/manager/instance/:instanceId/evoai/:evoaiId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ck,{})})})},{path:"/manager/instance/:instanceId/evolutionBot",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ek,{})})})},{path:"/manager/instance/:instanceId/evolutionBot/:evolutionBotId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ek,{})})})},{path:"/manager/instance/:instanceId/flowise",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(kk,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(kk,{})})})},{path:"/manager/instance/:instanceId/proxy",element:i.jsx(tn,{children:i.jsx(un,{children:i.jsx(Ore,{})})})},{path:"/manager/embed-chat",element:i.jsx(Sk,{})},{path:"/manager/embed-chat/:remoteJid",element:i.jsx(Sk,{})}]),$se={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class uh{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||$se,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[u,d]=l;for(let f=0;f{let[u,d]=l;for(let f=0;f{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},Mk=e=>e==null?"":""+e,Bse=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},zse=/###/g,_k=e=>e&&e.indexOf("###")>-1?e.replace(zse,"."):e,Rk=e=>!e||typeof e=="string",Pu=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=Pu(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],l=t.slice(0,t.length-1),u=Pu(e,l,Object);for(;u.obj===void 0&&l.length;)o=`${l[l.length-1]}.${o}`,l=l.slice(0,l.length-1),u=Pu(e,l,Object),u&&u.obj&&typeof u.obj[`${u.k}.${o}`]<"u"&&(u.obj=void 0);u.obj[`${u.k}.${o}`]=n},Use=(e,t,n,r)=>{const{obj:s,k:o}=Pu(e,t,Object);s[o]=s[o]||[],s[o].push(n)},dh=(e,t)=>{const{obj:n,k:r}=Pu(e,t);if(n)return n[r]},Vse=(e,t,n)=>{const r=dh(e,n);return r!==void 0?r:dh(t,n)},HI=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):HI(e[r],t[r],n):e[r]=t[r]);return e},Sl=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Hse={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const qse=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>Hse[t]):e;class Kse{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const Wse=[" ",",","?","!",";"],Gse=new Kse(20),Jse=(e,t,n)=>{t=t||"",n=n||"";const r=Wse.filter(l=>t.indexOf(l)<0&&n.indexOf(l)<0);if(r.length===0)return!0;const s=Gse.getRegExp(`(${r.map(l=>l==="?"?"\\?":l).join("|")})`);let o=!s.test(e);if(!o){const l=e.indexOf(n);l>0&&!s.test(e.substring(0,l))&&(o=!0)}return o},Mb=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&de&&e.indexOf("_")>0?e.replace("_","-"):e;class Ok extends kg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,l=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let u;t.indexOf(".")>-1?u=t.split("."):(u=[t,n],r&&(Array.isArray(r)?u.push(...r):typeof r=="string"&&o?u.push(...r.split(o)):u.push(r)));const d=dh(this.data,u);return!d&&!n&&!r&&t.indexOf(".")>-1&&(t=u[0],n=u[1],r=u.slice(2).join(".")),d||!l||typeof r!="string"?d:Mb(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const l=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let u=[t,n];r&&(u=u.concat(l?r.split(l):r)),t.indexOf(".")>-1&&(u=t.split("."),s=n,n=u[1]),this.addNamespaces(n),Pk(this.data,u,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let l=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},u=[t,n];t.indexOf(".")>-1&&(u=t.split("."),s=r,r=n,n=u[1]),this.addNamespaces(n);let d=dh(this.data,u)||{};l.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?HI(d,r,o):d={...d,...r},Pk(this.data,u,d),l.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var qI={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const Ik={};class ph extends kg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Bse(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Ks.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const l=r&&t.indexOf(r)>-1,u=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Jse(t,r,s);if(l&&!u){const d=t.match(this.interpolator.nestingRegexp);if(d&&d.length>0)return{key:t,namespaces:o};const f=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(f[0])>-1)&&(o=f.shift()),t=f.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:l,namespaces:u}=this.extractFromKey(t[t.length-1],n),d=u[u.length-1],f=n.lng||this.language,h=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f&&f.toLowerCase()==="cimode"){if(h){const _=n.nsSeparator||this.options.nsSeparator;return s?{res:`${d}${_}${l}`,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(n)}:`${d}${_}${l}`}return s?{res:l,usedKey:l,exactUsedKey:l,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(n)}:l}const m=this.resolve(t,n);let g=m&&m.res;const x=m&&m.usedKey||l,b=m&&m.exactUsedKey||l,w=Object.prototype.toString.apply(g),C=["[object Number]","[object Function]","[object RegExp]"],k=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,j=!this.i18nFormat||this.i18nFormat.handleAsObject;if(j&&g&&(typeof g!="string"&&typeof g!="boolean"&&typeof g!="number")&&C.indexOf(w)<0&&!(typeof k=="string"&&Array.isArray(g))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const _=this.options.returnedObjectHandler?this.options.returnedObjectHandler(x,g,{...n,ns:u}):`key '${l} (${this.language})' returned an object instead of string.`;return s?(m.res=_,m.usedParams=this.getUsedParamsDetails(n),m):_}if(o){const _=Array.isArray(g),R=_?[]:{},N=_?b:x;for(const O in g)if(Object.prototype.hasOwnProperty.call(g,O)){const D=`${N}${o}${O}`;R[O]=this.translate(D,{...n,joinArrays:!1,ns:u}),R[O]===D&&(R[O]=g[O])}g=R}}else if(j&&typeof k=="string"&&Array.isArray(g))g=g.join(k),g&&(g=this.extendTranslation(g,t,n,r));else{let _=!1,R=!1;const N=n.count!==void 0&&typeof n.count!="string",O=ph.hasDefaultValue(n),D=N?this.pluralResolver.getSuffix(f,n.count,n):"",z=n.ordinal&&N?this.pluralResolver.getSuffix(f,n.count,{ordinal:!1}):"",Q=N&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),pe=Q&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${D}`]||n[`defaultValue${z}`]||n.defaultValue;!this.isValidLookup(g)&&O&&(_=!0,g=pe),this.isValidLookup(g)||(R=!0,g=l);const G=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&R?void 0:g,W=O&&pe!==g&&this.options.updateMissing;if(R||_||W){if(this.logger.log(W?"updateKey":"missingKey",f,d,l,W?pe:g),o){const H=this.resolve(l,{...n,keySeparator:!1});H&&H.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let ie=[];const re=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&re&&re[0])for(let H=0;H{const A=O&&he!==g?he:G;this.options.missingKeyHandler?this.options.missingKeyHandler(H,d,q,A,W,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(H,d,q,A,W,n),this.emit("missingKey",H,d,q,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&N?ie.forEach(H=>{const q=this.pluralResolver.getSuffixes(H,n);Q&&n[`defaultValue${this.options.pluralSeparator}zero`]&&q.indexOf(`${this.options.pluralSeparator}zero`)<0&&q.push(`${this.options.pluralSeparator}zero`),q.forEach(he=>{Y([H],l+he,n[`defaultValue${he}`]||pe)})}):Y(ie,l,pe))}g=this.extendTranslation(g,t,n,m,r),R&&g===l&&this.options.appendNamespaceToMissingKey&&(g=`${d}:${l}`),(R||_)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}:${l}`:l,_?g:void 0):g=this.options.parseMissingKeyHandler(g))}return s?(m.res=g,m.usedParams=this.getUsedParamsDetails(n),m):g}extendTranslation(t,n,r,s,o){var l=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const f=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let h;if(f){const g=t.match(this.interpolator.nestingRegexp);h=g&&g.length}let m=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(m={...this.options.interpolation.defaultVariables,...m}),t=this.interpolator.interpolate(t,m,r.lng||this.language||s.usedLng,r),f){const g=t.match(this.interpolator.nestingRegexp),x=g&&g.length;h1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,l,u;return typeof t=="string"&&(t=[t]),t.forEach(d=>{if(this.isValidLookup(r))return;const f=this.extractFromKey(d,n),h=f.key;s=h;let m=f.namespaces;this.options.fallbackNS&&(m=m.concat(this.options.fallbackNS));const g=n.count!==void 0&&typeof n.count!="string",x=g&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),b=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",w=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);m.forEach(C=>{this.isValidLookup(r)||(u=C,!Ik[`${w[0]}-${C}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(u)&&(Ik[`${w[0]}-${C}`]=!0,this.logger.warn(`key "${s}" for languages "${w.join(", ")}" won't get resolved as namespace "${u}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),w.forEach(k=>{if(this.isValidLookup(r))return;l=k;const j=[h];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(j,h,k,C,n);else{let _;g&&(_=this.pluralResolver.getSuffix(k,n.count,n));const R=`${this.options.pluralSeparator}zero`,N=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(g&&(j.push(h+_),n.ordinal&&_.indexOf(N)===0&&j.push(h+_.replace(N,this.options.pluralSeparator)),x&&j.push(h+R)),b){const O=`${h}${this.options.contextSeparator}${n.context}`;j.push(O),g&&(j.push(O+_),n.ordinal&&_.indexOf(N)===0&&j.push(O+_.replace(N,this.options.pluralSeparator)),x&&j.push(O+R))}}let M;for(;M=j.pop();)this.isValidLookup(r)||(o=M,r=this.getResource(k,C,M,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:l,usedNS:u}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const xy=e=>e.charAt(0).toUpperCase()+e.slice(1);class Ak{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ks.create("languageUtils")}getScriptPartFromCode(t){if(t=fh(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=fh(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=xy(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=xy(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=xy(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=l=>{l&&(this.isSupportedCode(l)?s.push(l):this.logger.warn(`rejecting language code not found in supportedLngs: ${l}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(l=>{s.indexOf(l)<0&&o(this.formatLanguageCode(l))}),s}}let Qse=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Zse={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const Yse=["v1","v2","v3"],Xse=["v4"],Dk={zero:0,one:1,two:2,few:3,many:4,other:5},eoe=()=>{const e={};return Qse.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:Zse[t.fc]}})}),e};class toe{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=Ks.create("pluralResolver"),(!this.options.compatibilityJSON||Xse.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=eoe(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=fh(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const l=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=l,l}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>Dk[s]-Dk[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!Yse.includes(this.options.compatibilityJSON)}}const Fk=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=Vse(e,t,n);return!o&&s&&typeof n=="string"&&(o=Mb(e,n,r),o===void 0&&(o=Mb(t,n,r))),o},wy=e=>e.replace(/\$/g,"$$$$");class noe{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Ks.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:l,suffix:u,suffixEscaped:d,formatSeparator:f,unescapeSuffix:h,unescapePrefix:m,nestingPrefix:g,nestingPrefixEscaped:x,nestingSuffix:b,nestingSuffixEscaped:w,nestingOptionsSeparator:C,maxReplaces:k,alwaysFormat:j}=t.interpolation;this.escape=n!==void 0?n:qse,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?Sl(o):l||"{{",this.suffix=u?Sl(u):d||"}}",this.formatSeparator=f||",",this.unescapePrefix=h?"":m||"-",this.unescapeSuffix=this.unescapePrefix?"":h||"",this.nestingPrefix=g?Sl(g):x||Sl("$t("),this.nestingSuffix=b?Sl(b):w||Sl(")"),this.nestingOptionsSeparator=C||",",this.maxReplaces=k||1e3,this.alwaysFormat=j!==void 0?j:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,l,u;const d=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},f=x=>{if(x.indexOf(this.formatSeparator)<0){const k=Fk(n,d,x,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(k,void 0,r,{...s,...n,interpolationkey:x}):k}const b=x.split(this.formatSeparator),w=b.shift().trim(),C=b.join(this.formatSeparator).trim();return this.format(Fk(n,d,w,this.options.keySeparator,this.options.ignoreJSONStructure),C,r,{...s,...n,interpolationkey:w})};this.resetRegExp();const h=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,m=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:x=>wy(x)},{regex:this.regexp,safeValue:x=>this.escapeValue?wy(this.escape(x)):wy(x)}].forEach(x=>{for(u=0;o=x.regex.exec(t);){const b=o[1].trim();if(l=f(b),l===void 0)if(typeof h=="function"){const C=h(t,o,s);l=typeof C=="string"?C:""}else if(s&&Object.prototype.hasOwnProperty.call(s,b))l="";else if(m){l=o[0];continue}else this.logger.warn(`missed to pass in variable ${b} for interpolating ${t}`),l="";else typeof l!="string"&&!this.useRawValueToEscape&&(l=Mk(l));const w=x.safeValue(l);if(t=t.replace(o[0],w),m?(x.regex.lastIndex+=l.length,x.regex.lastIndex-=o[0].length):x.regex.lastIndex=0,u++,u>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,l;const u=(d,f)=>{const h=this.nestingOptionsSeparator;if(d.indexOf(h)<0)return d;const m=d.split(new RegExp(`${h}[ ]*{`));let g=`{${m[1]}`;d=m[0],g=this.interpolate(g,l);const x=g.match(/'/g),b=g.match(/"/g);(x&&x.length%2===0&&!b||b.length%2!==0)&&(g=g.replace(/'/g,'"'));try{l=JSON.parse(g),f&&(l={...f,...l})}catch(w){return this.logger.warn(`failed parsing options string in nesting for key ${d}`,w),`${d}${h}${g}`}return l.defaultValue&&l.defaultValue.indexOf(this.prefix)>-1&&delete l.defaultValue,d};for(;s=this.nestingRegexp.exec(t);){let d=[];l={...r},l=l.replace&&typeof l.replace!="string"?l.replace:l,l.applyPostProcessor=!1,delete l.defaultValue;let f=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const h=s[1].split(this.formatSeparator).map(m=>m.trim());s[1]=h.shift(),d=h,f=!0}if(o=n(u.call(this,s[1].trim(),l),l),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=Mk(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),f&&(o=d.reduce((h,m)=>this.format(h,m,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const roe=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(l=>{if(l){const[u,...d]=l.split(":"),f=d.join(":").trim().replace(/^'+|'+$/g,""),h=u.trim();n[h]||(n[h]=f),f==="false"&&(n[h]=!1),f==="true"&&(n[h]=!0),isNaN(f)||(n[h]=parseInt(f,10))}})}return{formatName:t,formatOptions:n}},Cl=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const l=r+JSON.stringify(o);let u=t[l];return u||(u=e(fh(r),s),t[l]=u),u(n)}};class soe{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Ks.create("formatter"),this.options=t,this.formats={number:Cl((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:Cl((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:Cl((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:Cl((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:Cl((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=Cl(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(u=>u.indexOf(")")>-1)){const u=o.findIndex(d=>d.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,u)].join(this.formatSeparator)}return o.reduce((u,d)=>{const{formatName:f,formatOptions:h}=roe(d);if(this.formats[f]){let m=u;try{const g=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},x=g.locale||g.lng||s.locale||s.lng||r;m=this.formats[f](u,x,{...h,...s,...g})}catch(g){this.logger.warn(g)}return m}else this.logger.warn(`there was no format function for ${f}`);return u},t)}}const ooe=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class aoe extends kg{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=Ks.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},l={},u={},d={};return t.forEach(f=>{let h=!0;n.forEach(m=>{const g=`${f}|${m}`;!r.reload&&this.store.hasResourceBundle(f,m)?this.state[g]=2:this.state[g]<0||(this.state[g]===1?l[g]===void 0&&(l[g]=!0):(this.state[g]=1,h=!1,l[g]===void 0&&(l[g]=!0),o[g]===void 0&&(o[g]=!0),d[m]===void 0&&(d[m]=!0)))}),h||(u[f]=!0)}),(Object.keys(o).length||Object.keys(l).length)&&this.queue.push({pending:l,pendingCount:Object.keys(l).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(l),toLoadLanguages:Object.keys(u),toLoadNamespaces:Object.keys(d)}}loaded(t,n,r){const s=t.split("|"),o=s[0],l=s[1];n&&this.emit("failedLoading",o,l,n),!n&&r&&this.store.addResourceBundle(o,l,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const u={};this.queue.forEach(d=>{Use(d.loaded,[o],l),ooe(d,t),n&&d.errors.push(n),d.pendingCount===0&&!d.done&&(Object.keys(d.loaded).forEach(f=>{u[f]||(u[f]={});const h=d.loaded[f];h.length&&h.forEach(m=>{u[f][m]===void 0&&(u[f][m]=!0)})}),d.done=!0,d.errors.length?d.callback(d.errors):d.callback())}),this.emit("loaded",u),this.queue=this.queue.filter(d=>!d.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,l=arguments.length>5?arguments[5]:void 0;if(!t.length)return l(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:l});return}this.readingCalls++;const u=(f,h)=>{if(this.readingCalls--,this.waitingReads.length>0){const m=this.waitingReads.shift();this.read(m.lng,m.ns,m.fcName,m.tried,m.wait,m.callback)}if(f&&h&&s{this.read.call(this,t,n,r,s+1,o*2,l)},o);return}l(f,h)},d=this.backend[r].bind(this.backend);if(d.length===2){try{const f=d(t,n);f&&typeof f.then=="function"?f.then(h=>u(null,h)).catch(u):u(null,f)}catch(f){u(f)}return}return d(t,n,u)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(l=>{this.loadOne(l)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(l,u)=>{l&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,l),!l&&u&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,u),this.loaded(t,l,u)})}saveMissing(t,n,r,s,o){let l=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},u=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const d={...l,isUpdate:o},f=this.backend.create.bind(this.backend);if(f.length<6)try{let h;f.length===5?h=f(t,n,r,s,d):h=f(t,n,r,s),h&&typeof h.then=="function"?h.then(m=>u(null,m)).catch(u):u(null,h)}catch(h){u(h)}else f(t,n,r,s,u,d)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const Lk=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),$k=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),lp=()=>{},ioe=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class dd extends kg{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=$k(t),this.services={},this.logger=Ks,this.modules={external:[]},ioe(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=Lk();this.options={...s,...this.options,...$k(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=h=>h?typeof h=="function"?new h:h:null;if(!this.options.isClone){this.modules.logger?Ks.init(o(this.modules.logger),this.options):Ks.init(null,this.options);let h;this.modules.formatter?h=this.modules.formatter:typeof Intl<"u"&&(h=soe);const m=new Ak(this.options);this.store=new Ok(this.options.resources,this.options);const g=this.services;g.logger=Ks,g.resourceStore=this.store,g.languageUtils=m,g.pluralResolver=new toe(m,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),h&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(g.formatter=o(h),g.formatter.init(g,this.options),this.options.interpolation.format=g.formatter.format.bind(g.formatter)),g.interpolator=new noe(this.options),g.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},g.backendConnector=new aoe(o(this.modules.backend),g.resourceStore,g,this.options),g.backendConnector.on("*",function(x){for(var b=arguments.length,w=new Array(b>1?b-1:0),C=1;C1?b-1:0),C=1;C{x.init&&x.init(this)})}if(this.format=this.options.interpolation.format,r||(r=lp),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const h=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);h.length>0&&h[0]!=="dev"&&(this.options.lng=h[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(h=>{this[h]=function(){return t.store[h](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(h=>{this[h]=function(){return t.store[h](...arguments),t}});const d=hu(),f=()=>{const h=(m,g)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),d.resolve(g),r(m,g)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return h(null,this.t.bind(this));this.changeLanguage(this.options.lng,h)};return this.options.resources||!this.options.initImmediate?f():setTimeout(f,0),d}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:lp;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],l=u=>{if(!u||u==="cimode")return;this.services.languageUtils.toResolveHierarchy(u).forEach(f=>{f!=="cimode"&&o.indexOf(f)<0&&o.push(f)})};s?l(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(d=>l(d)),this.options.preload&&this.options.preload.forEach(u=>l(u)),this.services.backendConnector.load(o,this.options.ns,u=>{!u&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(u)})}else r(null)}reloadResources(t,n,r){const s=hu();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=lp),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&qI.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=hu();this.emit("languageChanging",t);const o=d=>{this.language=d,this.languages=this.services.languageUtils.toResolveHierarchy(d),this.resolvedLanguage=void 0,this.setResolvedLanguage(d)},l=(d,f)=>{f?(o(f),this.translator.changeLanguage(f),this.isLanguageChangingTo=void 0,this.emit("languageChanged",f),this.logger.log("languageChanged",f)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(d,function(){return r.t(...arguments)})},u=d=>{!t&&!d&&this.services.languageDetector&&(d=[]);const f=typeof d=="string"?d:this.services.languageUtils.getBestMatchFromCodes(d);f&&(this.language||o(f),this.translator.language||this.translator.changeLanguage(f),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(f)),this.loadResources(f,h=>{l(h,f)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?u(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(u):this.services.languageDetector.detect(u):u(t),s}getFixedT(t,n,r){var s=this;const o=function(l,u){let d;if(typeof u!="object"){for(var f=arguments.length,h=new Array(f>2?f-2:0),m=2;m`${d.keyPrefix}${g}${b}`):x=d.keyPrefix?`${d.keyPrefix}${g}${l}`:l,s.t(x,d)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const l=(u,d)=>{const f=this.services.backendConnector.state[`${u}|${d}`];return f===-1||f===0||f===2};if(n.precheck){const u=n.precheck(this,l);if(u!==void 0)return u}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||l(r,t)&&(!s||l(o,t)))}loadNamespaces(t,n){const r=hu();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=hu();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(l=>s.indexOf(l)<0&&this.services.languageUtils.isSupportedCode(l));return o.length?(this.options.preload=s.concat(o),this.loadResources(l=>{r.resolve(),n&&n(l)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new Ak(Lk());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new dd(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:lp;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new dd(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(u=>{o[u]=this[u]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new Ok(this.store.data,s),o.services.resourceStore=o.store),o.translator=new ph(o.services,s),o.translator.on("*",function(u){for(var d=arguments.length,f=new Array(d>1?d-1:0),h=1;h:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-x>:not([hidden])~:not([hidden]){--tw-divide-x-reverse: 0;border-right-width:calc(1px * var(--tw-divide-x-reverse));border-left-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-wrap{text-wrap:wrap}.break-all{word-break:break-all}.rounded-3xl{border-radius:1.5rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-amber-500\/20{border-color:#f59e0b33}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-emerald-500\/20{border-color:#10b98133}.border-gray-600\/50{border-color:#4b556380}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-red-500\/20{border-color:#ef444433}.border-sky-500\/20{border-color:#0ea5e933}.border-transparent{border-color:transparent}.border-zinc-500\/20{border-color:#71717a33}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-amber-50\/50{background-color:#fffbeb80}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity))}.bg-background{background-color:hsl(var(--background))}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-50\/50{background-color:#ecfdf580}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-red-50\/50{background-color:#fef2f280}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sky-50\/50{background-color:#f0f9ff80}.bg-transparent{background-color:transparent}.bg-zinc-50\/50{background-color:#fafafa80}.fill-current{fill:currentColor}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pl-12{padding-left:3rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-8{padding-left:2rem}.pr-16{padding-right:4rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity))}.text-foreground{color:hsl(var(--foreground))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity))}.text-rose-600{--tw-text-opacity: 1;color:rgb(225 29 72 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.after\:bg-border:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-600\/80:hover{background-color:#d97706cc}.hover\:bg-amber-600\/90:hover{background-color:#d97706e6}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-transparent:hover{background-color:transparent}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-muted[data-state=open],.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:border-amber-500\/30:is(.dark *){border-color:#f59e0b4d}.dark\:border-emerald-500\/30:is(.dark *){border-color:#10b9814d}.dark\:border-red-500\/30:is(.dark *){border-color:#ef44444d}.dark\:border-sky-500\/30:is(.dark *){border-color:#0ea5e94d}.dark\:border-zinc-500\/30:is(.dark *){border-color:#71717a4d}.dark\:bg-amber-500\/10:is(.dark *){background-color:#f59e0b1a}.dark\:bg-emerald-500\/10:is(.dark *){background-color:#10b9811a}.dark\:bg-red-500\/10:is(.dark *){background-color:#ef44441a}.dark\:bg-sky-500\/10:is(.dark *){background-color:#0ea5e91a}.dark\:bg-zinc-500\/10:is(.dark *){background-color:#71717a1a}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}.dark\:text-sky-200:is(.dark *){--tw-text-opacity: 1;color:rgb(186 230 253 / var(--tw-text-opacity))}.dark\:text-zinc-300:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:m-4{margin:1rem}.sm\:inline{display:inline}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[10rem_1fr_10rem\]{grid-template-columns:10rem 1fr 10rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:w-64{width:16rem}.md\:w-full{width:100%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\*\]\:p-4>*{padding:1rem}.\[\&\>\*\]\:px-4>*{padding-left:1rem;padding-right:1rem}.\[\&\>\*\]\:py-2>*{padding-top:.5rem;padding-bottom:.5rem}.\[\&\>div\[style\]\]\:\!block>div[style]{display:block!important}.\[\&\>div\[style\]\]\:h-full>div[style]{height:100%}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:fill-rose-600>svg{fill:#e11d48}.\[\&\>svg\]\:text-amber-500>svg{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-emerald-600>svg{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-red-600>svg{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-sky-500>svg{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-zinc-400>svg{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity))}.hover\:\[\&\>svg\]\:fill-rose-700>svg:hover{fill:#be123c}.dark\:\[\&\>svg\]\:text-emerald-400\/80>svg:is(.dark *){color:#34d399cc}.dark\:\[\&\>svg\]\:text-red-400\/80>svg:is(.dark *){color:#f87171cc}.dark\:\[\&\>svg\]\:text-zinc-300>svg:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_strong\]\:text-foreground strong{color:hsl(var(--foreground))}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word}.bubble-right .bubble{background-color:#0a0a0a;text-align:right;max-width:100%}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px} diff --git a/manager/dist/assets/index-DsIrum0U.css b/manager/dist/assets/index-DsIrum0U.css new file mode 100644 index 000000000..be936d9a2 --- /dev/null +++ b/manager/dist/assets/index-DsIrum0U.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap";*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--gradient: #093028;--background: 178 98.4% 98.22%;--foreground: 178 6.800000000000001% .44%;--muted: 178 6.800000000000001% 91.1%;--muted-foreground: 178 3.4000000000000004% 41.1%;--popover: 178 35.599999999999994% 91.1%;--popover-foreground: 178 6.800000000000001% .55%;--card: 178 35.599999999999994% 91.1%;--card-foreground: 178 6.800000000000001% .55%;--border: 178 11.8% 89.44%;--input: 178 11.8% 89.44%;--primary: 178 68% 11%;--primary-foreground: 178 1.36% 91.1%;--secondary: 178 3.4000000000000004% 95.55%;--secondary-foreground: 178 5.08% 11.1%;--accent: 178 3.4000000000000004% 95.55%;--accent-foreground: 178 5.08% 11.1%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--ring: 178 68% 11%;--radius: .5rem}.dark{--gradient: #189d68;--background: 166 47.449999999999996% 2.88%;--foreground: 166 7.3% 96.8%;--muted: 166 36.5% 10.799999999999999%;--muted-foreground: 166 7.3% 53.6%;--popover: 166 50.4% 4.68%;--popover-foreground: 166 7.3% 96.8%;--card: 166 50.4% 4.68%;--card-foreground: 166 7.3% 96.8%;--border: 166 36.5% 10.799999999999999%;--input: 166 36.5% 10.799999999999999%;--primary: 166 73% 36%;--primary-foreground: 166 7.3% 96.8%;--secondary: 166 36.5% 10.799999999999999%;--secondary-foreground: 166 7.3% 96.8%;--accent: 166 36.5% 10.799999999999999%;--accent-foreground: 166 7.3% 96.8%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 166 7.3% 96.8%;--ring: 166 73% 36%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground));font-family:Inter,sans-serif;scrollbar-width:thin;scrollbar-color:transparent transparent}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%;margin-right:auto;margin-left:auto;padding-right:2rem;padding-left:2rem}@media (min-width: 1400px){.container{max-width:1400px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.invisible{visibility:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.-bottom-4{bottom:-1rem}.bottom-0{bottom:0}.left-0{left:0}.left-2{left:.5rem}.right-0{right:0}.right-4{right:1rem}.top-0{top:0}.top-4{top:1rem}.z-10{z-index:10}.z-50{z-index:50}.-m-2{margin:-.5rem}.m-4{margin:1rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.-mx-4{margin-left:-1rem;margin-right:-1rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.my-2{margin-top:.5rem;margin-bottom:.5rem}.my-4{margin-top:1rem;margin-bottom:1rem}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-2{margin-left:.5rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-16{margin-right:4rem}.mr-2{margin-right:.5rem}.mt-1{margin-top:.25rem}.mt-12{margin-top:3rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-auto{margin-top:auto}.box-border{box-sizing:border-box}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-24{height:6rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[1\.2rem\]{height:1.2rem}.h-\[1px\]{height:1px}.h-\[calc\(100vh-160px\)\]{height:calc(100vh - 160px)}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[300px\]{max-height:300px}.min-h-0{min-height:0px}.min-h-\[80px\]{min-height:80px}.min-h-\[calc\(100vh_-_56px\)\]{min-height:calc(100vh - 56px)}.min-h-screen{min-height:100vh}.w-0{width:0px}.w-1{width:.25rem}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-80{width:20rem}.w-\[1\.2rem\]{width:1.2rem}.w-\[1px\]{width:1px}.w-\[300px\]{width:300px}.w-\[350px\]{width:350px}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-\[280px\]{min-width:280px}.min-w-\[80px\]{min-width:80px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-2xl{max-width:42rem}.max-w-32{max-width:8rem}.max-w-40{max-width:10rem}.max-w-4xl{max-width:56rem}.max-w-\[300px\]{max-width:300px}.max-w-\[320px\]{max-width:320px}.max-w-\[60\%\]{max-width:60%}.max-w-\[64rem\]{max-width:64rem}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.flex-grow,.grow{flex-grow:1}.caption-bottom{caption-side:bottom}.translate-y-1{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-0{--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-0{--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-100{--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.grid-cols-\[repeat\(auto-fit\,_minmax\(15rem\,_1fr\)\)\]{grid-template-columns:repeat(auto-fit,minmax(15rem,1fr))}.flex-row{flex-direction:row}.flex-row-reverse{flex-direction:row-reverse}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-x>:not([hidden])~:not([hidden]){--tw-divide-x-reverse: 0;border-right-width:calc(1px * var(--tw-divide-x-reverse));border-left-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.self-end{align-self:flex-end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.overflow-ellipsis,.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-wrap{text-wrap:wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-3xl{border-radius:1.5rem}.rounded-\[16px\]{border-radius:16px}.rounded-\[2px\]{border-radius:2px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.rounded-l-lg{border-top-left-radius:var(--radius);border-bottom-left-radius:var(--radius)}.border{border-width:1px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[--color-border\]{border-color:var(--color-border)}.border-amber-500\/20{border-color:#f59e0b33}.border-black{--tw-border-opacity: 1;border-color:rgb(0 0 0 / var(--tw-border-opacity))}.border-black\/10{border-color:#0000001a}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-emerald-500\/20{border-color:#10b98133}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity))}.border-gray-600\/50{border-color:#4b556380}.border-input{border-color:hsl(var(--input))}.border-muted{border-color:hsl(var(--muted))}.border-red-500\/20{border-color:#ef444433}.border-sky-500\/20{border-color:#0ea5e933}.border-slate-600{--tw-border-opacity: 1;border-color:rgb(71 85 105 / var(--tw-border-opacity))}.border-transparent{border-color:transparent}.border-zinc-500\/20{border-color:#71717a33}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#b2ece0\]{--tw-bg-opacity: 1;background-color:rgb(178 236 224 / var(--tw-bg-opacity))}.bg-\[\#c8fff2\]{--tw-bg-opacity: 1;background-color:rgb(200 255 242 / var(--tw-bg-opacity))}.bg-\[\#d2e2e2\]{--tw-bg-opacity: 1;background-color:rgb(210 226 226 / var(--tw-bg-opacity))}.bg-\[\#e0f0f0\]{--tw-bg-opacity: 1;background-color:rgb(224 240 240 / var(--tw-bg-opacity))}.bg-\[--color-bg\]{background-color:var(--color-bg)}.bg-amber-50\/50{background-color:#fffbeb80}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity))}.bg-background{background-color:hsl(var(--background))}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-black\/10{background-color:#0000001a}.bg-black\/5{background-color:#0000000d}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity))}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-50\/50{background-color:#ecfdf580}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-primary\/30{background-color:hsl(var(--primary) / .3)}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity))}.bg-red-50\/50{background-color:#fef2f280}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sky-50\/50{background-color:#f0f9ff80}.bg-slate-700{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity))}.bg-transparent{background-color:transparent}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity))}.bg-zinc-50\/50{background-color:#fafafa80}.fill-current{fill:currentColor}.fill-gray-100{fill:#f3f4f6}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[0\.375rem_1rem_0_1rem\]{padding:.375rem 1rem 0}.p-\[1px\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-3{padding-bottom:.75rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-widest{letter-spacing:.1em}.text-\[\#008069\]{--tw-text-opacity: 1;color:rgb(0 128 105 / var(--tw-text-opacity))}.text-\[\#b03f3f\]{--tw-text-opacity: 1;color:rgb(176 63 63 / var(--tw-text-opacity))}.text-amber-100{--tw-text-opacity: 1;color:rgb(254 243 199 / var(--tw-text-opacity))}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-900{--tw-text-opacity: 1;color:rgb(6 78 59 / var(--tw-text-opacity))}.text-foreground{color:hsl(var(--foreground))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-muted-foreground\/80{color:hsl(var(--muted-foreground) / .8)}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity))}.text-rose-600{--tw-text-opacity: 1;color:rgb(225 29 72 / var(--tw-text-opacity))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sky-900{--tw-text-opacity: 1;color:rgb(12 74 110 / var(--tw-text-opacity))}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity))}.text-zinc-900{--tw-text-opacity: 1;color:rgb(24 24 27 / var(--tw-text-opacity))}.underline-offset-4{text-underline-offset:4px}.caret-transparent{caret-color:transparent}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-muted-foreground{--tw-ring-color: hsl(var(--muted-foreground))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.paused{animation-play-state:paused}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:bottom-\[12px\]:after{content:var(--tw-content);bottom:12px}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.after\:border-\[8px\]:after{content:var(--tw-content);border-width:8px}.after\:border-solid:after{content:var(--tw-content);border-style:solid}.after\:bg-border:after{content:var(--tw-content);background-color:hsl(var(--border))}.hover\:bg-\[\#a4ecde\]:hover{--tw-bg-opacity: 1;background-color:rgb(164 236 222 / var(--tw-bg-opacity))}.hover\:bg-\[\#b2ece0\]:hover{--tw-bg-opacity: 1;background-color:rgb(178 236 224 / var(--tw-bg-opacity))}.hover\:bg-\[\#c2d2d2\]:hover{--tw-bg-opacity: 1;background-color:rgb(194 210 210 / var(--tw-bg-opacity))}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-600\/80:hover{background-color:#d97706cc}.hover\:bg-amber-600\/90:hover{background-color:#d97706e6}.hover\:bg-black\/10:hover{background-color:#0000001a}.hover\:bg-destructive\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:stroke-destructive:hover{stroke:hsl(var(--destructive))}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-0:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-transparent:focus-visible{--tw-ring-color: transparent}.focus-visible\:ring-offset-0:focus-visible{--tw-ring-offset-width: 0px}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.focus-visible\:ring-offset-transparent:focus-visible{--tw-ring-offset-color: transparent}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-default:disabled{cursor:default}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:visible{visibility:visible}.group:hover .group-hover\:opacity-100{opacity:1}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.aria-selected\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=active\]\:bg-primary[data-state=active],.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-slate-400[data-state=unchecked]{--tw-bg-opacity: 1;background-color:rgb(148 163 184 / var(--tw-bg-opacity))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=active\]\:text-primary-foreground[data-state=active]{color:hsl(var(--primary-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:-rotate-90:is(.dark *){--tw-rotate: -90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:rotate-0:is(.dark *){--tw-rotate: 0deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-0:is(.dark *){--tw-scale-x: 0;--tw-scale-y: 0;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:scale-100:is(.dark *){--tw-scale-x: 1;--tw-scale-y: 1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dark\:border-amber-500\/30:is(.dark *){border-color:#f59e0b4d}.dark\:border-emerald-500\/30:is(.dark *){border-color:#10b9814d}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-red-500\/30:is(.dark *){border-color:#ef44444d}.dark\:border-sky-500\/30:is(.dark *){border-color:#0ea5e94d}.dark\:border-white\/10:is(.dark *){border-color:#ffffff1a}.dark\:border-zinc-500\/30:is(.dark *){border-color:#71717a4d}.dark\:bg-\[\#082720\]:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(8 39 32 / var(--tw-bg-opacity))}.dark\:bg-\[\#0b332a\]:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(11 51 42 / var(--tw-bg-opacity))}.dark\:bg-\[\#0f1413\]:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(15 20 19 / var(--tw-bg-opacity))}.dark\:bg-\[\#1d2724\]:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(29 39 36 / var(--tw-bg-opacity))}.dark\:bg-amber-500\/10:is(.dark *){background-color:#f59e0b1a}.dark\:bg-blue-300:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity))}.dark\:bg-emerald-500\/10:is(.dark *){background-color:#10b9811a}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity))}.dark\:bg-red-500\/10:is(.dark *){background-color:#ef44441a}.dark\:bg-red-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity))}.dark\:bg-sky-500\/10:is(.dark *){background-color:#0ea5e91a}.dark\:bg-white\/10:is(.dark *){background-color:#ffffff1a}.dark\:bg-white\/5:is(.dark *){background-color:#ffffff0d}.dark\:bg-yellow-950:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(66 32 6 / var(--tw-bg-opacity))}.dark\:bg-zinc-500\/10:is(.dark *){background-color:#71717a1a}.dark\:fill-gray-800:is(.dark *){fill:#1f2937}.dark\:text-\[\#00a884\]:is(.dark *){--tw-text-opacity: 1;color:rgb(0 168 132 / var(--tw-text-opacity))}.dark\:text-amber-200:is(.dark *){--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity))}.dark\:text-emerald-200:is(.dark *){--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity))}.dark\:text-gray-100:is(.dark *){--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-red-200:is(.dark *){--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}.dark\:text-sky-200:is(.dark *){--tw-text-opacity: 1;color:rgb(186 230 253 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:text-zinc-300:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.dark\:hover\:bg-\[\#071f19\]:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(7 31 25 / var(--tw-bg-opacity))}.dark\:hover\:bg-\[\#082720\]:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(8 39 32 / var(--tw-bg-opacity))}.dark\:hover\:bg-\[\#141a18\]:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(20 26 24 / var(--tw-bg-opacity))}.dark\:hover\:bg-white\/10:hover:is(.dark *){background-color:#ffffff1a}@media (min-width: 640px){.sm\:m-4{margin:1rem}.sm\:inline{display:inline}.sm\:max-h-\[600px\]{max-height:600px}.sm\:max-w-\[650px\]{max-width:650px}.sm\:max-w-\[740px\]{max-width:740px}.sm\:max-w-\[950px\]{max-width:950px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-\[10rem_1fr_10rem\]{grid-template-columns:10rem 1fr 10rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}}@media (min-width: 768px){.md\:inline{display:inline}.md\:flex{display:flex}.md\:w-64{width:16rem}.md\:w-full{width:100%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-8{gap:2rem}}@media (min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\>\*\]\:p-4>*{padding:1rem}.\[\&\>\*\]\:px-4>*{padding-left:1rem;padding-right:1rem}.\[\&\>\*\]\:py-2>*{padding-top:.5rem;padding-bottom:.5rem}.\[\&\>div\[style\]\]\:\!block>div[style]{display:block!important}.\[\&\>div\[style\]\]\:h-full>div[style]{height:100%}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:left-4>svg{left:1rem}.\[\&\>svg\]\:top-4>svg{top:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:fill-rose-600>svg{fill:#e11d48}.\[\&\>svg\]\:text-amber-500>svg{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-emerald-600>svg{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-foreground>svg{color:hsl(var(--foreground))}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-red-600>svg{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-sky-500>svg{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity))}.\[\&\>svg\]\:text-zinc-400>svg{--tw-text-opacity: 1;color:rgb(161 161 170 / var(--tw-text-opacity))}.hover\:\[\&\>svg\]\:fill-rose-700>svg:hover{fill:#be123c}.dark\:\[\&\>svg\]\:text-emerald-400\/80>svg:is(.dark *){color:#34d399cc}.dark\:\[\&\>svg\]\:text-red-400\/80>svg:is(.dark *){color:#f87171cc}.dark\:\[\&\>svg\]\:text-zinc-300>svg:is(.dark *){--tw-text-opacity: 1;color:rgb(212 212 216 / var(--tw-text-opacity))}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:1.75rem}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-sector\]\:outline-none .recharts-sector,.\[\&_\.recharts-surface\]\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_strong\]\:text-foreground strong{color:hsl(var(--foreground))}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: #e74c3c;--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient( to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55 );--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width : 480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}}.Toastify__toast{--y: 0;position:relative;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px #0000001a;display:flex;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;flex:1 1 auto;padding:6px;display:flex;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;flex:1}.Toastify__toast-icon{margin-inline-end:10px;width:20px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width : 480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.chat-item{display:flex;padding:10px;cursor:pointer;background-color:hsl(var(--background))}.chat-item:hover,.chat-item.active{background-color:#2f2f2f}.bubble{border-radius:16px;padding:12px;word-wrap:break-word;max-width:100%;overflow:hidden}.bubble-right .bubble{background-color:#0a0a0a;max-width:100%}.bubble-right .bubble>span{text-align:right;display:block}.bubble-left .bubble{background-color:#1b1b1b;max-width:100%}.bubble-right{align-self:flex-end;display:flex;justify-content:flex-end;width:80%}.bubble-left{align-self:flex-start;display:flex;justify-content:flex-start;width:80%}.input-message textarea{background-color:#2f2f2f;padding-left:48px}.input-message textarea:focus{outline:none;border:none;box-shadow:none}.message-container{flex:1;overflow-y:auto;max-height:calc(100vh - 110px);padding-top:50px}.tabs-chat{background-color:transparent;width:100%;border-radius:0}.contacts-container{height:calc(100vh - 180px);overflow-y:auto;display:flex;flex-direction:column}.chat-item{display:flex;padding:10px;cursor:pointer}.custom-scrollbar{scrollbar-width:none}.custom-scrollbar::-webkit-scrollbar{display:none}.input-container{position:sticky;bottom:0;display:flex;flex-direction:column;gap:.375rem;background-color:transparent;padding:.375rem 1rem;width:100%;max-width:48rem;margin:0 auto;box-sizing:border-box}.formatted-message{white-space:pre-wrap}.formatted-message p{margin-bottom:1em}.formatted-message strong{font-weight:700}.formatted-message em{font-style:italic}.formatted-message del{text-decoration:line-through}.formatted-message a{color:#170c96!important;text-decoration:underline!important}.highlight-quoted{animation:highlight 2s ease-out}@keyframes highlight{0%{background-color:#3b82f633}to{background-color:transparent}} diff --git a/manager/dist/index.html b/manager/dist/index.html index 0a85ca226..01a75fd5a 100644 --- a/manager/dist/index.html +++ b/manager/dist/index.html @@ -2,11 +2,11 @@ - + Evolution Manager - - + +
diff --git a/manager_install.sh b/manager_install.sh new file mode 100755 index 000000000..c6806744a --- /dev/null +++ b/manager_install.sh @@ -0,0 +1,8 @@ +#! /bin/bash + +cd evolution-manager-v2 +npm install +npm run build +cd .. +rm -rf manager/dist +cp -r evolution-manager-v2/dist manager/dist \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..c45e8fef3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,16284 @@ +{ + "name": "evolution-api", + "version": "2.3.7", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "evolution-api", + "version": "2.3.7", + "license": "Apache-2.0", + "dependencies": { + "@adiwajshing/keyed-db": "^0.2.4", + "@aws-sdk/client-sqs": "^3.891.0", + "@ffmpeg-installer/ffmpeg": "^1.1.0", + "@figuro/chatwoot-sdk": "^1.1.16", + "@hapi/boom": "^10.0.1", + "@paralleldrive/cuid2": "^2.2.2", + "@prisma/client": "^6.16.2", + "@sentry/node": "^10.12.0", + "@types/uuid": "^10.0.0", + "amqplib": "^0.10.5", + "audio-decode": "^2.2.3", + "axios": "^1.7.9", + "baileys": "7.0.0-rc.9", + "class-validator": "^0.14.1", + "compression": "^1.7.5", + "cors": "^2.8.5", + "dayjs": "^1.11.13", + "dotenv": "^16.4.7", + "emoji-regex": "^10.4.0", + "eventemitter2": "^6.4.9", + "express": "^4.21.2", + "express-async-errors": "^3.1.1", + "fetch-socks": "^1.3.2", + "fluent-ffmpeg": "^2.1.3", + "form-data": "^4.0.1", + "https-proxy-agent": "^7.0.6", + "i18next": "^23.7.19", + "jimp": "^1.6.0", + "json-schema": "^0.4.0", + "jsonschema": "^1.4.1", + "jsonwebtoken": "^9.0.2", + "kafkajs": "^2.2.4", + "libphonenumber-js": "^1.12.25", + "link-preview-js": "^3.0.13", + "long": "^5.2.3", + "mediainfo.js": "^0.3.4", + "mime": "^4.0.0", + "mime-types": "^2.1.35", + "minio": "^8.0.3", + "multer": "^2.0.2", + "nats": "^2.29.1", + "node-cache": "^5.1.2", + "node-cron": "^3.0.3", + "openai": "^4.77.3", + "pg": "^8.13.1", + "pino": "^9.10.0", + "prisma": "^6.1.0", + "pusher": "^5.2.0", + "qrcode": "^1.5.4", + "qrcode-terminal": "^0.12.0", + "redis": "^4.7.0", + "rxjs": "^7.8.2", + "sharp": "^0.34.2", + "socket.io": "^4.8.1", + "socket.io-client": "^4.8.1", + "socks-proxy-agent": "^8.0.5", + "swagger-ui-express": "^5.0.1", + "tsup": "^8.3.5", + "undici": "^7.16.0", + "uuid": "^13.0.0" + }, + "devDependencies": { + "@commitlint/cli": "^19.8.1", + "@commitlint/config-conventional": "^19.8.1", + "@types/compression": "^1.7.5", + "@types/cors": "^2.8.17", + "@types/express": "^4.17.18", + "@types/json-schema": "^7.0.15", + "@types/mime": "^4.0.0", + "@types/mime-types": "^2.1.4", + "@types/node": "^24.5.2", + "@types/node-cron": "^3.0.11", + "@types/qrcode": "^1.5.5", + "@types/qrcode-terminal": "^0.12.2", + "@typescript-eslint/eslint-plugin": "^8.44.0", + "@typescript-eslint/parser": "^8.44.0", + "commitizen": "^4.3.1", + "cz-conventional-changelog": "^3.3.0", + "eslint": "^8.45.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-prettier": "^5.2.1", + "eslint-plugin-simple-import-sort": "^12.1.1", + "husky": "^9.1.7", + "lint-staged": "^16.1.6", + "prettier": "^3.4.2", + "tsconfig-paths": "^4.2.0", + "tsx": "^4.20.5", + "typescript": "^5.7.2" + } + }, + "node_modules/@adiwajshing/keyed-db": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@adiwajshing/keyed-db/-/keyed-db-0.2.4.tgz", + "integrity": "sha512-yprSnAtj80/VKuDqRcFFLDYltoNV8tChNwFfIgcf6PGD4sjzWIBgs08pRuTqGH5mk5wgL6PBRSsMCZqtZwzFEw==", + "license": "MIT" + }, + "node_modules/@apm-js-collab/code-transformer": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/@apm-js-collab/code-transformer/-/code-transformer-0.8.2.tgz", + "integrity": "sha512-YRjJjNq5KFSjDUoqu5pFUWrrsvGOxl6c3bu+uMFc9HNNptZ2rNU/TI2nLw4jnhQNtka972Ee2m3uqbvDQtPeCA==", + "license": "Apache-2.0" + }, + "node_modules/@apm-js-collab/tracing-hooks": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@apm-js-collab/tracing-hooks/-/tracing-hooks-0.3.1.tgz", + "integrity": "sha512-Vu1CbmPURlN5fTboVuKMoJjbO5qcq9fA5YXpskx3dXe/zTBvjODFoerw+69rVBlRLrJpwPqSDqEuJDEKIrTldw==", + "license": "Apache-2.0", + "dependencies": { + "@apm-js-collab/code-transformer": "^0.8.0", + "debug": "^4.4.1", + "module-details-from-path": "^1.0.4" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-sqs": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sqs/-/client-sqs-3.936.0.tgz", + "integrity": "sha512-JDYdeGV8L+zXr9Ce7gVeleQB2z0F3YWWmNvbE6cS20fR9E0XVIsYw5Grymjw9/3AG4wbOIQJ5Nayy+HgxKANjA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.936.0", + "@aws-sdk/credential-provider-node": "3.936.0", + "@aws-sdk/middleware-host-header": "3.936.0", + "@aws-sdk/middleware-logger": "3.936.0", + "@aws-sdk/middleware-recursion-detection": "3.936.0", + "@aws-sdk/middleware-sdk-sqs": "3.936.0", + "@aws-sdk/middleware-user-agent": "3.936.0", + "@aws-sdk/region-config-resolver": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@aws-sdk/util-endpoints": "3.936.0", + "@aws-sdk/util-user-agent-browser": "3.936.0", + "@aws-sdk/util-user-agent-node": "3.936.0", + "@smithy/config-resolver": "^4.4.3", + "@smithy/core": "^3.18.5", + "@smithy/fetch-http-handler": "^5.3.6", + "@smithy/hash-node": "^4.2.5", + "@smithy/invalid-dependency": "^4.2.5", + "@smithy/md5-js": "^4.2.5", + "@smithy/middleware-content-length": "^4.2.5", + "@smithy/middleware-endpoint": "^4.3.12", + "@smithy/middleware-retry": "^4.4.12", + "@smithy/middleware-serde": "^4.2.6", + "@smithy/middleware-stack": "^4.2.5", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/node-http-handler": "^4.4.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.11", + "@smithy/util-defaults-mode-node": "^4.2.14", + "@smithy/util-endpoints": "^3.2.5", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-retry": "^4.2.5", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.936.0.tgz", + "integrity": "sha512-0G73S2cDqYwJVvqL08eakj79MZG2QRaB56Ul8/Ps9oQxllr7DMI1IQ/N3j3xjxgpq/U36pkoFZ8aK1n7Sbr3IQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.936.0", + "@aws-sdk/middleware-host-header": "3.936.0", + "@aws-sdk/middleware-logger": "3.936.0", + "@aws-sdk/middleware-recursion-detection": "3.936.0", + "@aws-sdk/middleware-user-agent": "3.936.0", + "@aws-sdk/region-config-resolver": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@aws-sdk/util-endpoints": "3.936.0", + "@aws-sdk/util-user-agent-browser": "3.936.0", + "@aws-sdk/util-user-agent-node": "3.936.0", + "@smithy/config-resolver": "^4.4.3", + "@smithy/core": "^3.18.5", + "@smithy/fetch-http-handler": "^5.3.6", + "@smithy/hash-node": "^4.2.5", + "@smithy/invalid-dependency": "^4.2.5", + "@smithy/middleware-content-length": "^4.2.5", + "@smithy/middleware-endpoint": "^4.3.12", + "@smithy/middleware-retry": "^4.4.12", + "@smithy/middleware-serde": "^4.2.6", + "@smithy/middleware-stack": "^4.2.5", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/node-http-handler": "^4.4.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.11", + "@smithy/util-defaults-mode-node": "^4.2.14", + "@smithy/util-endpoints": "^3.2.5", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-retry": "^4.2.5", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.936.0.tgz", + "integrity": "sha512-eGJ2ySUMvgtOziHhDRDLCrj473RJoL4J1vPjVM3NrKC/fF3/LoHjkut8AAnKmrW6a2uTzNKubigw8dEnpmpERw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@aws-sdk/xml-builder": "3.930.0", + "@smithy/core": "^3.18.5", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/signature-v4": "^5.3.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.936.0.tgz", + "integrity": "sha512-dKajFuaugEA5i9gCKzOaVy9uTeZcApE+7Z5wdcZ6j40523fY1a56khDAUYkCfwqa7sHci4ccmxBkAo+fW1RChA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.936.0.tgz", + "integrity": "sha512-5FguODLXG1tWx/x8fBxH+GVrk7Hey2LbXV5h9SFzYCx/2h50URBm0+9hndg0Rd23+xzYe14F6SI9HA9c1sPnjg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/fetch-http-handler": "^5.3.6", + "@smithy/node-http-handler": "^4.4.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/util-stream": "^4.5.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.936.0.tgz", + "integrity": "sha512-TbUv56ERQQujoHcLMcfL0Q6bVZfYF83gu/TjHkVkdSlHPOIKaG/mhE2XZSQzXv1cud6LlgeBbfzVAxJ+HPpffg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/credential-provider-env": "3.936.0", + "@aws-sdk/credential-provider-http": "3.936.0", + "@aws-sdk/credential-provider-login": "3.936.0", + "@aws-sdk/credential-provider-process": "3.936.0", + "@aws-sdk/credential-provider-sso": "3.936.0", + "@aws-sdk/credential-provider-web-identity": "3.936.0", + "@aws-sdk/nested-clients": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/credential-provider-imds": "^4.2.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.936.0.tgz", + "integrity": "sha512-8DVrdRqPyUU66gfV7VZNToh56ZuO5D6agWrkLQE/xbLJOm2RbeRgh6buz7CqV8ipRd6m+zCl9mM4F3osQLZn8Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/nested-clients": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.936.0.tgz", + "integrity": "sha512-rk/2PCtxX9xDsQW8p5Yjoca3StqmQcSfkmD7nQ61AqAHL1YgpSQWqHE+HjfGGiHDYKG7PvE33Ku2GyA7lEIJAw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.936.0", + "@aws-sdk/credential-provider-http": "3.936.0", + "@aws-sdk/credential-provider-ini": "3.936.0", + "@aws-sdk/credential-provider-process": "3.936.0", + "@aws-sdk/credential-provider-sso": "3.936.0", + "@aws-sdk/credential-provider-web-identity": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/credential-provider-imds": "^4.2.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.936.0.tgz", + "integrity": "sha512-GpA4AcHb96KQK2PSPUyvChvrsEKiLhQ5NWjeef2IZ3Jc8JoosiedYqp6yhZR+S8cTysuvx56WyJIJc8y8OTrLA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.936.0.tgz", + "integrity": "sha512-wHlEAJJvtnSyxTfNhN98JcU4taA1ED2JvuI2eePgawqBwS/Tzi0mhED1lvNIaWOkjfLd+nHALwszGrtJwEq4yQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.936.0", + "@aws-sdk/core": "3.936.0", + "@aws-sdk/token-providers": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.936.0.tgz", + "integrity": "sha512-v3qHAuoODkoRXsAF4RG+ZVO6q2P9yYBT4GMpMEfU9wXVNn7AIfwZgTwzSUfnjNiGva5BKleWVpRpJ9DeuLFbUg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/nested-clients": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.936.0.tgz", + "integrity": "sha512-tAaObaAnsP1XnLGndfkGWFuzrJYuk9W0b/nLvol66t8FZExIAf/WdkT2NNAWOYxljVs++oHnyHBCxIlaHrzSiw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.936.0.tgz", + "integrity": "sha512-aPSJ12d3a3Ea5nyEnLbijCaaYJT2QjQ9iW+zGh5QcZYXmOGWbKVyPSxmVOboZQG+c1M8t6d2O7tqrwzIq8L8qw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.936.0.tgz", + "integrity": "sha512-l4aGbHpXM45YNgXggIux1HgsCVAvvBoqHPkqLnqMl9QVapfuSTjJHfDYDsx1Xxct6/m7qSMUzanBALhiaGO2fA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@aws/lambda-invoke-store": "^0.2.0", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-sqs": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-sqs/-/middleware-sdk-sqs-3.936.0.tgz", + "integrity": "sha512-39WohFCCPeD6LV8zLQq7CyYbIieetEDDNLsEPeGJSh2Uv9qpY9r6zJRSTjb8hTuQbHDSEOGntHMYKpLoHdoxdQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.936.0.tgz", + "integrity": "sha512-YB40IPa7K3iaYX0lSnV9easDOLPLh+fJyUDF3BH8doX4i1AOSsYn86L4lVldmOaSX+DwiaqKHpvk4wPBdcIPWw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@aws-sdk/util-endpoints": "3.936.0", + "@smithy/core": "^3.18.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.936.0.tgz", + "integrity": "sha512-eyj2tz1XmDSLSZQ5xnB7cLTVKkSJnYAEoNDSUNhzWPxrBDYeJzIbatecOKceKCU8NBf8gWWZCK/CSY0mDxMO0A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.936.0", + "@aws-sdk/middleware-host-header": "3.936.0", + "@aws-sdk/middleware-logger": "3.936.0", + "@aws-sdk/middleware-recursion-detection": "3.936.0", + "@aws-sdk/middleware-user-agent": "3.936.0", + "@aws-sdk/region-config-resolver": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@aws-sdk/util-endpoints": "3.936.0", + "@aws-sdk/util-user-agent-browser": "3.936.0", + "@aws-sdk/util-user-agent-node": "3.936.0", + "@smithy/config-resolver": "^4.4.3", + "@smithy/core": "^3.18.5", + "@smithy/fetch-http-handler": "^5.3.6", + "@smithy/hash-node": "^4.2.5", + "@smithy/invalid-dependency": "^4.2.5", + "@smithy/middleware-content-length": "^4.2.5", + "@smithy/middleware-endpoint": "^4.3.12", + "@smithy/middleware-retry": "^4.4.12", + "@smithy/middleware-serde": "^4.2.6", + "@smithy/middleware-stack": "^4.2.5", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/node-http-handler": "^4.4.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.1", + "@smithy/util-defaults-mode-browser": "^4.3.11", + "@smithy/util-defaults-mode-node": "^4.2.14", + "@smithy/util-endpoints": "^3.2.5", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-retry": "^4.2.5", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.936.0.tgz", + "integrity": "sha512-wOKhzzWsshXGduxO4pqSiNyL9oUtk4BEvjWm9aaq6Hmfdoydq6v6t0rAGHWPjFwy9z2haovGRi3C8IxdMB4muw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/config-resolver": "^4.4.3", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.936.0.tgz", + "integrity": "sha512-vvw8+VXk0I+IsoxZw0mX9TMJawUJvEsg3EF7zcCSetwhNPAU8Xmlhv7E/sN/FgSmm7b7DsqKoW6rVtQiCs1PWQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.936.0", + "@aws-sdk/nested-clients": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.936.0.tgz", + "integrity": "sha512-uz0/VlMd2pP5MepdrHizd+T+OKfyK4r3OA9JI+L/lPKg0YFQosdJNCKisr6o70E3dh8iMpFYxF1UN/4uZsyARg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.936.0.tgz", + "integrity": "sha512-0Zx3Ntdpu+z9Wlm7JKUBOzS9EunwKAb4KdGUQQxDqh5Lc3ta5uBoub+FgmVuzwnmBu9U1Os8UuwVTH0Lgu+P5w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "@smithy/util-endpoints": "^3.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.893.0.tgz", + "integrity": "sha512-T89pFfgat6c8nMmpI8eKjBcDcgJq36+m9oiXbcUzeU55MP9ZuGgBomGjGnHaEyF36jenW9gmg3NfZDm0AO2XPg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.936.0.tgz", + "integrity": "sha512-eZ/XF6NxMtu+iCma58GRNRxSq4lHo6zHQLOZRIeL/ghqYJirqHdenMOwrzPettj60KWlv827RVebP9oNVrwZbw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.936.0", + "@smithy/types": "^4.9.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.936.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.936.0.tgz", + "integrity": "sha512-XOEc7PF9Op00pWV2AYCGDSu5iHgYjIO53Py2VUQTIvP7SRCaCsXmA33mjBvC2Ms6FhSyWNa4aK4naUGIz0hQcw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.936.0", + "@aws-sdk/types": "3.936.0", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.930.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.930.0.tgz", + "integrity": "sha512-YIfkD17GocxdmlUVc3ia52QhcWuRIUJonbF8A2CYfcWNV3HzvAqpcPeC0bYUhkK+8e8YO1ARnLKZQE0TlwzorA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "fast-xml-parser": "5.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.1.tgz", + "integrity": "sha512-sIyFcoPZkTtNu9xFeEoynMef3bPJIAbOfUh+ueYcfhVl6xm2VRtMcMclSxmZCMnHHd4hlYKJeq/aggmBEWynww==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", + "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz", + "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.0.tgz", + "integrity": "sha512-X999CKBxGwX8wW+4gFibsbiNdwqmdQEXmUejIWaIqdrHBgS5ARIOOeyiQbHjP9G58xVEPcuvP6VwwH3A0OFTOA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@cacheable/memory": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.0.5.tgz", + "integrity": "sha512-fkiAxCvssEyJZ5fxX4tcdZFRmW9JehSTGvvqmXn6rTzG5cH6V/3C4ad8yb01vOjp2xBydHkHrgpW0qeGtzt6VQ==", + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.3.0", + "@keyv/bigmap": "^1.1.0", + "hookified": "^1.12.2", + "keyv": "^5.5.4" + } + }, + "node_modules/@cacheable/node-cache": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@cacheable/node-cache/-/node-cache-1.7.5.tgz", + "integrity": "sha512-awY5UuLseuR5ytutXefzyEQeVXCm1reQqahAp1Qd39+mTzOaTV3VJx9qoX7juICEfYI0Q1SFj2m2+83l6+6UbQ==", + "license": "MIT", + "dependencies": { + "cacheable": "^2.2.0", + "hookified": "^1.13.0", + "keyv": "^5.5.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.3.1.tgz", + "integrity": "sha512-38NJXjIr4W1Sghun8ju+uYWD8h2c61B4dKwfnQHVDFpAJ9oS28RpfqZQJ6Dgd3RceGkILDY9YT+72HJR3LoeSQ==", + "license": "MIT", + "dependencies": { + "hashery": "^1.2.0", + "keyv": "^5.5.4" + } + }, + "node_modules/@commitlint/cli": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/cli/-/cli-19.8.1.tgz", + "integrity": "sha512-LXUdNIkspyxrlV6VDHWBmCZRtkEVRpBKxi2Gtw3J54cGWhLCTouVD/Q6ZSaSvd2YaDObWK8mDjrz3TIKtaQMAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/format": "^19.8.1", + "@commitlint/lint": "^19.8.1", + "@commitlint/load": "^19.8.1", + "@commitlint/read": "^19.8.1", + "@commitlint/types": "^19.8.1", + "tinyexec": "^1.0.0", + "yargs": "^17.0.0" + }, + "bin": { + "commitlint": "cli.js" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/config-conventional": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/config-conventional/-/config-conventional-19.8.1.tgz", + "integrity": "sha512-/AZHJL6F6B/G959CsMAzrPKKZjeEiAVifRyEwXxcT6qtqbPwGw+iQxmNS+Bu+i09OCtdNRW6pNpBvgPrtMr9EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "conventional-changelog-conventionalcommits": "^7.0.2" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/config-validator": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/config-validator/-/config-validator-19.8.1.tgz", + "integrity": "sha512-0jvJ4u+eqGPBIzzSdqKNX1rvdbSU1lPNYlfQQRIFnBgLy26BtC0cFnr7c/AyuzExMxWsMOte6MkTi9I3SQ3iGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "ajv": "^8.11.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/ensure": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/ensure/-/ensure-19.8.1.tgz", + "integrity": "sha512-mXDnlJdvDzSObafjYrOSvZBwkD01cqB4gbnnFuVyNpGUM5ijwU/r/6uqUmBXAAOKRfyEjpkGVZxaDsCVnHAgyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "lodash.camelcase": "^4.3.0", + "lodash.kebabcase": "^4.1.1", + "lodash.snakecase": "^4.1.1", + "lodash.startcase": "^4.4.0", + "lodash.upperfirst": "^4.3.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/execute-rule": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/execute-rule/-/execute-rule-19.8.1.tgz", + "integrity": "sha512-YfJyIqIKWI64Mgvn/sE7FXvVMQER/Cd+s3hZke6cI1xgNT/f6ZAz5heND0QtffH+KbcqAwXDEE1/5niYayYaQA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/format": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/format/-/format-19.8.1.tgz", + "integrity": "sha512-kSJj34Rp10ItP+Eh9oCItiuN/HwGQMXBnIRk69jdOwEW9llW9FlyqcWYbHPSGofmjsqeoxa38UaEA5tsbm2JWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "chalk": "^5.3.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/is-ignored": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/is-ignored/-/is-ignored-19.8.1.tgz", + "integrity": "sha512-AceOhEhekBUQ5dzrVhDDsbMaY5LqtN8s1mqSnT2Kz1ERvVZkNihrs3Sfk1Je/rxRNbXYFzKZSHaPsEJJDJV8dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "semver": "^7.6.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/lint": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/lint/-/lint-19.8.1.tgz", + "integrity": "sha512-52PFbsl+1EvMuokZXLRlOsdcLHf10isTPlWwoY1FQIidTsTvjKXVXYb7AvtpWkDzRO2ZsqIgPK7bI98x8LRUEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/is-ignored": "^19.8.1", + "@commitlint/parse": "^19.8.1", + "@commitlint/rules": "^19.8.1", + "@commitlint/types": "^19.8.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/load": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/load/-/load-19.8.1.tgz", + "integrity": "sha512-9V99EKG3u7z+FEoe4ikgq7YGRCSukAcvmKQuTtUyiYPnOd9a2/H9Ak1J9nJA1HChRQp9OA/sIKPugGS+FK/k1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/config-validator": "^19.8.1", + "@commitlint/execute-rule": "^19.8.1", + "@commitlint/resolve-extends": "^19.8.1", + "@commitlint/types": "^19.8.1", + "chalk": "^5.3.0", + "cosmiconfig": "^9.0.0", + "cosmiconfig-typescript-loader": "^6.1.0", + "lodash.isplainobject": "^4.0.6", + "lodash.merge": "^4.6.2", + "lodash.uniq": "^4.5.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/message": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/message/-/message-19.8.1.tgz", + "integrity": "sha512-+PMLQvjRXiU+Ae0Wc+p99EoGEutzSXFVwQfa3jRNUZLNW5odZAyseb92OSBTKCu+9gGZiJASt76Cj3dLTtcTdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/parse": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/parse/-/parse-19.8.1.tgz", + "integrity": "sha512-mmAHYcMBmAgJDKWdkjIGq50X4yB0pSGpxyOODwYmoexxxiUCy5JJT99t1+PEMK7KtsCtzuWYIAXYAiKR+k+/Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "conventional-changelog-angular": "^7.0.0", + "conventional-commits-parser": "^5.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/read": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/read/-/read-19.8.1.tgz", + "integrity": "sha512-03Jbjb1MqluaVXKHKRuGhcKWtSgh3Jizqy2lJCRbRrnWpcM06MYm8th59Xcns8EqBYvo0Xqb+2DoZFlga97uXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/top-level": "^19.8.1", + "@commitlint/types": "^19.8.1", + "git-raw-commits": "^4.0.0", + "minimist": "^1.2.8", + "tinyexec": "^1.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/resolve-extends": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/resolve-extends/-/resolve-extends-19.8.1.tgz", + "integrity": "sha512-GM0mAhFk49I+T/5UCYns5ayGStkTt4XFFrjjf0L4S26xoMTSkdCf9ZRO8en1kuopC4isDFuEm7ZOm/WRVeElVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/config-validator": "^19.8.1", + "@commitlint/types": "^19.8.1", + "global-directory": "^4.0.1", + "import-meta-resolve": "^4.0.0", + "lodash.mergewith": "^4.6.2", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/rules": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/rules/-/rules-19.8.1.tgz", + "integrity": "sha512-Hnlhd9DyvGiGwjfjfToMi1dsnw1EXKGJNLTcsuGORHz6SS9swRgkBsou33MQ2n51/boIDrbsg4tIBbRpEWK2kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/ensure": "^19.8.1", + "@commitlint/message": "^19.8.1", + "@commitlint/to-lines": "^19.8.1", + "@commitlint/types": "^19.8.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/to-lines": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/to-lines/-/to-lines-19.8.1.tgz", + "integrity": "sha512-98Mm5inzbWTKuZQr2aW4SReY6WUukdWXuZhrqf1QdKPZBCCsXuG87c+iP0bwtD6DBnmVVQjgp4whoHRVixyPBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/top-level": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/top-level/-/top-level-19.8.1.tgz", + "integrity": "sha512-Ph8IN1IOHPSDhURCSXBz44+CIu+60duFwRsg6HqaISFHQHbmBtxVw4ZrFNIYUzEP7WwrNPxa2/5qJ//NK1FGcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^7.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/types": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/types/-/types-19.8.1.tgz", + "integrity": "sha512-/yCrWGCoA1SVKOks25EGadP9Pnj0oAIHGpl2wH2M2Y46dPM2ueb8wyCVOD7O3WCTkaJ0IkKvzhl1JY7+uCT2Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/conventional-commits-parser": "^5.0.0", + "chalk": "^5.3.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.7.1.tgz", + "integrity": "sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz", + "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz", + "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz", + "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz", + "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz", + "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz", + "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz", + "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz", + "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz", + "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz", + "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz", + "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz", + "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz", + "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz", + "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz", + "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz", + "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz", + "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz", + "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz", + "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz", + "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz", + "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz", + "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz", + "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz", + "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz", + "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz", + "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eshaz/web-worker": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@eshaz/web-worker/-/web-worker-1.2.2.tgz", + "integrity": "sha512-WxXiHFmD9u/owrzempiDlBB1ZYqiLnm9s6aPc8AlFQalq2tKmqdmMr9GXOupDgzXtqnBipj8Un0gkIm7Sjf8mw==", + "license": "Apache-2.0" + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", + "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", + "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@ffmpeg-installer/darwin-arm64": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-arm64/-/darwin-arm64-4.1.5.tgz", + "integrity": "sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "https://git.ffmpeg.org/gitweb/ffmpeg.git/blob_plain/HEAD:/LICENSE.md", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/darwin-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-x64/-/darwin-x64-4.1.0.tgz", + "integrity": "sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "LGPL-2.1", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/ffmpeg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/ffmpeg/-/ffmpeg-1.1.0.tgz", + "integrity": "sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==", + "license": "LGPL-2.1", + "optionalDependencies": { + "@ffmpeg-installer/darwin-arm64": "4.1.5", + "@ffmpeg-installer/darwin-x64": "4.1.0", + "@ffmpeg-installer/linux-arm": "4.1.3", + "@ffmpeg-installer/linux-arm64": "4.1.4", + "@ffmpeg-installer/linux-ia32": "4.1.0", + "@ffmpeg-installer/linux-x64": "4.1.0", + "@ffmpeg-installer/win32-ia32": "4.1.0", + "@ffmpeg-installer/win32-x64": "4.1.0" + } + }, + "node_modules/@ffmpeg-installer/linux-arm": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm/-/linux-arm-4.1.3.tgz", + "integrity": "sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==", + "cpu": [ + "arm" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-arm64": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm64/-/linux-arm64-4.1.4.tgz", + "integrity": "sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-ia32/-/linux-ia32-4.1.0.tgz", + "integrity": "sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==", + "cpu": [ + "ia32" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-x64/-/linux-x64-4.1.0.tgz", + "integrity": "sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "license": "GPLv3", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/win32-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-ia32/-/win32-ia32-4.1.0.tgz", + "integrity": "sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==", + "cpu": [ + "ia32" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ffmpeg-installer/win32-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-x64/-/win32-x64-4.1.0.tgz", + "integrity": "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==", + "cpu": [ + "x64" + ], + "license": "GPLv3", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@figuro/chatwoot-sdk": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@figuro/chatwoot-sdk/-/chatwoot-sdk-1.1.17.tgz", + "integrity": "sha512-KfrBoMLMAan3379evYqmC2gUKYWGRJb0g+1EQZ44vUcDxOGlH5riddK1OB998Knvm0TYNZBqKhhwJHqDYBUpSw==", + "license": "MIT", + "dependencies": { + "axios": "^0.27.2" + } + }, + "node_modules/@figuro/chatwoot-sdk/node_modules/axios": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", + "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.14.9", + "form-data": "^4.0.0" + } + }, + "node_modules/@hapi/boom": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@hapi/boom/-/boom-10.0.1.tgz", + "integrity": "sha512-ERcCZaEjdH3OgSJlyjVk8pHIFeus91CjKP3v+MpgBNp5IvGzP2l/bRiD78nqYcKPaZdbKkK5vDBVPd2ohHBlsA==", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "^11.0.2" + } + }, + "node_modules/@hapi/hoek": { + "version": "11.0.7", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-11.0.7.tgz", + "integrity": "sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", + "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", + "deprecated": "Use @eslint/config-array instead", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanwhocodes/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", + "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", + "deprecated": "Use @eslint/object-schema instead", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@img/colour": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz", + "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jimp/core": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/core/-/core-1.6.0.tgz", + "integrity": "sha512-EQQlKU3s9QfdJqiSrZWNTxBs3rKXgO2W+GxNXDtwchF3a4IqxDheFX1ti+Env9hdJXDiYLp2jTRjlxhPthsk8w==", + "license": "MIT", + "dependencies": { + "@jimp/file-ops": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "await-to-js": "^3.0.0", + "exif-parser": "^0.1.12", + "file-type": "^16.0.0", + "mime": "3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/core/node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@jimp/diff": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/diff/-/diff-1.6.0.tgz", + "integrity": "sha512-+yUAQ5gvRC5D1WHYxjBHZI7JBRusGGSLf8AmPRPCenTzh4PA+wZ1xv2+cYqQwTfQHU5tXYOhA0xDytfHUf1Zyw==", + "license": "MIT", + "dependencies": { + "@jimp/plugin-resize": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "pixelmatch": "^5.3.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/file-ops": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/file-ops/-/file-ops-1.6.0.tgz", + "integrity": "sha512-Dx/bVDmgnRe1AlniRpCKrGRm5YvGmUwbDzt+MAkgmLGf+jvBT75hmMEZ003n9HQI/aPnm/YKnXjg/hOpzNCpHQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/js-bmp": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/js-bmp/-/js-bmp-1.6.0.tgz", + "integrity": "sha512-FU6Q5PC/e3yzLyBDXupR3SnL3htU7S3KEs4e6rjDP6gNEOXRFsWs6YD3hXuXd50jd8ummy+q2WSwuGkr8wi+Gw==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "bmp-ts": "^1.0.9" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/js-gif": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/js-gif/-/js-gif-1.6.0.tgz", + "integrity": "sha512-N9CZPHOrJTsAUoWkWZstLPpwT5AwJ0wge+47+ix3++SdSL/H2QzyMqxbcDYNFe4MoI5MIhATfb0/dl/wmX221g==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "gifwrap": "^0.10.1", + "omggif": "^1.0.10" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/js-jpeg": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/js-jpeg/-/js-jpeg-1.6.0.tgz", + "integrity": "sha512-6vgFDqeusblf5Pok6B2DUiMXplH8RhIKAryj1yn+007SIAQ0khM1Uptxmpku/0MfbClx2r7pnJv9gWpAEJdMVA==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "jpeg-js": "^0.4.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/js-png": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/js-png/-/js-png-1.6.0.tgz", + "integrity": "sha512-AbQHScy3hDDgMRNfG0tPjL88AV6qKAILGReIa3ATpW5QFjBKpisvUaOqhzJ7Reic1oawx3Riyv152gaPfqsBVg==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "pngjs": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/js-tiff": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/js-tiff/-/js-tiff-1.6.0.tgz", + "integrity": "sha512-zhReR8/7KO+adijj3h0ZQUOiun3mXUv79zYEAKvE0O+rP7EhgtKvWJOZfRzdZSNv0Pu1rKtgM72qgtwe2tFvyw==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "utif2": "^4.1.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-blit": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-blit/-/plugin-blit-1.6.0.tgz", + "integrity": "sha512-M+uRWl1csi7qilnSK8uxK4RJMSuVeBiO1AY0+7APnfUbQNZm6hCe0CCFv1Iyw1D/Dhb8ph8fQgm5mwM0eSxgVA==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-blur": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-blur/-/plugin-blur-1.6.0.tgz", + "integrity": "sha512-zrM7iic1OTwUCb0g/rN5y+UnmdEsT3IfuCXCJJNs8SZzP0MkZ1eTvuwK9ZidCuMo4+J3xkzCidRwYXB5CyGZTw==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/utils": "1.6.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-circle": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-circle/-/plugin-circle-1.6.0.tgz", + "integrity": "sha512-xt1Gp+LtdMKAXfDp3HNaG30SPZW6AQ7dtAtTnoRKorRi+5yCJjKqXRgkewS5bvj8DEh87Ko1ydJfzqS3P2tdWw==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-color": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-color/-/plugin-color-1.6.0.tgz", + "integrity": "sha512-J5q8IVCpkBsxIXM+45XOXTrsyfblyMZg3a9eAo0P7VPH4+CrvyNQwaYatbAIamSIN1YzxmO3DkIZXzRjFSz1SA==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "tinycolor2": "^1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-contain": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-contain/-/plugin-contain-1.6.0.tgz", + "integrity": "sha512-oN/n+Vdq/Qg9bB4yOBOxtY9IPAtEfES8J1n9Ddx+XhGBYT1/QTU/JYkGaAkIGoPnyYvmLEDqMz2SGihqlpqfzQ==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/plugin-blit": "1.6.0", + "@jimp/plugin-resize": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-cover": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-cover/-/plugin-cover-1.6.0.tgz", + "integrity": "sha512-Iow0h6yqSC269YUJ8HC3Q/MpCi2V55sMlbkkTTx4zPvd8mWZlC0ykrNDeAy9IJegrQ7v5E99rJwmQu25lygKLA==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/plugin-crop": "1.6.0", + "@jimp/plugin-resize": "1.6.0", + "@jimp/types": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-crop": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-crop/-/plugin-crop-1.6.0.tgz", + "integrity": "sha512-KqZkEhvs+21USdySCUDI+GFa393eDIzbi1smBqkUPTE+pRwSWMAf01D5OC3ZWB+xZsNla93BDS9iCkLHA8wang==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-displace": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-displace/-/plugin-displace-1.6.0.tgz", + "integrity": "sha512-4Y10X9qwr5F+Bo5ME356XSACEF55485j5nGdiyJ9hYzjQP9nGgxNJaZ4SAOqpd+k5sFaIeD7SQ0Occ26uIng5Q==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-dither": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-dither/-/plugin-dither-1.6.0.tgz", + "integrity": "sha512-600d1RxY0pKwgyU0tgMahLNKsqEcxGdbgXadCiVCoGd6V6glyCvkNrnnwC0n5aJ56Htkj88PToSdF88tNVZEEQ==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-fisheye": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-fisheye/-/plugin-fisheye-1.6.0.tgz", + "integrity": "sha512-E5QHKWSCBFtpgZarlmN3Q6+rTQxjirFqo44ohoTjzYVrDI6B6beXNnPIThJgPr0Y9GwfzgyarKvQuQuqCnnfbA==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-flip": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-flip/-/plugin-flip-1.6.0.tgz", + "integrity": "sha512-/+rJVDuBIVOgwoyVkBjUFHtP+wmW0r+r5OQ2GpatQofToPVbJw1DdYWXlwviSx7hvixTWLKVgRWQ5Dw862emDg==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-hash": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-hash/-/plugin-hash-1.6.0.tgz", + "integrity": "sha512-wWzl0kTpDJgYVbZdajTf+4NBSKvmI3bRI8q6EH9CVeIHps9VWVsUvEyb7rpbcwVLWYuzDtP2R0lTT6WeBNQH9Q==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/js-bmp": "1.6.0", + "@jimp/js-jpeg": "1.6.0", + "@jimp/js-png": "1.6.0", + "@jimp/js-tiff": "1.6.0", + "@jimp/plugin-color": "1.6.0", + "@jimp/plugin-resize": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "any-base": "^1.1.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-mask": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-mask/-/plugin-mask-1.6.0.tgz", + "integrity": "sha512-Cwy7ExSJMZszvkad8NV8o/Z92X2kFUFM8mcDAhNVxU0Q6tA0op2UKRJY51eoK8r6eds/qak3FQkXakvNabdLnA==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-print": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-print/-/plugin-print-1.6.0.tgz", + "integrity": "sha512-zarTIJi8fjoGMSI/M3Xh5yY9T65p03XJmPsuNet19K/Q7mwRU6EV2pfj+28++2PV2NJ+htDF5uecAlnGyxFN2A==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/js-jpeg": "1.6.0", + "@jimp/js-png": "1.6.0", + "@jimp/plugin-blit": "1.6.0", + "@jimp/types": "1.6.0", + "parse-bmfont-ascii": "^1.0.6", + "parse-bmfont-binary": "^1.0.6", + "parse-bmfont-xml": "^1.1.6", + "simple-xml-to-json": "^1.2.2", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-quantize": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-quantize/-/plugin-quantize-1.6.0.tgz", + "integrity": "sha512-EmzZ/s9StYQwbpG6rUGBCisc3f64JIhSH+ncTJd+iFGtGo0YvSeMdAd+zqgiHpfZoOL54dNavZNjF4otK+mvlg==", + "license": "MIT", + "dependencies": { + "image-q": "^4.0.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-resize": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-resize/-/plugin-resize-1.6.0.tgz", + "integrity": "sha512-uSUD1mqXN9i1SGSz5ov3keRZ7S9L32/mAQG08wUwZiEi5FpbV0K8A8l1zkazAIZi9IJzLlTauRNU41Mi8IF9fA==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/types": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-rotate": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-rotate/-/plugin-rotate-1.6.0.tgz", + "integrity": "sha512-JagdjBLnUZGSG4xjCLkIpQOZZ3Mjbg8aGCCi4G69qR+OjNpOeGI7N2EQlfK/WE8BEHOW5vdjSyglNqcYbQBWRw==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/plugin-crop": "1.6.0", + "@jimp/plugin-resize": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/plugin-threshold": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/plugin-threshold/-/plugin-threshold-1.6.0.tgz", + "integrity": "sha512-M59m5dzLoHOVWdM41O8z9SyySzcDn43xHseOH0HavjsfQsT56GGCC4QzU1banJidbUrePhzoEdS42uFE8Fei8w==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/plugin-color": "1.6.0", + "@jimp/plugin-hash": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0", + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/types": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/types/-/types-1.6.0.tgz", + "integrity": "sha512-7UfRsiKo5GZTAATxm2qQ7jqmUXP0DxTArztllTcYdyw6Xi5oT4RaoXynVtCD4UyLK5gJgkZJcwonoijrhYFKfg==", + "license": "MIT", + "dependencies": { + "zod": "^3.23.8" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jimp/utils": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jimp/utils/-/utils-1.6.0.tgz", + "integrity": "sha512-gqFTGEosKbOkYF/WFj26jMHOI5OH2jeP1MmC/zbK6BF6VJBf8rIC5898dPfSzZEbSA0wbbV5slbntWVc5PKLFA==", + "license": "MIT", + "dependencies": { + "@jimp/types": "1.6.0", + "tinycolor2": "^1.6.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@keyv/bigmap": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.0.tgz", + "integrity": "sha512-KT01GjzV6AQD5+IYrcpoYLkCu1Jod3nau1Z7EsEuViO3TZGRacSbO9MfHmbJ1WaOXFtWLxPVj169cn2WNKPkIg==", + "license": "MIT", + "dependencies": { + "hashery": "^1.2.0", + "hookified": "^1.13.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.5.4" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "license": "MIT" + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.204.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.204.0.tgz", + "integrity": "sha512-DqxY8yoAaiBPivoJD4UtgrMS8gEmzZ5lnaxzPojzLVHBGqPxgWm4zcuvcUHZiqQ6kRX2Klel2r9y8cA2HAtqpw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.2.0.tgz", + "integrity": "sha512-qRkLWiUEZNAmYapZ7KGS5C4OmBLcP/H2foXeOEaowYCR0wi89fHejrfYfbuLVCMLp/dWZXKvQusdbUEZjERfwQ==", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.2.0.tgz", + "integrity": "sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/instrumentation": { + "version": "0.204.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.204.0.tgz", + "integrity": "sha512-vV5+WSxktzoMP8JoYWKeopChy6G3HKk4UQ2hESCRDUUTZqQ3+nM3u8noVG0LmNfRWwcFBnbZ71GKC7vaYYdJ1g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.204.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-amqplib": { + "version": "0.51.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.51.0.tgz", + "integrity": "sha512-XGmjYwjVRktD4agFnWBWQXo9SiYHKBxR6Ag3MLXwtLE4R99N3a08kGKM5SC1qOFKIELcQDGFEFT9ydXMH00Luw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-connect": { + "version": "0.48.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.48.0.tgz", + "integrity": "sha512-OMjc3SFL4pC16PeK+tDhwP7MRvDPalYCGSvGqUhX5rASkI2H0RuxZHOWElYeXkV0WP+70Gw6JHWac/2Zqwmhdw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0", + "@types/connect": "3.4.38" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-dataloader": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.22.0.tgz", + "integrity": "sha512-bXnTcwtngQsI1CvodFkTemrrRSQjAjZxqHVc+CJZTDnidT0T6wt3jkKhnsjU/Kkkc0lacr6VdRpCu2CUWa0OKw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-express": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.53.0.tgz", + "integrity": "sha512-r/PBafQmFYRjuxLYEHJ3ze1iBnP2GDA1nXOSS6E02KnYNZAVjj6WcDA1MSthtdAUUK0XnotHvvWM8/qz7DMO5A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-fs": { + "version": "0.24.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.24.0.tgz", + "integrity": "sha512-HjIxJ6CBRD770KNVaTdMXIv29Sjz4C1kPCCK5x1Ujpc6SNnLGPqUVyJYZ3LUhhnHAqdbrl83ogVWjCgeT4Q0yw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-generic-pool": { + "version": "0.48.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.48.0.tgz", + "integrity": "sha512-TLv/On8pufynNR+pUbpkyvuESVASZZKMlqCm4bBImTpXKTpqXaJJ3o/MUDeMlM91rpen+PEv2SeyOKcHCSlgag==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-graphql": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.52.0.tgz", + "integrity": "sha512-3fEJ8jOOMwopvldY16KuzHbRhPk8wSsOTSF0v2psmOCGewh6ad+ZbkTx/xyUK9rUdUMWAxRVU0tFpj4Wx1vkPA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-hapi": { + "version": "0.51.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.51.0.tgz", + "integrity": "sha512-qyf27DaFNL1Qhbo/da+04MSCw982B02FhuOS5/UF+PMhM61CcOiu7fPuXj8TvbqyReQuJFljXE6UirlvoT/62g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-http": { + "version": "0.204.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.204.0.tgz", + "integrity": "sha512-1afJYyGRA4OmHTv0FfNTrTAzoEjPQUYgd+8ih/lX0LlZBnGio/O80vxA0lN3knsJPS7FiDrsDrWq25K7oAzbkw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.1.0", + "@opentelemetry/instrumentation": "0.204.0", + "@opentelemetry/semantic-conventions": "^1.29.0", + "forwarded-parse": "2.1.2" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/core": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.1.0.tgz", + "integrity": "sha512-RMEtHsxJs/GiHHxYT58IY57UXAQTuUnZVco6ymDEqTNlJKTimM4qPUPVe8InNFyBjhHBEAx4k3Q8LtNayBsbUQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/instrumentation-ioredis": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.52.0.tgz", + "integrity": "sha512-rUvlyZwI90HRQPYicxpDGhT8setMrlHKokCtBtZgYxQWRF5RBbG4q0pGtbZvd7kyseuHbFpA3I/5z7M8b/5ywg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/redis-common": "^0.38.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-kafkajs": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.14.0.tgz", + "integrity": "sha512-kbB5yXS47dTIdO/lfbbXlzhvHFturbux4EpP0+6H78Lk0Bn4QXiZQW7rmZY1xBCY16mNcCb8Yt0mhz85hTnSVA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.30.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-knex": { + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.49.0.tgz", + "integrity": "sha512-NKsRRT27fbIYL4Ix+BjjP8h4YveyKc+2gD6DMZbr5R5rUeDqfC8+DTfIt3c3ex3BIc5Vvek4rqHnN7q34ZetLQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.33.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-koa": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.52.0.tgz", + "integrity": "sha512-JJSBYLDx/mNSy8Ibi/uQixu2rH0bZODJa8/cz04hEhRaiZQoeJ5UrOhO/mS87IdgVsHrnBOsZ6vDu09znupyuA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-lru-memoizer": { + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.49.0.tgz", + "integrity": "sha512-ctXu+O/1HSadAxtjoEg2w307Z5iPyLOMM8IRNwjaKrIpNAthYGSOanChbk1kqY6zU5CrpkPHGdAT6jk8dXiMqw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-mongodb": { + "version": "0.57.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.57.0.tgz", + "integrity": "sha512-KD6Rg0KSHWDkik+qjIOWoksi1xqSpix8TSPfquIK1DTmd9OTFb5PHmMkzJe16TAPVEuElUW8gvgP59cacFcrMQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-mongoose": { + "version": "0.51.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.51.0.tgz", + "integrity": "sha512-gwWaAlhhV2By7XcbyU3DOLMvzsgeaymwP/jktDC+/uPkCmgB61zurwqOQdeiRq9KAf22Y2dtE5ZLXxytJRbEVA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-mysql": { + "version": "0.50.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.50.0.tgz", + "integrity": "sha512-duKAvMRI3vq6u9JwzIipY9zHfikN20bX05sL7GjDeLKr2qV0LQ4ADtKST7KStdGcQ+MTN5wghWbbVdLgNcB3rA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0", + "@types/mysql": "2.15.27" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-mysql2": { + "version": "0.51.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.51.0.tgz", + "integrity": "sha512-zT2Wg22Xn43RyfU3NOUmnFtb5zlDI0fKcijCj9AcK9zuLZ4ModgtLXOyBJSSfO+hsOCZSC1v/Fxwj+nZJFdzLQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0", + "@opentelemetry/sql-common": "^0.41.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-pg": { + "version": "0.57.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.57.0.tgz", + "integrity": "sha512-dWLGE+r5lBgm2A8SaaSYDE3OKJ/kwwy5WLyGyzor8PLhUL9VnJRiY6qhp4njwhnljiLtzeffRtG2Mf/YyWLeTw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.34.0", + "@opentelemetry/sql-common": "^0.41.0", + "@types/pg": "8.15.5", + "@types/pg-pool": "2.0.6" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-redis": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis/-/instrumentation-redis-0.53.0.tgz", + "integrity": "sha512-WUHV8fr+8yo5RmzyU7D5BIE1zwiaNQcTyZPwtxlfr7px6NYYx7IIpSihJK7WA60npWynfxxK1T67RAVF0Gdfjg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/redis-common": "^0.38.0", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-tedious": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.23.0.tgz", + "integrity": "sha512-3TMTk/9VtlRonVTaU4tCzbg4YqW+Iq/l5VnN2e5whP6JgEg/PKfrGbqQ+CxQWNLfLaQYIUgEZqAn5gk/inh1uQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/semantic-conventions": "^1.27.0", + "@types/tedious": "^4.0.14" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-undici": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.15.0.tgz", + "integrity": "sha512-sNFGA/iCDlVkNjzTzPRcudmI11vT/WAfAguRdZY9IspCw02N4WSC72zTuQhSMheh2a1gdeM9my1imnKRvEEvEg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/instrumentation": "^0.204.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.7.0" + } + }, + "node_modules/@opentelemetry/redis-common": { + "version": "0.38.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/redis-common/-/redis-common-0.38.2.tgz", + "integrity": "sha512-1BCcU93iwSRZvDAgwUxC/DV4T/406SkMfxGqu5ojc3AvNI+I9GhV7v0J1HljsczuuhcnFLYqD5VmwVXfCGHzxA==", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.2.0.tgz", + "integrity": "sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.2.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.2.0.tgz", + "integrity": "sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.2.0", + "@opentelemetry/resources": "2.2.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.38.0.tgz", + "integrity": "sha512-kocjix+/sSggfJhwXqClZ3i9Y/MI0fp7b+g7kCRm6psy2dsf8uApTRclwG18h8Avm7C9+fnt+O36PspJ/OzoWg==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/sql-common": { + "version": "0.41.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/sql-common/-/sql-common-0.41.2.tgz", + "integrity": "sha512-4mhWm3Z8z+i508zQJ7r6Xi7y4mmoJpdvH0fZPFRkWrdp5fq7hhZ2HhYokEOLkfqSMgPR4Z9EyB3DBkbKGOqZiQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^2.0.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0" + } + }, + "node_modules/@paralleldrive/cuid2": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", + "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.1.5" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/@pkgr/core": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz", + "integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/pkgr" + } + }, + "node_modules/@prisma/client": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.19.0.tgz", + "integrity": "sha512-QXFT+N/bva/QI2qoXmjBzL7D6aliPffIwP+81AdTGq0FXDoLxLkWivGMawG8iM5B9BKfxLIXxfWWAF6wbuJU6g==", + "hasInstallScript": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "prisma": "*", + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@prisma/config": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.19.0.tgz", + "integrity": "sha512-zwCayme+NzI/WfrvFEtkFhhOaZb/hI+X8TTjzjJ252VbPxAl2hWHK5NMczmnG9sXck2lsXrxIZuK524E25UNmg==", + "license": "Apache-2.0", + "dependencies": { + "c12": "3.1.0", + "deepmerge-ts": "7.1.5", + "effect": "3.18.4", + "empathic": "2.0.0" + } + }, + "node_modules/@prisma/debug": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.19.0.tgz", + "integrity": "sha512-8hAdGG7JmxrzFcTzXZajlQCidX0XNkMJkpqtfbLV54wC6LSSX6Vni25W/G+nAANwLnZ2TmwkfIuWetA7jJxJFA==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.19.0.tgz", + "integrity": "sha512-pMRJ+1S6NVdXoB8QJAPIGpKZevFjxhKt0paCkRDTZiczKb7F4yTgRP8M4JdVkpQwmaD4EoJf6qA+p61godDokw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0", + "@prisma/engines-version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "@prisma/fetch-engine": "6.19.0", + "@prisma/get-platform": "6.19.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773.tgz", + "integrity": "sha512-gV7uOBQfAFlWDvPJdQxMT1aSRur3a0EkU/6cfbAC5isV67tKDWUrPauyaHNpB+wN1ebM4A9jn/f4gH+3iHSYSQ==", + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.19.0.tgz", + "integrity": "sha512-OOx2Lda0DGrZ1rodADT06ZGqHzr7HY7LNMaFE2Vp8dp146uJld58sRuasdX0OiwpHgl8SqDTUKHNUyzEq7pDdQ==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0", + "@prisma/engines-version": "6.19.0-26.2ba551f319ab1df4bc874a89965d8b3641056773", + "@prisma/get-platform": "6.19.0" + } + }, + "node_modules/@prisma/get-platform": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.19.0.tgz", + "integrity": "sha512-ym85WDO2yDhC3fIXHWYpG3kVMBA49cL1XD2GCsCF8xbwoy2OkDQY44gEbAt2X46IQ4Apq9H6g0Ex1iFfPqEkHA==", + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.0" + } + }, + "node_modules/@prisma/instrumentation": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/@prisma/instrumentation/-/instrumentation-6.15.0.tgz", + "integrity": "sha512-6TXaH6OmDkMOQvOxwLZ8XS51hU2v4A3vmE2pSijCIiGRJYyNeMcL6nMHQMyYdZRD8wl7LF3Wzc+AMPMV/9Oo7A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.8" + } + }, + "node_modules/@prisma/instrumentation/node_modules/@opentelemetry/api-logs": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.2.tgz", + "integrity": "sha512-uIX52NnTM0iBh84MShlpouI7UKqkZ7MrUszTmaypHBu4r7NofznSnQRfJ+uUeDtQDj6w8eFGg5KBLDAwAPz1+A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@prisma/instrumentation/node_modules/@opentelemetry/instrumentation": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.2.tgz", + "integrity": "sha512-BdBGhQBh8IjZ2oIIX6F2/Q3LKm/FDDKi6ccYKcBTeilh6SNdNKveDOLk73BkSJjQLJk6qe4Yh+hHw1UPhCDdrg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", + "license": "BSD-3-Clause" + }, + "node_modules/@redis/bloom": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz", + "integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/client": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.6.1.tgz", + "integrity": "sha512-/KCsg3xSlR+nCK8/8ZYSknYxvXHwubJrU82F3Lm1Fp6789VQ0/3RJKfsmRXjqfaTA++23CvC3hqmqe/2GEt6Kw==", + "license": "MIT", + "dependencies": { + "cluster-key-slot": "1.1.2", + "generic-pool": "3.9.0", + "yallist": "4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@redis/graph": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.1.tgz", + "integrity": "sha512-FEMTcTHZozZciLRl6GiiIB4zGm5z5F3F6a6FZCyrfxdKOhFlGkiAqlexWMBzCi4DcRoyiOsuLfW+cjlGWyExOw==", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/json": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.7.tgz", + "integrity": "sha512-6UyXfjVaTBTJtKNG4/9Z8PSpKE6XgSyEb8iwaqDcy+uKrd/DGYHTWkUdnQDyzm727V7p21WUMhsqz5oy65kPcQ==", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/search": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-1.2.0.tgz", + "integrity": "sha512-tYoDBbtqOVigEDMAcTGsRlMycIIjwMCgD8eR2t0NANeQmgK/lvxNAvYyb6bZDD4frHRhIHkJu2TBRvB0ERkOmw==", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/time-series": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.1.0.tgz", + "integrity": "sha512-c1Q99M5ljsIuc4YdaCwfUEXsofakb9c8+Zse2qxTadu8TalLXuAESzLvFAvNVbkmSlvlzIQOLpBCmWI9wTOt+g==", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.3.tgz", + "integrity": "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.3.tgz", + "integrity": "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.3.tgz", + "integrity": "sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.3.tgz", + "integrity": "sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.3.tgz", + "integrity": "sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.3.tgz", + "integrity": "sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.3.tgz", + "integrity": "sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.3.tgz", + "integrity": "sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.3.tgz", + "integrity": "sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.53.3.tgz", + "integrity": "sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.3.tgz", + "integrity": "sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.3.tgz", + "integrity": "sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.3.tgz", + "integrity": "sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.3.tgz", + "integrity": "sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.3.tgz", + "integrity": "sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", + "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", + "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.3.tgz", + "integrity": "sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.3.tgz", + "integrity": "sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.3.tgz", + "integrity": "sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.3.tgz", + "integrity": "sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.3.tgz", + "integrity": "sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", + "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@scarf/scarf": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz", + "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==", + "hasInstallScript": true, + "license": "Apache-2.0" + }, + "node_modules/@sentry/core": { + "version": "10.26.0", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-10.26.0.tgz", + "integrity": "sha512-TjDe5QI37SLuV0q3nMOH8JcPZhv2e85FALaQMIhRILH9Ce6G7xW5GSjmH91NUVq8yc3XtiqYlz/EenEZActc4Q==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry/node": { + "version": "10.26.0", + "resolved": "https://registry.npmjs.org/@sentry/node/-/node-10.26.0.tgz", + "integrity": "sha512-VUwNoKYhRpnHQSj9lty1TgooO+1wcpS1V0K87HU8sZEas5gx3Ujiouk5ocPjlgbKreoYOApgOnEEIq5W/hfQcQ==", + "license": "MIT", + "dependencies": { + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/context-async-hooks": "^2.1.0", + "@opentelemetry/core": "^2.1.0", + "@opentelemetry/instrumentation": "^0.204.0", + "@opentelemetry/instrumentation-amqplib": "0.51.0", + "@opentelemetry/instrumentation-connect": "0.48.0", + "@opentelemetry/instrumentation-dataloader": "0.22.0", + "@opentelemetry/instrumentation-express": "0.53.0", + "@opentelemetry/instrumentation-fs": "0.24.0", + "@opentelemetry/instrumentation-generic-pool": "0.48.0", + "@opentelemetry/instrumentation-graphql": "0.52.0", + "@opentelemetry/instrumentation-hapi": "0.51.0", + "@opentelemetry/instrumentation-http": "0.204.0", + "@opentelemetry/instrumentation-ioredis": "0.52.0", + "@opentelemetry/instrumentation-kafkajs": "0.14.0", + "@opentelemetry/instrumentation-knex": "0.49.0", + "@opentelemetry/instrumentation-koa": "0.52.0", + "@opentelemetry/instrumentation-lru-memoizer": "0.49.0", + "@opentelemetry/instrumentation-mongodb": "0.57.0", + "@opentelemetry/instrumentation-mongoose": "0.51.0", + "@opentelemetry/instrumentation-mysql": "0.50.0", + "@opentelemetry/instrumentation-mysql2": "0.51.0", + "@opentelemetry/instrumentation-pg": "0.57.0", + "@opentelemetry/instrumentation-redis": "0.53.0", + "@opentelemetry/instrumentation-tedious": "0.23.0", + "@opentelemetry/instrumentation-undici": "0.15.0", + "@opentelemetry/resources": "^2.1.0", + "@opentelemetry/sdk-trace-base": "^2.1.0", + "@opentelemetry/semantic-conventions": "^1.37.0", + "@prisma/instrumentation": "6.15.0", + "@sentry/core": "10.26.0", + "@sentry/node-core": "10.26.0", + "@sentry/opentelemetry": "10.26.0", + "import-in-the-middle": "^1.14.2", + "minimatch": "^9.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@sentry/node-core": { + "version": "10.26.0", + "resolved": "https://registry.npmjs.org/@sentry/node-core/-/node-core-10.26.0.tgz", + "integrity": "sha512-7OrHVn8XAsq9mMVMlpL18XTKQEVcLOJSo0n2M7QGKfFk/OfVtSFMcUWGqN1qhYtT9aMTr2bjtR5+BI33djnNTQ==", + "license": "MIT", + "dependencies": { + "@apm-js-collab/tracing-hooks": "^0.3.1", + "@sentry/core": "10.26.0", + "@sentry/opentelemetry": "10.26.0", + "import-in-the-middle": "^1.14.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0", + "@opentelemetry/core": "^1.30.1 || ^2.1.0", + "@opentelemetry/instrumentation": ">=0.57.1 <1", + "@opentelemetry/resources": "^1.30.1 || ^2.1.0", + "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0", + "@opentelemetry/semantic-conventions": "^1.37.0" + } + }, + "node_modules/@sentry/opentelemetry": { + "version": "10.26.0", + "resolved": "https://registry.npmjs.org/@sentry/opentelemetry/-/opentelemetry-10.26.0.tgz", + "integrity": "sha512-ASJdOwn6NwMH2ZeBrnGJI+l/xkJp1AOiQ5FWkvTqLc/vHX+r3PDMO7c+koecY+LiZxSzZF4IV8sALXfOh6UnwA==", + "license": "MIT", + "dependencies": { + "@sentry/core": "10.26.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0", + "@opentelemetry/core": "^1.30.1 || ^2.1.0", + "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0", + "@opentelemetry/semantic-conventions": "^1.37.0" + } + }, + "node_modules/@smithy/abort-controller": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.5.tgz", + "integrity": "sha512-j7HwVkBw68YW8UmFRcjZOmssE77Rvk0GWAIN1oFBhsaovQmZWYCIcGa9/pwRB0ExI8Sk9MWNALTjftjHZea7VA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.4.3.tgz", + "integrity": "sha512-ezHLe1tKLUxDJo2LHtDuEDyWXolw8WGOR92qb4bQdWq/zKenO5BvctZGrVJBK08zjezSk7bmbKFOXIVyChvDLw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.5", + "@smithy/types": "^4.9.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-endpoints": "^3.2.5", + "@smithy/util-middleware": "^4.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.18.5.tgz", + "integrity": "sha512-6gnIz3h+PEPQGDj8MnRSjDvKBah042jEoPgjFGJ4iJLBE78L4lY/n98x14XyPF4u3lN179Ub/ZKFY5za9GeLQw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/middleware-serde": "^4.2.6", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-stream": "^4.5.6", + "@smithy/util-utf8": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.2.5.tgz", + "integrity": "sha512-BZwotjoZWn9+36nimwm/OLIcVe+KYRwzMjfhd4QT7QxPm9WY0HiOV8t/Wlh+HVUif0SBVV7ksq8//hPaBC/okQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.3.6", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.3.6.tgz", + "integrity": "sha512-3+RG3EA6BBJ/ofZUeTFJA7mHfSYrZtQIrDP9dI8Lf7X6Jbos2jptuLrAAteDiFVrmbEmLSuRG/bUKzfAXk7dhg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.5", + "@smithy/querystring-builder": "^4.2.5", + "@smithy/types": "^4.9.0", + "@smithy/util-base64": "^4.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-node": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.2.5.tgz", + "integrity": "sha512-DpYX914YOfA3UDT9CN1BM787PcHfWRBB43fFGCYrZFUH0Jv+5t8yYl+Pd5PW4+QzoGEDvn5d5QIO4j2HyYZQSA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.2.5.tgz", + "integrity": "sha512-2L2erASEro1WC5nV+plwIMxrTXpvpfzl4e+Nre6vBVRR2HKeGGcvpJyyL3/PpiSg+cJG2KpTmZmq934Olb6e5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/md5-js": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.2.5.tgz", + "integrity": "sha512-Bt6jpSTMWfjCtC0s79gZ/WZ1w90grfmopVOWqkI2ovhjpD5Q2XRXuecIPB9689L2+cCySMbaXDhBPU56FKNDNg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.2.5.tgz", + "integrity": "sha512-Y/RabVa5vbl5FuHYV2vUCwvh/dqzrEY/K2yWPSqvhFUwIY0atLqO4TienjBXakoy4zrKAMCZwg+YEqmH7jaN7A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "4.3.12", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.3.12.tgz", + "integrity": "sha512-9pAX/H+VQPzNbouhDhkW723igBMLgrI8OtX+++M7iKJgg/zY/Ig3i1e6seCcx22FWhE6Q/S61BRdi2wXBORT+A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.18.5", + "@smithy/middleware-serde": "^4.2.6", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "@smithy/url-parser": "^4.2.5", + "@smithy/util-middleware": "^4.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "4.4.12", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.4.12.tgz", + "integrity": "sha512-S4kWNKFowYd0lID7/DBqWHOQxmxlsf0jBaos9chQZUWTVOjSW1Ogyh8/ib5tM+agFDJ/TCxuCTvrnlc+9cIBcQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/service-error-classification": "^4.2.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-retry": "^4.2.5", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.2.6.tgz", + "integrity": "sha512-VkLoE/z7e2g8pirwisLz8XJWedUSY8my/qrp81VmAdyrhi94T+riBfwP+AOEEFR9rFTSonC/5D2eWNmFabHyGQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.2.5.tgz", + "integrity": "sha512-bYrutc+neOyWxtZdbB2USbQttZN0mXaOyYLIsaTbJhFsfpXyGWUxJpEuO1rJ8IIJm2qH4+xJT0mxUSsEDTYwdQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.5.tgz", + "integrity": "sha512-UTurh1C4qkVCtqggI36DGbLB2Kv8UlcFdMXDcWMbqVY2uRg0XmT9Pb4Vj6oSQ34eizO1fvR0RnFV4Axw4IrrAg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.5", + "@smithy/shared-ini-file-loader": "^4.4.0", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.4.5.tgz", + "integrity": "sha512-CMnzM9R2WqlqXQGtIlsHMEZfXKJVTIrqCNoSd/QpAyp+Dw0a1Vps13l6ma1fH8g7zSPNsA59B/kWgeylFuA/lw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.2.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/querystring-builder": "^4.2.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.5.tgz", + "integrity": "sha512-8iLN1XSE1rl4MuxvQ+5OSk/Zb5El7NJZ1td6Tn+8dQQHIjp59Lwl6bd0+nzw6SKm2wSSriH2v/I9LPzUic7EOg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "5.3.5", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.5.tgz", + "integrity": "sha512-RlaL+sA0LNMp03bf7XPbFmT5gN+w3besXSWMkA8rcmxLSVfiEXElQi4O2IWwPfxzcHkxqrwBFMbngB8yx/RvaQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.2.5.tgz", + "integrity": "sha512-y98otMI1saoajeik2kLfGyRp11e5U/iJYH/wLCh3aTV/XutbGT9nziKGkgCaMD1ghK7p6htHMm6b6scl9JRUWg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "@smithy/util-uri-escape": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.5.tgz", + "integrity": "sha512-031WCTdPYgiQRYNPXznHXof2YM0GwL6SeaSyTH/P72M1Vz73TvCNH2Nq8Iu2IEPq9QP2yx0/nrw5YmSeAi/AjQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.2.5.tgz", + "integrity": "sha512-8fEvK+WPE3wUAcDvqDQG1Vk3ANLR8Px979te96m84CbKAjBVf25rPYSzb4xU4hlTyho7VhOGnh5i62D/JVF0JQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.4.0.tgz", + "integrity": "sha512-5WmZ5+kJgJDjwXXIzr1vDTG+RhF9wzSODQBfkrQ2VVkYALKGvZX1lgVSxEkgicSAFnFhPj5rudJV0zoinqS0bA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.3.5", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.3.5.tgz", + "integrity": "sha512-xSUfMu1FT7ccfSXkoLl/QRQBi2rOvi3tiBZU2Tdy3I6cgvZ6SEi9QNey+lqps/sJRnogIS+lq+B1gxxbra2a/w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-middleware": "^4.2.5", + "@smithy/util-uri-escape": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "4.9.8", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.9.8.tgz", + "integrity": "sha512-8xgq3LgKDEFoIrLWBho/oYKyWByw9/corz7vuh1upv7ZBm0ZMjGYBhbn6v643WoIqA9UTcx5A5htEp/YatUwMA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.18.5", + "@smithy/middleware-endpoint": "^4.3.12", + "@smithy/middleware-stack": "^4.2.5", + "@smithy/protocol-http": "^5.3.5", + "@smithy/types": "^4.9.0", + "@smithy/util-stream": "^4.5.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.9.0.tgz", + "integrity": "sha512-MvUbdnXDTwykR8cB1WZvNNwqoWVaTRA0RLlLmf/cIFNMM2cKWz01X4Ly6SMC4Kks30r8tT3Cty0jmeWfiuyHTA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.5.tgz", + "integrity": "sha512-VaxMGsilqFnK1CeBX+LXnSuaMx4sTL/6znSZh2829txWieazdVxr54HmiyTsIbpOTLcf5nYpq9lpzmwRdxj6rQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/querystring-parser": "^4.2.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-base64": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz", + "integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.2.0.tgz", + "integrity": "sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.2.1.tgz", + "integrity": "sha512-h53dz/pISVrVrfxV1iqXlx5pRg3V2YWFcSQyPyXZRrZoZj4R4DeWRDo1a7dd3CPTcFi3kE+98tuNyD2axyZReA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.2.0.tgz", + "integrity": "sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "4.3.11", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.3.11.tgz", + "integrity": "sha512-yHv+r6wSQXEXTPVCIQTNmXVWs7ekBTpMVErjqZoWkYN75HIFN5y9+/+sYOejfAuvxWGvgzgxbTHa/oz61YTbKw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "4.2.14", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.2.14.tgz", + "integrity": "sha512-ljZN3iRvaJUgulfvobIuG97q1iUuCMrvXAlkZ4msY+ZuVHQHDIqn7FKZCEj+bx8omz6kF5yQXms/xhzjIO5XiA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/config-resolver": "^4.4.3", + "@smithy/credential-provider-imds": "^4.2.5", + "@smithy/node-config-provider": "^4.3.5", + "@smithy/property-provider": "^4.2.5", + "@smithy/smithy-client": "^4.9.8", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.2.5.tgz", + "integrity": "sha512-3O63AAWu2cSNQZp+ayl9I3NapW1p1rR5mlVHcF6hAB1dPZUQFfRPYtplWX/3xrzWthPGj5FqB12taJJCfH6s8A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz", + "integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.5.tgz", + "integrity": "sha512-6Y3+rvBF7+PZOc40ybeZMcGln6xJGVeY60E7jy9Mv5iKpMJpHgRE6dKy9ScsVxvfAYuEX4Q9a65DQX90KaQ3bA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.2.5.tgz", + "integrity": "sha512-GBj3+EZBbN4NAqJ/7pAhsXdfzdlznOh8PydUijy6FpNIMnHPSMO2/rP4HKu+UFeikJxShERk528oy7GT79YiJg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/service-error-classification": "^4.2.5", + "@smithy/types": "^4.9.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "4.5.6", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.5.6.tgz", + "integrity": "sha512-qWw/UM59TiaFrPevefOZ8CNBKbYEP6wBAIlLqxn3VAIo9rgnTNc4ASbVrqDmhuwI87usnjhdQrxodzAGFFzbRQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/fetch-http-handler": "^5.3.6", + "@smithy/node-http-handler": "^4.4.5", + "@smithy/types": "^4.9.0", + "@smithy/util-base64": "^4.3.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.0.tgz", + "integrity": "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/uuid": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@smithy/uuid/-/uuid-1.1.0.tgz", + "integrity": "sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", + "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==", + "license": "MIT" + }, + "node_modules/@thi.ng/bitstream": { + "version": "2.4.34", + "resolved": "https://registry.npmjs.org/@thi.ng/bitstream/-/bitstream-2.4.34.tgz", + "integrity": "sha512-1bS+601Ar/D2Smpv6xzr4Mk7pJV4CIs4LbLEpi2f09sAHssAByfnOeo2Vfh0MqX9Vt4jaOPXZqEVGcRX5rsgiw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "dependencies": { + "@thi.ng/errors": "^2.5.48" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@thi.ng/errors": { + "version": "2.5.48", + "resolved": "https://registry.npmjs.org/@thi.ng/errors/-/errors-2.5.48.tgz", + "integrity": "sha512-6LXqHT3DWruK3GrH+sIQPXZUQaoRrq0ASc90wd4MSPmGR53b4DuBLL6iE1dJtrQAmGx64LEor8yDIvAL8CZBzQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/postspectacular" + }, + { + "type": "patreon", + "url": "https://patreon.com/thing_umbrella" + }, + { + "type": "liberapay", + "url": "https://liberapay.com/thi.ng" + } + ], + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@tokenizer/inflate": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", + "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "token-types": "^6.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/inflate/node_modules/@borewit/text-codec": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz", + "integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/inflate/node_modules/token-types": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz", + "integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.1.0", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@types/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-kCFuWS0ebDbmxs0AXYn6e2r2nrGAb5KwQhknjSPSPgJcGd8+HVSILlUyFhGqML2gk39HcG7D1ydW9/qpYkN00Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/conventional-commits-parser": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/conventional-commits-parser/-/conventional-commits-parser-5.0.2.tgz", + "integrity": "sha512-BgT2szDXnVypgpNxOK8aL5SGjUdaQbC++WZNjF1Qge3Og2+zhHj+RWhmehLhYyvQwqAmvezruVfOf8+3m74W+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "license": "MIT" + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/long": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", + "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-4.0.0.tgz", + "integrity": "sha512-5eEkJZ/BLvTE3vXGKkWlyTSUVZuzj23Wj8PoyOq2lt5I3CYbiLBOPb3XmCW6QcuOibIUE6emHXHt9E/F/rCa6w==", + "deprecated": "This is a stub types definition. mime provides its own type definitions, so you do not need this installed.", + "dev": true, + "license": "MIT", + "dependencies": { + "mime": "*" + } + }, + "node_modules/@types/mime-types": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-2.1.4.tgz", + "integrity": "sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/mysql": { + "version": "2.15.27", + "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.27.tgz", + "integrity": "sha512-YfWiV16IY0OeBfBCk8+hXKmdTKrKlwKN1MNKAPBu5JYxLwBEZl7QzeEpGnlZb3VMGJrrGmB84gXiH+ofs/TezA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "24.10.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", + "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/node-cron": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz", + "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/pg": { + "version": "8.15.5", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.15.5.tgz", + "integrity": "sha512-LF7lF6zWEKxuT3/OR8wAZGzkg4ENGXFNyiV/JeOt9z5B+0ZVwbql9McqX5c/WStFq1GaGso7H1AzP/qSzmlCKQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, + "node_modules/@types/pg-pool": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/pg-pool/-/pg-pool-2.0.6.tgz", + "integrity": "sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ==", + "license": "MIT", + "dependencies": { + "@types/pg": "*" + } + }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/qrcode-terminal": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@types/qrcode-terminal/-/qrcode-terminal-0.12.2.tgz", + "integrity": "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/shimmer": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", + "integrity": "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg==", + "license": "MIT" + }, + "node_modules/@types/tedious": { + "version": "4.0.14", + "resolved": "https://registry.npmjs.org/@types/tedious/-/tedious-4.0.14.tgz", + "integrity": "sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/validator": { + "version": "13.15.10", + "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz", + "integrity": "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==", + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.47.0.tgz", + "integrity": "sha512-fe0rz9WJQ5t2iaLfdbDc9T80GJy0AeO453q8C3YCilnGozvOyCG5t+EZtg7j7D88+c3FipfP/x+wzGnh1xp8ZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.47.0", + "@typescript-eslint/type-utils": "8.47.0", + "@typescript-eslint/utils": "8.47.0", + "@typescript-eslint/visitor-keys": "8.47.0", + "graphemer": "^1.4.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.47.0", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.47.0.tgz", + "integrity": "sha512-lJi3PfxVmo0AkEY93ecfN+r8SofEqZNGByvHAI3GBLrvt1Cw6H5k1IM02nSzu0RfUafr2EvFSw0wAsZgubNplQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.47.0", + "@typescript-eslint/types": "8.47.0", + "@typescript-eslint/typescript-estree": "8.47.0", + "@typescript-eslint/visitor-keys": "8.47.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.47.0.tgz", + "integrity": "sha512-2X4BX8hUeB5JcA1TQJ7GjcgulXQ+5UkNb0DL8gHsHUHdFoiCTJoYLTpib3LtSDPZsRET5ygN4qqIWrHyYIKERA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.47.0", + "@typescript-eslint/types": "^8.47.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.47.0.tgz", + "integrity": "sha512-a0TTJk4HXMkfpFkL9/WaGTNuv7JWfFTQFJd6zS9dVAjKsojmv9HT55xzbEpnZoY+VUb+YXLMp+ihMLz/UlZfDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.47.0", + "@typescript-eslint/visitor-keys": "8.47.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.47.0.tgz", + "integrity": "sha512-ybUAvjy4ZCL11uryalkKxuT3w3sXJAuWhOoGS3T/Wu+iUu1tGJmk5ytSY8gbdACNARmcYEB0COksD2j6hfGK2g==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.47.0.tgz", + "integrity": "sha512-QC9RiCmZ2HmIdCEvhd1aJELBlD93ErziOXXlHEZyuBo3tBiAZieya0HLIxp+DoDWlsQqDawyKuNEhORyku+P8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.47.0", + "@typescript-eslint/typescript-estree": "8.47.0", + "@typescript-eslint/utils": "8.47.0", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.47.0.tgz", + "integrity": "sha512-nHAE6bMKsizhA2uuYZbEbmp5z2UpffNrPEqiKIeN7VsV6UY/roxanWfoRrf6x/k9+Obf+GQdkm0nPU+vnMXo9A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.47.0.tgz", + "integrity": "sha512-k6ti9UepJf5NpzCjH31hQNLHQWupTRPhZ+KFF8WtTuTpy7uHPfeg2NM7cP27aCGajoEplxJDFVCEm9TGPYyiVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.47.0", + "@typescript-eslint/tsconfig-utils": "8.47.0", + "@typescript-eslint/types": "8.47.0", + "@typescript-eslint/visitor-keys": "8.47.0", + "debug": "^4.3.4", + "fast-glob": "^3.3.2", + "is-glob": "^4.0.3", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.47.0.tgz", + "integrity": "sha512-g7XrNf25iL4TJOiPqatNuaChyqt49a/onq5YsJ9+hXeugK+41LVg7AxikMfM02PC6jbNtZLCJj6AUcQXJS/jGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.47.0", + "@typescript-eslint/types": "8.47.0", + "@typescript-eslint/typescript-estree": "8.47.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.47.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.47.0.tgz", + "integrity": "sha512-SIV3/6eftCy1bNzCQoPmbWsRLujS8t5iDIZ4spZOBHqrM+yfX2ogg8Tt3PDTAVKw3sSCiUgg30uOAvK2r9zGjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.47.0", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", + "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", + "dev": true, + "license": "ISC" + }, + "node_modules/@wasm-audio-decoders/common": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/common/-/common-9.0.7.tgz", + "integrity": "sha512-WRaUuWSKV7pkttBygml/a6dIEpatq2nnZGFIoPTc5yPLkxL6Wk4YaslPM98OPQvWacvNZ+Py9xROGDtrFBDzag==", + "license": "MIT", + "dependencies": { + "@eshaz/web-worker": "1.2.2", + "simple-yenc": "^1.0.4" + } + }, + "node_modules/@wasm-audio-decoders/flac": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/flac/-/flac-0.2.10.tgz", + "integrity": "sha512-YfcyoD2rYRBa6ffawZKNi5qvV5HArJmNmuMVUPoutuZ2hhGi6WNSWIzgvbROGmPbFivLL764Am7xxJENWJDhjw==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7", + "codec-parser": "2.5.0" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/@wasm-audio-decoders/ogg-vorbis": { + "version": "0.1.20", + "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/ogg-vorbis/-/ogg-vorbis-0.1.20.tgz", + "integrity": "sha512-zaQPasU5usRjUDXtXOHYED5tfkR4QMXd+EH3Nrz1+4+M5pCsdD+s9YxJqb0oqnTyRu/KUujOmu5Z/m/NT47vwg==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7", + "codec-parser": "2.5.0" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/@wasm-audio-decoders/opus-ml": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/opus-ml/-/opus-ml-0.0.2.tgz", + "integrity": "sha512-58rWEqDGg+CKCyEeKm2KoxxSwTWtHh/NLTW9ObR4K8CGF6VwuuGudEI1CtniS/oSRmL1nJq/eh8MKARiluw4DQ==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/@zxing/text-encoding": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz", + "integrity": "sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==", + "license": "(Unlicense OR Apache-2.0)", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/agentkeepalive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", + "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", + "license": "MIT", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/amqplib": { + "version": "0.10.9", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.10.9.tgz", + "integrity": "sha512-jwSftI4QjS3mizvnSnOrPGYiUnm1vI2OP1iXeOUz5pb74Ua0nbf6nPyyTzuiCLEE3fMpaJORXh2K/TQ08H5xGA==", + "license": "MIT", + "dependencies": { + "buffer-more-ints": "~1.0.0", + "url-parse": "~1.5.10" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-escapes/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-base": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/any-base/-/any-base-1.1.0.tgz", + "integrity": "sha512-uMgjozySS8adZZYePpaWs8cxB9/kdzmpX6SgJZ+wbz1K5eYk5QMYDVJaZKhxyIHUdnnJkfR7SVgStgH7LkGUyg==", + "license": "MIT" + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "license": "MIT" + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/array-ify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz", + "integrity": "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==", + "dev": true, + "license": "MIT" + }, + "node_modules/array-includes": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", + "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", + "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", + "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/async": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==" + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/async-mutex": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", + "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/audio-buffer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/audio-buffer/-/audio-buffer-5.0.0.tgz", + "integrity": "sha512-gsDyj1wwUp8u7NBB+eW6yhLb9ICf+0eBmDX8NGaAS00w8/fLqFdxUlL5Ge/U8kB64DlQhdonxYC59dXy1J7H/w==", + "license": "MIT" + }, + "node_modules/audio-decode": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/audio-decode/-/audio-decode-2.2.3.tgz", + "integrity": "sha512-Z0lHvMayR/Pad9+O9ddzaBJE0DrhZkQlStrC1RwcAHF3AhQAsdwKHeLGK8fYKyp2DDU6xHxzGb4CLMui12yVrg==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/flac": "^0.2.4", + "@wasm-audio-decoders/ogg-vorbis": "^0.1.15", + "audio-buffer": "^5.0.0", + "audio-type": "^2.2.1", + "mpg123-decoder": "^1.0.0", + "node-wav": "^0.0.2", + "ogg-opus-decoder": "^1.6.12", + "qoa-format": "^1.0.1" + } + }, + "node_modules/audio-type": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/audio-type/-/audio-type-2.2.1.tgz", + "integrity": "sha512-En9AY6EG1qYqEy5L/quryzbA4akBpJrnBZNxeKTqGHC2xT9Qc4aZ8b7CcbOMFTTc/MGdoNyp+SN4zInZNKxMYA==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/await-to-js": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/await-to-js/-/await-to-js-3.0.0.tgz", + "integrity": "sha512-zJAaP9zxTcvTHRlejau3ZOY4V7SRpiByf3/dxx2uyKxxor19tpmpV2QRsTKikckwhaPmr2dVpxxMr7jOCYVp5g==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/axios": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz", + "integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/baileys": { + "version": "7.0.0-rc.9", + "resolved": "https://registry.npmjs.org/baileys/-/baileys-7.0.0-rc.9.tgz", + "integrity": "sha512-Txd2dZ9MHbojvsHckeuCnAKPO/bQjKxua/0tQSJwOKXffK5vpS82k4eA/Nb46K0cK0Bx+fyY0zhnQHYMBriQcw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@cacheable/node-cache": "^1.4.0", + "@hapi/boom": "^9.1.3", + "async-mutex": "^0.5.0", + "libsignal": "git+https://github.com/whiskeysockets/libsignal-node.git", + "lru-cache": "^11.1.0", + "music-metadata": "^11.7.0", + "p-queue": "^9.0.0", + "pino": "^9.6", + "protobufjs": "^7.2.4", + "ws": "^8.13.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "audio-decode": "^2.1.3", + "jimp": "^1.6.0", + "link-preview-js": "^3.0.0", + "sharp": "*" + }, + "peerDependenciesMeta": { + "audio-decode": { + "optional": true + }, + "jimp": { + "optional": true + }, + "link-preview-js": { + "optional": true + } + } + }, + "node_modules/baileys/node_modules/@hapi/boom": { + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/@hapi/boom/-/boom-9.1.4.tgz", + "integrity": "sha512-Ls1oH8jaN1vNsqcaHVYJrKmgMcKsC1wcp8bujvXrHaAqD2iDYq3HoOwsxwo09Cuda5R5nC0o0IxlrlTuvPuzSw==", + "license": "BSD-3-Clause", + "dependencies": { + "@hapi/hoek": "9.x.x" + } + }, + "node_modules/baileys/node_modules/@hapi/hoek": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", + "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==", + "license": "BSD-3-Clause" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "license": "MIT", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/block-stream2": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/block-stream2/-/block-stream2-2.1.0.tgz", + "integrity": "sha512-suhjmLI57Ewpmq00qaygS8UgEq2ly2PCItenIyhMqVjo4t4pGzqMvfgJuX8iWTeSDdfSSqS6j38fL4ToNL7Pfg==", + "license": "MIT", + "dependencies": { + "readable-stream": "^3.4.0" + } + }, + "node_modules/bmp-ts": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/bmp-ts/-/bmp-ts-1.0.9.tgz", + "integrity": "sha512-cTEHk2jLrPyi+12M3dhpEbnnPOsaZuq7C45ylbbQIiWgDFZq4UVYPEY5mlqjvsj/6gJv9qX5sa+ebDzLXT28Vw==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "license": "ISC" + }, + "node_modules/bowser": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.13.0.tgz", + "integrity": "sha512-yHAbSRuT6LTeKi6k2aS40csueHqgAsFEgmrOsfRyFpJnFv5O2hl9FYmWEUZ97gZ/dG17U4IQQcTx4YAFYPuWRQ==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-or-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/browser-or-node/-/browser-or-node-2.1.1.tgz", + "integrity": "sha512-8CVjaLJGuSKMVTxJ2DpBl5XnlNDiT4cQFeuCJJrvJmts9YrTZDizTX7PjC2s6W4x+MBGZeEY6dGMrF04/6Hgqg==", + "license": "MIT" + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-crc32": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-1.0.0.tgz", + "integrity": "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==", + "license": "MIT" + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/c12": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz", + "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==", + "license": "MIT", + "dependencies": { + "chokidar": "^4.0.3", + "confbox": "^0.2.2", + "defu": "^6.1.4", + "dotenv": "^16.6.1", + "exsolve": "^1.0.7", + "giget": "^2.0.0", + "jiti": "^2.4.2", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^1.0.0", + "pkg-types": "^2.2.0", + "rc9": "^2.1.2" + }, + "peerDependencies": { + "magicast": "^0.3.5" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.2.0.tgz", + "integrity": "sha512-LEJxRqfeomiiRd2t0uON6hxAtgOoWDfY3fugebbz+J3vDLO+SkdfFChQcOHTZhj9SYa9iwE9MGYNX72dKiOE4w==", + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.0.5", + "@cacheable/utils": "^2.3.0", + "hookified": "^1.13.0", + "keyv": "^5.5.4", + "qified": "^0.5.2" + } + }, + "node_modules/cachedir": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cachedir/-/cachedir-2.3.0.tgz", + "integrity": "sha512-A+Fezp4zxnit6FanDmv9EqXNAi3vt9DWp51/71UEhXukb7QUuvtv9344h91dyAxuTLoSYJFU299qzR3tzwPAhw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/call-bind": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", + "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cheerio": { + "version": "1.0.0-rc.11", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.11.tgz", + "integrity": "sha512-bQwNaDIBKID5ts/DsdhxrjqFXYfLw4ste+wMKqWA8DyKcS4qwsPP4Bk8ZNaTJjvpiX/qW3BT4sU7d6Bh5i+dag==", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "htmlparser2": "^8.0.1", + "parse5": "^7.0.0", + "parse5-htmlparser2-tree-adapter": "^7.0.0", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", + "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/citty": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", + "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "license": "MIT" + }, + "node_modules/class-validator": { + "version": "0.14.3", + "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.3.tgz", + "integrity": "sha512-rXXekcjofVN1LTOSw+u4u9WXVEUvNBVjORW154q/IdmYWy1nMbOU9aNtZB0t8m+FJQ9q91jlr2f9CwwUFdFMRA==", + "license": "MIT", + "dependencies": { + "@types/validator": "^13.15.3", + "libphonenumber-js": "^1.11.1", + "validator": "^13.15.20" + } + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.1.1.tgz", + "integrity": "sha512-SroPvNHxUnk+vIW/dOSfNqdy1sPEFkrTk6TUtqLCnBlo3N7TNYYkzzN7uSD6+jVjrdO4+p8nH7JzH6cIvUem6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^7.1.0", + "string-width": "^8.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.1.0.tgz", + "integrity": "sha512-Kxl3KJGb/gxkaUMOjRsQ8IrXiGW75O4E3RPjFIINOVH8AMl2SQ/yWdTzWwF3FevIX9LcMAjJW+GRwAlAbTSXdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/codec-parser": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/codec-parser/-/codec-parser-2.5.0.tgz", + "integrity": "sha512-Ru9t80fV8B0ZiixQl8xhMTLru+dzuis/KQld32/x5T/+3LwZb0/YvQdSKytX9JqCnRdiupvAvyYJINKrXieziQ==", + "license": "LGPL-3.0-or-later" + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", + "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/commitizen": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/commitizen/-/commitizen-4.3.1.tgz", + "integrity": "sha512-gwAPAVTy/j5YcOOebcCRIijn+mSjWJC+IYKivTu6aG8Ei/scoXgfsMRnuAk6b0GRste2J4NGxVdMN3ZpfNaVaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cachedir": "2.3.0", + "cz-conventional-changelog": "3.3.0", + "dedent": "0.7.0", + "detect-indent": "6.1.0", + "find-node-modules": "^2.1.2", + "find-root": "1.1.0", + "fs-extra": "9.1.0", + "glob": "7.2.3", + "inquirer": "8.2.5", + "is-utf8": "^0.2.1", + "lodash": "4.17.21", + "minimist": "1.2.7", + "strip-bom": "4.0.0", + "strip-json-comments": "3.1.1" + }, + "bin": { + "commitizen": "bin/commitizen", + "cz": "bin/git-cz", + "git-cz": "bin/git-cz" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/commitizen/node_modules/minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/compare-func": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz", + "integrity": "sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-ify": "^1.0.0", + "dot-prop": "^5.1.0" + } + }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "license": "MIT", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "compressible": "~2.0.18", + "debug": "2.6.9", + "negotiator": "~0.6.4", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/confbox": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz", + "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==", + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/conventional-changelog-angular": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-7.0.0.tgz", + "integrity": "sha512-ROjNchA9LgfNMTTFSIWPzebCwOGFdgkEq45EnvvrmSLvCtAw0HSmrCs7/ty+wAeYUZyNay0YMUNYFTRL72PkBQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "compare-func": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/conventional-changelog-conventionalcommits": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-7.0.2.tgz", + "integrity": "sha512-NKXYmMR/Hr1DevQegFB4MwfM5Vv0m4UIxKZTTYuD98lpTknaZlSRrDOG4X7wIXpGkfsYxZTghUN+Qq+T0YQI7w==", + "dev": true, + "license": "ISC", + "dependencies": { + "compare-func": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/conventional-commit-types": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/conventional-commit-types/-/conventional-commit-types-3.0.0.tgz", + "integrity": "sha512-SmmCYnOniSsAa9GqWOeLqc179lfr5TRu5b4QFDkbsrJ5TZjPJx85wtOr3zn+1dbeNiXDKGPbZ72IKbPhLXh/Lg==", + "dev": true, + "license": "ISC" + }, + "node_modules/conventional-commits-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", + "integrity": "sha512-ZPMl0ZJbw74iS9LuX9YIAiW8pfM5p3yh2o/NbXHbkFuZzY5jvdi5jFycEOkmBW5H5I7nA+D6f3UcsCLP2vvSEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-text-path": "^2.0.0", + "JSONStream": "^1.3.5", + "meow": "^12.0.1", + "split2": "^4.0.0" + }, + "bin": { + "conventional-commits-parser": "cli.mjs" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cosmiconfig": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", + "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/cosmiconfig-typescript-loader": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-6.2.0.tgz", + "integrity": "sha512-GEN39v7TgdxgIoNcdkRE3uiAzQt3UXLyHbRHD6YoL048XAeOomyxaP+Hh/+2C6C2wYjxJ2onhJcsQp+L4YEkVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "jiti": "^2.6.1" + }, + "engines": { + "node": ">=v18" + }, + "peerDependencies": { + "@types/node": "*", + "cosmiconfig": ">=9", + "typescript": ">=5" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/curve25519-js": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/curve25519-js/-/curve25519-js-0.0.4.tgz", + "integrity": "sha512-axn2UMEnkhyDUPWOwVKBMVIzSQy2ejH2xRGy1wq81dqRwApXfIzfbE3hIX0ZRFBIihf/KDqK158DLwESu4AK1w==", + "license": "MIT" + }, + "node_modules/cz-conventional-changelog": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/cz-conventional-changelog/-/cz-conventional-changelog-3.3.0.tgz", + "integrity": "sha512-U466fIzU5U22eES5lTNiNbZ+d8dfcHcssH4o7QsdWaCcRs/feIPCxKYSWkYBNs5mny7MvEfwpTLWjvbm94hecw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^2.4.1", + "commitizen": "^4.0.3", + "conventional-commit-types": "^3.0.0", + "lodash.map": "^4.5.1", + "longest": "^2.0.1", + "word-wrap": "^1.0.3" + }, + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@commitlint/load": ">6.1.1" + } + }, + "node_modules/cz-conventional-changelog/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cz-conventional-changelog/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cz-conventional-changelog/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/dargs": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/dargs/-/dargs-8.1.0.tgz", + "integrity": "sha512-wAV9QHOsNbwnWdNW2FYvE1P56wtgSbM+3SZcdGiWQILwVjACCXDCI3Ai8QlCjMDB8YK5zySiXZYBiwGmNY3lnw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/dayjs": { + "version": "1.11.19", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz", + "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decode-uri-component": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.2.tgz", + "integrity": "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge-ts": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", + "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/defaults": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", + "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "clone": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/defaults/node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/defu": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz", + "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==", + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-indent": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", + "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dot-prop": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", + "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/effect": { + "version": "3.18.4", + "resolved": "https://registry.npmjs.org/effect/-/effect-3.18.4.tgz", + "integrity": "sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "fast-check": "^3.23.1" + } + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/empathic": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", + "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/engine.io": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz", + "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==", + "license": "MIT", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-client": { + "version": "6.6.3", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.3.tgz", + "integrity": "sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1", + "xmlhttprequest-ssl": "~2.1.1" + } + }, + "node_modules/engine.io-client/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/engine.io-client/node_modules/ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/engine.io/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/engine.io/node_modules/ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.24.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.0.tgz", + "integrity": "sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz", + "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/esbuild": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz", + "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.0", + "@esbuild/android-arm": "0.27.0", + "@esbuild/android-arm64": "0.27.0", + "@esbuild/android-x64": "0.27.0", + "@esbuild/darwin-arm64": "0.27.0", + "@esbuild/darwin-x64": "0.27.0", + "@esbuild/freebsd-arm64": "0.27.0", + "@esbuild/freebsd-x64": "0.27.0", + "@esbuild/linux-arm": "0.27.0", + "@esbuild/linux-arm64": "0.27.0", + "@esbuild/linux-ia32": "0.27.0", + "@esbuild/linux-loong64": "0.27.0", + "@esbuild/linux-mips64el": "0.27.0", + "@esbuild/linux-ppc64": "0.27.0", + "@esbuild/linux-riscv64": "0.27.0", + "@esbuild/linux-s390x": "0.27.0", + "@esbuild/linux-x64": "0.27.0", + "@esbuild/netbsd-arm64": "0.27.0", + "@esbuild/netbsd-x64": "0.27.0", + "@esbuild/openbsd-arm64": "0.27.0", + "@esbuild/openbsd-x64": "0.27.0", + "@esbuild/openharmony-arm64": "0.27.0", + "@esbuild/sunos-x64": "0.27.0", + "@esbuild/win32-arm64": "0.27.0", + "@esbuild/win32-ia32": "0.27.0", + "@esbuild/win32-x64": "0.27.0" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", + "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-config-prettier": { + "version": "10.1.8", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz", + "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", + "dev": true, + "license": "MIT", + "bin": { + "eslint-config-prettier": "bin/cli.js" + }, + "funding": { + "url": "https://opencollective.com/eslint-config-prettier" + }, + "peerDependencies": { + "eslint": ">=7.0.0" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-module-utils": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz", + "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz", + "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.9", + "array.prototype.findlastindex": "^1.2.6", + "array.prototype.flat": "^1.3.3", + "array.prototype.flatmap": "^1.3.3", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.9", + "eslint-module-utils": "^2.12.1", + "hasown": "^2.0.2", + "is-core-module": "^2.16.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.1", + "semver": "^6.3.1", + "string.prototype.trimend": "^1.0.9", + "tsconfig-paths": "^3.15.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-import/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import/node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eslint-plugin-import/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/eslint-plugin-import/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/eslint-plugin-import/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-import/node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/eslint-plugin-import/node_modules/tsconfig-paths": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", + "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/eslint-plugin-prettier": { + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.4.tgz", + "integrity": "sha512-swNtI95SToIz05YINMA6Ox5R057IMAmWZ26GqPxusAp1TZzj+IdY9tXNWWD3vkF/wEqydCONcwjTFpxybBqZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "prettier-linter-helpers": "^1.0.0", + "synckit": "^0.11.7" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-prettier" + }, + "peerDependencies": { + "@types/eslint": ">=8.0.0", + "eslint": ">=8.0.0", + "eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0", + "prettier": ">=3.0.0" + }, + "peerDependenciesMeta": { + "@types/eslint": { + "optional": true + }, + "eslint-config-prettier": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-simple-import-sort": { + "version": "12.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-simple-import-sort/-/eslint-plugin-simple-import-sort-12.1.1.tgz", + "integrity": "sha512-6nuzu4xwQtE3332Uz0to+TxDQYRLTKRESSc2hefVT48Zc8JthmN23Gx9lnYhu0FtkRSL1oxny3kJ2aveVhmOVA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": ">=5.0.0" + } + }, + "node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/eslint/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/eslint/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/eslint/node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint/node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/eslint/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/eslint/node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter2": { + "version": "6.4.9", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz", + "integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==", + "license": "MIT" + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/exif-parser": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/exif-parser/-/exif-parser-0.1.12.tgz", + "integrity": "sha512-c2bQfLNbMzLPmzQuOr8fy0csy84WmwnER81W88DzTp9CYNPJ6yzOj2EZAh9pywYpqHnshVLHQJ8WzldAyfY+Iw==" + }, + "node_modules/expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "homedir-polyfill": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-async-errors": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/express-async-errors/-/express-async-errors-3.1.1.tgz", + "integrity": "sha512-h6aK1da4tpqWSbyCa3FxB/V6Ehd4EEB15zyQq9qe75OZBp0krinNKuH4rAY+S/U/2I36vdLAUFSjQJ+TFmODng==", + "license": "ISC", + "peerDependencies": { + "express": "^4.16.2" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/exsolve": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", + "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "license": "MIT" + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-check": { + "version": "3.23.2", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", + "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "dependencies": { + "pure-rand": "^6.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-diff": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-xml-parser": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", + "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^2.1.0" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fetch-socks": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fetch-socks/-/fetch-socks-1.3.2.tgz", + "integrity": "sha512-vkH5+Zgj2yEbU57Cei0iyLgTZ4OkEKJj56Xu3ViB5dpsl599JgEooQ3x6NVagIFRHWnWJ+7K0MO0aIV1TMgvnw==", + "license": "MIT", + "dependencies": { + "socks": "^2.8.2", + "undici": ">=6" + } + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/figures/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/file-type": { + "version": "16.5.4", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-16.5.4.tgz", + "integrity": "sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw==", + "license": "MIT", + "dependencies": { + "readable-web-to-node-stream": "^3.0.0", + "strtok3": "^6.2.4", + "token-types": "^4.1.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/filter-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/filter-obj/-/filter-obj-1.1.0.tgz", + "integrity": "sha512-8rXg1ZnX7xzy2NGDVkBVaAy+lSlPNwad13BtgSlLuxfIslyt5Vg64U7tFcCt4WS1R0hvtnQybT/IyCkGZ3DpXQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/find-node-modules": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/find-node-modules/-/find-node-modules-2.1.3.tgz", + "integrity": "sha512-UC2I2+nx1ZuOBclWVNdcnbDR5dlrOdVb7xNjmT/lHE+LsgztWks3dG7boJ37yTS/venXw84B/mAW9uHVoC5QRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "findup-sync": "^4.0.0", + "merge": "^2.1.1" + } + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", + "dev": true, + "license": "MIT" + }, + "node_modules/find-up": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-7.0.0.tgz", + "integrity": "sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^7.2.0", + "path-exists": "^5.0.0", + "unicorn-magic": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/findup-sync": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-4.0.0.tgz", + "integrity": "sha512-6jvvn/12IC4quLBL1KNokxC7wWTvYncaVUYSoxWw7YykPLuRrnv4qdHcSOywOI5RpkOVGeQRtWM8/q+G6W6qfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.0", + "micromatch": "^4.0.2", + "resolve-dir": "^1.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/flat-cache": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.3", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flat-cache/node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/fluent-ffmpeg": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/fluent-ffmpeg/-/fluent-ffmpeg-2.1.3.tgz", + "integrity": "sha512-Be3narBNt2s6bsaqP6Jzq91heDgOEaDCJAXcE3qcma/EJBSy5FB4cvO31XBInuAuKBx8Kptf8dkhjK0IOru39Q==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "async": "^0.2.9", + "which": "^1.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/fluent-ffmpeg/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/form-data": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", + "license": "MIT" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "license": "MIT", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/forwarded-parse": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/forwarded-parse/-/forwarded-parse-2.1.2.tgz", + "integrity": "sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==", + "license": "MIT" + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz", + "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/generic-pool": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz", + "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", + "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", + "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/gifwrap": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/gifwrap/-/gifwrap-0.10.1.tgz", + "integrity": "sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw==", + "license": "MIT", + "dependencies": { + "image-q": "^4.0.0", + "omggif": "^1.0.10" + } + }, + "node_modules/giget": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", + "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.0", + "defu": "^6.1.4", + "node-fetch-native": "^1.6.6", + "nypm": "^0.6.0", + "pathe": "^2.0.3" + }, + "bin": { + "giget": "dist/cli.mjs" + } + }, + "node_modules/git-raw-commits": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-4.0.0.tgz", + "integrity": "sha512-ICsMM1Wk8xSGMowkOmPrzo2Fgmfo4bMHLNX6ytHjajRJUqvHOw/TFapQ+QG75c3X/tTDDhOSRPGC52dDbNM8FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dargs": "^8.0.0", + "meow": "^12.0.1", + "split2": "^4.0.0" + }, + "bin": { + "git-raw-commits": "cli.mjs" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/global-directory": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", + "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "4.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix/node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/global-prefix/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hashery": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.2.0.tgz", + "integrity": "sha512-43XJKpwle72Ik5Zpam7MuzRWyNdwwdf6XHlh8wCj2PggvWf+v/Dm5B0dxGZOmddidgeO6Ofu9As/o231Ti/9PA==", + "license": "MIT", + "dependencies": { + "hookified": "^1.13.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse-passwd": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/hookified": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.13.0.tgz", + "integrity": "sha512-6sPYUY8olshgM/1LDNW4QZQN0IqgKhtl/1C8koNZBJrKLBk3AZl6chQtNwpNztvfiApHMEwMHek5rv993PRbWw==", + "license": "MIT" + }, + "node_modules/htmlparser2": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", + "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "license": "MIT", + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "node_modules/i18next": { + "version": "23.16.8", + "resolved": "https://registry.npmjs.org/i18next/-/i18next-23.16.8.tgz", + "integrity": "sha512-06r/TitrM88Mg5FdUXAKL96dJMzgqLE5dv3ryBAra4KCwD9mJ4ndOTS95ZuymIGoE+2hzfdaMak2X11/es7ZWg==", + "funding": [ + { + "type": "individual", + "url": "https://locize.com" + }, + { + "type": "individual", + "url": "https://locize.com/i18next.html" + }, + { + "type": "individual", + "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project" + } + ], + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.23.2" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/image-q": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/image-q/-/image-q-4.0.0.tgz", + "integrity": "sha512-PfJGVgIfKQJuq3s0tTDOKtztksibuUEbJQIYT3by6wctQo+Rdlh7ef4evJ5NCdxY4CfMbvFkocEwbl4BF8RlJw==", + "license": "MIT", + "dependencies": { + "@types/node": "16.9.1" + } + }, + "node_modules/image-q/node_modules/@types/node": { + "version": "16.9.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.9.1.tgz", + "integrity": "sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g==", + "license": "MIT" + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/import-in-the-middle": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz", + "integrity": "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", + "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/inquirer": { + "version": "8.2.5", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.5.tgz", + "integrity": "sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.5.5", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/inquirer/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/inquirer/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ip-address": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz", + "integrity": "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-arguments": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz", + "integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-base64": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-base64/-/is-base64-1.1.0.tgz", + "integrity": "sha512-Nlhg7Z2dVC4/PTvIFkgVVNvPHSO2eR/Yd0XzhGiXCXEvWnptXlXa/clQ8aePPiMuxEGcWfzWbGw2Fe3d+Y3v1g==", + "license": "MIT", + "bin": { + "is_base64": "bin/is-base64", + "is-base64": "bin/is-base64" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-text-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-text-path/-/is-text-path-2.0.0.tgz", + "integrity": "sha512-+oDTluR6WEjdXEJMnC2z6A4FRwFoYuvShVVEGsS7ewc0UTi2QtAKMDJuL4BDEVt+5T7MjFo12RP8ghOM75oKJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "text-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha512-rMYPYvCzsXywIsldgLaSoPlw5PfoB/ssr7hY4pLfcodrA5M/eArza1a9VmTiNIBNMjOGr1Ow9mTyU2o69U6U9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jimp": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/jimp/-/jimp-1.6.0.tgz", + "integrity": "sha512-YcwCHw1kiqEeI5xRpDlPPBGL2EOpBKLwO4yIBJcXWHPj5PnA5urGq0jbyhM5KoNpypQ6VboSoxc9D8HyfvngSg==", + "license": "MIT", + "dependencies": { + "@jimp/core": "1.6.0", + "@jimp/diff": "1.6.0", + "@jimp/js-bmp": "1.6.0", + "@jimp/js-gif": "1.6.0", + "@jimp/js-jpeg": "1.6.0", + "@jimp/js-png": "1.6.0", + "@jimp/js-tiff": "1.6.0", + "@jimp/plugin-blit": "1.6.0", + "@jimp/plugin-blur": "1.6.0", + "@jimp/plugin-circle": "1.6.0", + "@jimp/plugin-color": "1.6.0", + "@jimp/plugin-contain": "1.6.0", + "@jimp/plugin-cover": "1.6.0", + "@jimp/plugin-crop": "1.6.0", + "@jimp/plugin-displace": "1.6.0", + "@jimp/plugin-dither": "1.6.0", + "@jimp/plugin-fisheye": "1.6.0", + "@jimp/plugin-flip": "1.6.0", + "@jimp/plugin-hash": "1.6.0", + "@jimp/plugin-mask": "1.6.0", + "@jimp/plugin-print": "1.6.0", + "@jimp/plugin-quantize": "1.6.0", + "@jimp/plugin-resize": "1.6.0", + "@jimp/plugin-rotate": "1.6.0", + "@jimp/plugin-threshold": "1.6.0", + "@jimp/types": "1.6.0", + "@jimp/utils": "1.6.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/jpeg-js": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/jpeg-js/-/jpeg-js-0.4.4.tgz", + "integrity": "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==", + "license": "BSD-3-Clause" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonfile": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", + "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "dev": true, + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/jsonschema": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/jsonschema/-/jsonschema-1.5.0.tgz", + "integrity": "sha512-K+A9hhqbn0f3pJX17Q/7H6yQfD/5OXgdrR5UE12gMXCiN9D5Xq2o5mddV2QEcX/bjla99ASsAAQUyMCCRWAEhw==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/JSONStream": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", + "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", + "dev": true, + "license": "(MIT OR Apache-2.0)", + "dependencies": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + }, + "bin": { + "JSONStream": "bin.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", + "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/kafkajs": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/kafkajs/-/kafkajs-2.2.4.tgz", + "integrity": "sha512-j/YeapB1vfPT2iOIUn/vxdyKEuhuY2PxMBvf5JWux6iSaukAccrMtXEY/Lb7OvavDhOWME589bpLrEdnVHjfjA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/keyv": { + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.5.4.tgz", + "integrity": "sha512-eohl3hKTiVyD1ilYdw9T0OiB4hnjef89e3dMYKz+mVKDzj+5IteTseASUsOB+EU9Tf6VNTCjDePcP6wkDGmLKQ==", + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/libphonenumber-js": { + "version": "1.12.29", + "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.12.29.tgz", + "integrity": "sha512-P2aLrbeqHbmh8+9P35LXQfXOKc7XJ0ymUKl7tyeyQjdRNfzunXWxQXGc4yl3fUf28fqLRfPY+vIVvFXK7KEBTw==", + "license": "MIT" + }, + "node_modules/libsignal": { + "name": "@whiskeysockets/libsignal-node", + "version": "2.0.1", + "resolved": "git+ssh://git@github.com/whiskeysockets/libsignal-node.git#1c30d7d7e76a3b0aa120b04dc6a26f5a12dccf67", + "license": "GPL-3.0", + "dependencies": { + "curve25519-js": "^0.0.4", + "protobufjs": "6.8.8" + } + }, + "node_modules/libsignal/node_modules/@types/node": { + "version": "10.17.60", + "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz", + "integrity": "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==", + "license": "MIT" + }, + "node_modules/libsignal/node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", + "license": "Apache-2.0" + }, + "node_modules/libsignal/node_modules/protobufjs": { + "version": "6.8.8", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.8.8.tgz", + "integrity": "sha512-AAmHtD5pXgZfi7GMpllpO3q1Xw1OYldr+dMUlAnffGTAhqkg72WdmSY71uKBF/JuyiKs8psYbtKrhi0ASCD8qw==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/long": "^4.0.0", + "@types/node": "^10.1.0", + "long": "^4.0.0" + }, + "bin": { + "pbjs": "bin/pbjs", + "pbts": "bin/pbts" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT" + }, + "node_modules/link-preview-js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/link-preview-js/-/link-preview-js-3.2.0.tgz", + "integrity": "sha512-FvrLltjOPGbTzt+RugbzM7g8XuUNLPO2U/INSLczrYdAA32E7nZVUrVL1gr61DGOArGJA2QkPGMEvNMLLsXREA==", + "license": "MIT", + "dependencies": { + "cheerio": "1.0.0-rc.11", + "url": "0.11.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/lint-staged": { + "version": "16.2.7", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.2.7.tgz", + "integrity": "sha512-lDIj4RnYmK7/kXMya+qJsmkRFkGolciXjrsZ6PC25GdTfWOAWetR0ZbsNXRAj1EHHImRSalc+whZFg56F5DVow==", + "dev": true, + "license": "MIT", + "dependencies": { + "commander": "^14.0.2", + "listr2": "^9.0.5", + "micromatch": "^4.0.8", + "nano-spawn": "^2.0.0", + "pidtree": "^0.6.0", + "string-argv": "^0.3.2", + "yaml": "^2.8.1" + }, + "bin": { + "lint-staged": "bin/lint-staged.js" + }, + "engines": { + "node": ">=20.17" + }, + "funding": { + "url": "https://opencollective.com/lint-staged" + } + }, + "node_modules/listr2": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-9.0.5.tgz", + "integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "cli-truncate": "^5.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.1.0", + "rfdc": "^1.4.1", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/listr2/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/locate-path": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", + "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.kebabcase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", + "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.map": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.map/-/lodash.map-4.6.0.tgz", + "integrity": "sha512-worNHGKLDetmcEYDvh2stPCrrQRkP20E4l0iIS7F8EvzMqBBi7ltvFN5m1HvTf1P7Jk1txKhvFcmYsCr8O2F1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.mergewith": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz", + "integrity": "sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.startcase": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.startcase/-/lodash.startcase-4.4.0.tgz", + "integrity": "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.upperfirst": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz", + "integrity": "sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/log-symbols/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/log-symbols/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-escapes": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.2.0.tgz", + "integrity": "sha512-g6LhBsl+GBPRWGWsBtutpzBYuIIdBkLEvad5C/va/74Db018+5TZiyA26cZJAr3Rft5lprVqOIPxf5Vid6tqAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/log-update/node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/longest": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-2.0.1.tgz", + "integrity": "sha512-Ajzxb8CM6WAnFjgiloPsI3bF+WCxcvhdIG3KNA2KN962+tdBsHcuQ4k4qX/EcS/2CRkcc0iAkR956Nib6aXU/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lru-cache": { + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", + "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", + "license": "ISC", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/mediainfo.js": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/mediainfo.js/-/mediainfo.js-0.3.6.tgz", + "integrity": "sha512-3xVRlxwlVWIZV3z1q7pb8LzFOO7iKi/DXoRiFRZdOlrUEhPyJDaaRt0uK32yQJabArQicRBeq7cRxmdZlIBTyA==", + "license": "BSD-2-Clause", + "dependencies": { + "yargs": "^18.0.0" + }, + "bin": { + "mediainfo.js": "dist/esm/cli.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/mediainfo.js/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/mediainfo.js/node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/mediainfo.js/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mediainfo.js/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/mediainfo.js/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/mediainfo.js/node_modules/yargs": { + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz", + "integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==", + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^7.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/mediainfo.js/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/meow": { + "version": "12.1.1", + "resolved": "https://registry.npmjs.org/meow/-/meow-12.1.1.tgz", + "integrity": "sha512-BhXM0Au22RwUneMPwSCnyhTOizdWoIEPU9sp0Aqa1PnDMR5Wv2FGXYDjuzJEIX+Eo2Rb8xuYe5jrnm5QowQFkw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/merge/-/merge-2.1.1.tgz", + "integrity": "sha512-jz+Cfrg9GWOZbQAnDQ4hlVnQky+341Yk5ru8bZSe6sIDTCIg8n9i/u7hSQGSVOF3C7lH6mGtqjkiT9G4wFLL0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-4.1.0.tgz", + "integrity": "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw==", + "funding": [ + "https://github.com/sponsors/broofa" + ], + "license": "MIT", + "bin": { + "mime": "bin/cli.js" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minio": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/minio/-/minio-8.0.6.tgz", + "integrity": "sha512-sOeh2/b/XprRmEtYsnNRFtOqNRTPDvYtMWh+spWlfsuCV/+IdxNeKVUMKLqI7b5Dr07ZqCPuaRGU/rB9pZYVdQ==", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.4", + "block-stream2": "^2.1.0", + "browser-or-node": "^2.1.1", + "buffer-crc32": "^1.0.0", + "eventemitter3": "^5.0.1", + "fast-xml-parser": "^4.4.1", + "ipaddr.js": "^2.0.1", + "lodash": "^4.17.21", + "mime-types": "^2.1.35", + "query-string": "^7.1.3", + "stream-json": "^1.8.0", + "through2": "^4.0.2", + "web-encoding": "^1.1.5", + "xml2js": "^0.5.0 || ^0.6.2" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, + "node_modules/minio/node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/minio/node_modules/fast-xml-parser": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz", + "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/minio/node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mlly": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz", + "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==", + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.1" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, + "node_modules/mpg123-decoder": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/mpg123-decoder/-/mpg123-decoder-1.0.3.tgz", + "integrity": "sha512-+fjxnWigodWJm3+4pndi+KUg9TBojgn31DPk85zEsim7C6s0X5Ztc/hQYdytXkwuGXH+aB0/aEkG40Emukv6oQ==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz", + "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "mkdirp": "^0.5.6", + "object-assign": "^4.1.1", + "type-is": "^1.6.18", + "xtend": "^4.0.2" + }, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/music-metadata": { + "version": "11.10.3", + "resolved": "https://registry.npmjs.org/music-metadata/-/music-metadata-11.10.3.tgz", + "integrity": "sha512-j0g/x4cNNZW6I5gdcPAY+GFkJY9WHTpkFDMBJKQLxJQyvSfQbXm57fTE3haGFFuOzCgtsTd4Plwc49Sn9RacDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.0", + "@tokenizer/token": "^0.3.0", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "file-type": "^21.1.1", + "media-typer": "^1.1.0", + "strtok3": "^10.3.4", + "token-types": "^6.1.1", + "uint8array-extras": "^1.5.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/music-metadata/node_modules/file-type": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.1.1.tgz", + "integrity": "sha512-ifJXo8zUqbQ/bLbl9sFoqHNTNWbnPY1COImFfM6CCy7z+E+jC1eY9YfOKkx0fckIg+VljAy2/87T61fp0+eEkg==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.4", + "token-types": "^6.1.1", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/music-metadata/node_modules/strtok3": { + "version": "10.3.4", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz", + "integrity": "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/music-metadata/node_modules/token-types": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz", + "integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.1.0", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/music-metadata/node_modules/token-types/node_modules/@borewit/text-codec": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz", + "integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true, + "license": "ISC" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nano-spawn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/nano-spawn/-/nano-spawn-2.0.0.tgz", + "integrity": "sha512-tacvGzUY5o2D8CBh2rrwxyNojUsZNU2zjNTzKQrkgGJQTbGAfArVWXSKMBokBeeg6C7OLRGUEyoFlYbfeWQIqw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/nano-spawn?sponsor=1" + } + }, + "node_modules/nats": { + "version": "2.29.3", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.29.3.tgz", + "integrity": "sha512-tOQCRCwC74DgBTk4pWZ9V45sk4d7peoE2njVprMRCBXrhJ5q5cYM7i6W+Uvw2qUrcfOSnuisrX7bEx3b3Wx4QA==", + "license": "Apache-2.0", + "dependencies": { + "nkeys.js": "1.1.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz", + "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/nkeys.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", + "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "license": "Apache-2.0", + "dependencies": { + "tweetnacl": "1.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/node-cache": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz", + "integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==", + "license": "MIT", + "dependencies": { + "clone": "2.x" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/node-cron": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz", + "integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==", + "license": "ISC", + "dependencies": { + "uuid": "8.3.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/node-cron/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "license": "MIT" + }, + "node_modules/node-wav": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/node-wav/-/node-wav-0.0.2.tgz", + "integrity": "sha512-M6Rm/bbG6De/gKGxOpeOobx/dnGuP0dz40adqx38boqHhlWssBJZgLCPBNtb9NkrmnKYiV04xELq+R6PFOnoLA==", + "license": "MIT", + "engines": { + "node": ">=4.4.0" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/nypm": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.2.tgz", + "integrity": "sha512-7eM+hpOtrKrBDCh7Ypu2lJ9Z7PNZBdi/8AT3AX8xoCj43BBVHD0hPSTEvMtkMpfs8FCqBGhxB+uToIQimA111g==", + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.2", + "pathe": "^2.0.3", + "pkg-types": "^2.3.0", + "tinyexec": "^1.0.1" + }, + "bin": { + "nypm": "dist/cli.mjs" + }, + "engines": { + "node": "^14.16.0 || >=16.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz", + "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ogg-opus-decoder": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/ogg-opus-decoder/-/ogg-opus-decoder-1.7.3.tgz", + "integrity": "sha512-w47tiZpkLgdkpa+34VzYD8mHUj8I9kfWVZa82mBbNwDvB1byfLXSSzW/HxA4fI3e9kVlICSpXGFwMLV1LPdjwg==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7", + "@wasm-audio-decoders/opus-ml": "0.0.2", + "codec-parser": "2.5.0", + "opus-decoder": "0.7.11" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/ohash": { + "version": "2.0.11", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", + "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", + "license": "MIT" + }, + "node_modules/omggif": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz", + "integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==", + "license": "MIT" + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/openai": { + "version": "4.104.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz", + "integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7" + }, + "bin": { + "openai": "bin/cli" + }, + "peerDependencies": { + "ws": "^8.18.0", + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/openai/node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/opus-decoder": { + "version": "0.7.11", + "resolved": "https://registry.npmjs.org/opus-decoder/-/opus-decoder-0.7.11.tgz", + "integrity": "sha512-+e+Jz3vGQLxRTBHs8YJQPRPc1Tr+/aC6coV/DlZylriA29BdHQAYXhvNRKtjftof17OFng0+P4wsFIqQu3a48A==", + "license": "MIT", + "dependencies": { + "@wasm-audio-decoders/common": "9.0.7" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/ora/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ora/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ora/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", + "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-limit": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", + "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", + "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.0.1.tgz", + "integrity": "sha512-RhBdVhSwJb7Ocn3e8ULk4NMwBEuOxe+1zcgphUy9c2e5aR/xbEsdVXxHJ3lynw6Qiqu7OINEyHlZkiblEpaq7w==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.1", + "p-timeout": "^7.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", + "integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-bmfont-ascii": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-ascii/-/parse-bmfont-ascii-1.0.6.tgz", + "integrity": "sha512-U4RrVsUFCleIOBsIGYOMKjn9PavsGOXxbvYGtMOEfnId0SVNsgehXh1DxUdVPLoxd5mvcEtvmKs2Mmf0Mpa1ZA==", + "license": "MIT" + }, + "node_modules/parse-bmfont-binary": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-binary/-/parse-bmfont-binary-1.0.6.tgz", + "integrity": "sha512-GxmsRea0wdGdYthjuUeWTMWPqm2+FAd4GI8vCvhgJsFnoGhTrLhXDDupwTo7rXVAgaLIGoVHDZS9p/5XbSqeWA==", + "license": "MIT" + }, + "node_modules/parse-bmfont-xml": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/parse-bmfont-xml/-/parse-bmfont-xml-1.1.6.tgz", + "integrity": "sha512-0cEliVMZEhrFDwMh4SxIyVJpqYoOWDJ9P895tFuS+XuNzI5UBmBk5U5O4KuJdTnZpSBI4LFA2+ZiJaiwfSwlMA==", + "license": "MIT", + "dependencies": { + "xml-parse-from-string": "^1.0.0", + "xml2js": "^0.5.0" + } + }, + "node_modules/parse-bmfont-xml/node_modules/xml2js": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", + "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz", + "integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.3", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", + "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/peek-readable": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-4.1.0.tgz", + "integrity": "sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "license": "MIT" + }, + "node_modules/pg": { + "version": "8.16.3", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz", + "integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.9.1", + "pg-pool": "^3.10.1", + "pg-protocol": "^1.10.3", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.2.7" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.2.7.tgz", + "integrity": "sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.9.1.tgz", + "integrity": "sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.10.1.tgz", + "integrity": "sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.10.3.tgz", + "integrity": "sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", + "dev": true, + "license": "MIT", + "bin": { + "pidtree": "bin/pidtree.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/pino": { + "version": "9.14.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", + "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz", + "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==", + "license": "MIT" + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pixelmatch": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-5.3.0.tgz", + "integrity": "sha512-o8mkY4E/+LNUf6LzX96ht6k6CEDi65k9G2rjMtBe9Oo+VPKSvl+0GKHuH/AlG+GA5LPG/i5hrekkxUc3s2HU+Q==", + "license": "ISC", + "dependencies": { + "pngjs": "^6.0.0" + }, + "bin": { + "pixelmatch": "bin/pixelmatch" + } + }, + "node_modules/pixelmatch/node_modules/pngjs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-6.0.0.tgz", + "integrity": "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==", + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/pkg-types": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", + "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-linter-helpers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz", + "integrity": "sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-diff": "^1.1.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/prisma": { + "version": "6.19.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.19.0.tgz", + "integrity": "sha512-F3eX7K+tWpkbhl3l4+VkFtrwJlLXbAM+f9jolgoUZbFcm1DgHZ4cq9AgVEgUym2au5Ad/TDLN8lg83D+M10ycw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/config": "6.19.0", + "@prisma/engines": "6.19.0" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz", + "integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-addr/node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, + "node_modules/punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha512-RofWgt/7fL5wP1Y7fxE7/EmTLzQVnB0ycyibJ0OOHIlJqTNzglYFxVwETOcIoJqJmpDXJ9xImDv+Fq34F/d4Dw==", + "license": "MIT" + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/pusher": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/pusher/-/pusher-5.2.0.tgz", + "integrity": "sha512-F6LNiZyJsIkoHLz+YurjKZ1HH8V1/cMggn4k97kihjP3uTvm0P4mZzSFeHOWIy+PlJ2VInJBhUFJBYLsFR5cjg==", + "license": "MIT", + "dependencies": { + "@types/node-fetch": "^2.5.7", + "abort-controller": "^3.0.0", + "is-base64": "^1.1.0", + "node-fetch": "^2.6.1", + "tweetnacl": "^1.0.0", + "tweetnacl-util": "^0.15.0" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/qified": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.5.2.tgz", + "integrity": "sha512-7gJ6mxcQb9vUBOtbKm5mDevbe2uRcOEVp1g4gb/Q+oLntB3HY8eBhOYRxFI2mlDFlY1e4DOSCptzxarXRvzxCA==", + "license": "MIT", + "dependencies": { + "hookified": "^1.13.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qoa-format": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/qoa-format/-/qoa-format-1.0.1.tgz", + "integrity": "sha512-dMB0Z6XQjdpz/Cw4Rf6RiBpQvUSPCfYlQMWvmuWlWkAT7nDQD29cVZ1SwDUB6DYJSitHENwbt90lqfI+7bvMcw==", + "license": "MIT", + "dependencies": { + "@thi.ng/bitstream": "^2.2.12" + } + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qrcode-terminal": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz", + "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==", + "bin": { + "qrcode-terminal": "bin/qrcode-terminal.js" + } + }, + "node_modules/qrcode/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/qrcode/node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/qrcode/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/qrcode/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/qrcode/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/qrcode/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qrcode/node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/qrcode/node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/query-string": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/query-string/-/query-string-7.1.3.tgz", + "integrity": "sha512-hh2WYhq4fi8+b+/2Kg9CEge4fDPvHS534aOOvOZeQ3+Vf2mCFsaFBYj0i+iXcAq6I9Vzp5fjMFBlONvayDC1qg==", + "license": "MIT", + "dependencies": { + "decode-uri-component": "^0.2.2", + "filter-obj": "^1.1.0", + "split-on-first": "^1.0.0", + "strict-uri-encode": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha512-X/xY82scca2tau62i9mDyU9K+I+djTMUsvwf7xnUX5GLvVzgJybOJf4Y6o9Zx3oJK/LSXg5tTZBjwzqVPaPO2g==", + "deprecated": "The querystring API is considered Legacy. new code should use the URLSearchParams API instead.", + "engines": { + "node": ">=0.4.x" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/rc9": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", + "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "license": "MIT", + "dependencies": { + "defu": "^6.1.4", + "destr": "^2.0.3" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readable-web-to-node-stream": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.4.tgz", + "integrity": "sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^4.7.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/readable-web-to-node-stream/node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/readable-web-to-node-stream/node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/redis": { + "version": "4.7.1", + "resolved": "https://registry.npmjs.org/redis/-/redis-4.7.1.tgz", + "integrity": "sha512-S1bJDnqLftzHXHP8JsT5II/CtHWQrASX5K96REjWjlmWKrviSOLWmM7QnRLstAWsu1VBBV1ffV6DzCvxNP0UJQ==", + "license": "MIT", + "workspaces": [ + "./packages/*" + ], + "dependencies": { + "@redis/bloom": "1.2.0", + "@redis/client": "1.6.1", + "@redis/graph": "1.1.1", + "@redis/json": "1.0.7", + "@redis/search": "1.2.0", + "@redis/time-series": "1.1.0" + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-in-the-middle": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "devOptional": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rollup": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", + "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.53.3", + "@rollup/rollup-android-arm64": "4.53.3", + "@rollup/rollup-darwin-arm64": "4.53.3", + "@rollup/rollup-darwin-x64": "4.53.3", + "@rollup/rollup-freebsd-arm64": "4.53.3", + "@rollup/rollup-freebsd-x64": "4.53.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", + "@rollup/rollup-linux-arm-musleabihf": "4.53.3", + "@rollup/rollup-linux-arm64-gnu": "4.53.3", + "@rollup/rollup-linux-arm64-musl": "4.53.3", + "@rollup/rollup-linux-loong64-gnu": "4.53.3", + "@rollup/rollup-linux-ppc64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-musl": "4.53.3", + "@rollup/rollup-linux-s390x-gnu": "4.53.3", + "@rollup/rollup-linux-x64-gnu": "4.53.3", + "@rollup/rollup-linux-x64-musl": "4.53.3", + "@rollup/rollup-openharmony-arm64": "4.53.3", + "@rollup/rollup-win32-arm64-msvc": "4.53.3", + "@rollup/rollup-win32-ia32-msvc": "4.53.3", + "@rollup/rollup-win32-x64-gnu": "4.53.3", + "@rollup/rollup-win32-x64-msvc": "4.53.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz", + "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.3.tgz", + "integrity": "sha512-yqYn1JhPczigF94DMS+shiDMjDowYO6y9+wB/4WgO0Y19jWYk0lQ4tuG5KI7kj4FTp1wxPj5IFfcrz/s1c3jjQ==", + "license": "BlueOak-1.0.0" + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shimmer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", + "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==", + "license": "BSD-2-Clause" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/simple-xml-to-json": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/simple-xml-to-json/-/simple-xml-to-json-1.2.3.tgz", + "integrity": "sha512-kWJDCr9EWtZ+/EYYM5MareWj2cRnZGF93YDNpH4jQiHB+hBIZnfPFSQiVMzZOdk+zXWqTZ/9fTeQNu2DqeiudA==", + "license": "MIT", + "engines": { + "node": ">=20.12.2" + } + }, + "node_modules/simple-yenc": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/simple-yenc/-/simple-yenc-1.0.4.tgz", + "integrity": "sha512-5gvxpSd79e9a3V4QDYUqnqxeD4HGlhCakVpb6gMnDD7lexJggSBJRBO5h52y/iJrdXRilX9UCuDaIJhSWm5OWw==", + "license": "MIT", + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/eshaz" + } + }, + "node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socket.io": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz", + "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.3.2", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz", + "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", + "license": "MIT", + "dependencies": { + "debug": "~4.3.4", + "ws": "~8.17.1" + } + }, + "node_modules/socket.io-adapter/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-adapter/node_modules/ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/socket.io-client": { + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.1.tgz", + "integrity": "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.6.1", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-client/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", + "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io/node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socks": { + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz", + "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/split-on-first": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/split-on-first/-/split-on-first-1.1.0.tgz", + "integrity": "sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/stream-chain": { + "version": "2.2.5", + "resolved": "https://registry.npmjs.org/stream-chain/-/stream-chain-2.2.5.tgz", + "integrity": "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA==", + "license": "BSD-3-Clause" + }, + "node_modules/stream-json": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/stream-json/-/stream-json-1.9.1.tgz", + "integrity": "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw==", + "license": "BSD-3-Clause", + "dependencies": { + "stream-chain": "^2.2.5" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/strict-uri-encode": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-2.0.0.tgz", + "integrity": "sha512-QwiXZgpRcKkhTj2Scnn++4PKtWsH0kpzZ62L2R6c/LUVYv7hVnZqcg2+sMuT6R7Jusu1vviK/MFsu6kNJfWlEQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", + "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", + "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strnum": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", + "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/strtok3": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-6.3.0.tgz", + "integrity": "sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^4.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/swagger-ui-dist": { + "version": "5.30.2", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.30.2.tgz", + "integrity": "sha512-HWCg1DTNE/Nmapt+0m2EPXFwNKNeKK4PwMjkwveN/zn1cV2Kxi9SURd+m0SpdcSgWEK/O64sf8bzXdtUhigtHA==", + "license": "Apache-2.0", + "dependencies": { + "@scarf/scarf": "=1.4.0" + } + }, + "node_modules/swagger-ui-express": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-5.0.1.tgz", + "integrity": "sha512-SrNU3RiBGTLLmFU8GIJdOdanJTl4TOmT27tt3bWWHppqYmAZ6IDuEuBvMU6nZq0zLEe6b/1rACXCgLZqO6ZfrA==", + "license": "MIT", + "dependencies": { + "swagger-ui-dist": ">=5.0.0" + }, + "engines": { + "node": ">= v0.10.32" + }, + "peerDependencies": { + "express": ">=4.0.0 || >=5.0.0-beta" + } + }, + "node_modules/synckit": { + "version": "0.11.11", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.11.tgz", + "integrity": "sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@pkgr/core": "^0.2.9" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/synckit" + } + }, + "node_modules/text-extensions": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/text-extensions/-/text-extensions-2.4.0.tgz", + "integrity": "sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true, + "license": "MIT" + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/thread-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, + "node_modules/tinycolor2": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", + "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==", + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/token-types": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-4.2.1.tgz", + "integrity": "sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "license": "Apache-2.0" + }, + "node_modules/tsconfig-paths": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.2.0.tgz", + "integrity": "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "json5": "^2.2.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tsconfig-paths/node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsup": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz", + "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==", + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.27.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "^0.7.6", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/tsup/node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "license": "MIT" + }, + "node_modules/tsx": { + "version": "4.20.6", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.6.tgz", + "integrity": "sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.25.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/tsx/node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "devOptional": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/tweetnacl-util": { + "version": "0.15.1", + "resolved": "https://registry.npmjs.org/tweetnacl-util/-/tweetnacl-util-0.15.1.tgz", + "integrity": "sha512-RKJBIj8lySrShN4w6i/BonWp2Z/uxwC3h4y7xsRrpP59ZboCd0GpEVsOnMDYLMmKBpYhb5TgHzZXy7wTfYFBRw==", + "license": "Unlicense" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz", + "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz", + "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==", + "license": "MIT" + }, + "node_modules/uint8array-extras": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.16.0.tgz", + "integrity": "sha512-QEg3HPMll0o3t2ourKwOeUAZ159Kn9mx5pnzHRQO8+Wixmh88YdZRiIwat0iNzNNXn0yoEtXJqFpyW7eM8BV7g==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/unicorn-magic": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", + "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/uri-js/node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha512-kbailJa29QrtXnxgq+DdCEGlbTeYM2eJUxsz6vjZavrCYPMIFHMKQmSKYAIuUK2i7hgPm28a8piX5NTUtM/LKQ==", + "license": "MIT", + "dependencies": { + "punycode": "1.3.2", + "querystring": "0.2.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/utif2": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/utif2/-/utif2-4.1.0.tgz", + "integrity": "sha512-+oknB9FHrJ7oW7A2WZYajOcv4FcDR4CfoGB0dPNfxbi4GO05RRnFmt5oa23+9w32EanrYcSJWspUiJkLMs+37w==", + "license": "MIT", + "dependencies": { + "pako": "^1.0.11" + } + }, + "node_modules/util": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/util/-/util-0.12.5.tgz", + "integrity": "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "is-typed-array": "^1.1.3", + "which-typed-array": "^1.1.2" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", + "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, + "node_modules/validator": { + "version": "13.15.23", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.15.23.tgz", + "integrity": "sha512-4yoz1kEWqUjzi5zsPbAS/903QXSYp0UOtHsPpp7p9rHAw/W+dkInskAE386Fat3oKRROwO98d9ZB0G4cObgUyw==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", + "dev": true, + "license": "MIT", + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/web-encoding": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/web-encoding/-/web-encoding-1.1.5.tgz", + "integrity": "sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==", + "license": "MIT", + "dependencies": { + "util": "^0.12.3" + }, + "optionalDependencies": { + "@zxing/text-encoding": "0.9.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/which-typed-array": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz", + "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-parse-from-string": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/xml-parse-from-string/-/xml-parse-from-string-1.0.1.tgz", + "integrity": "sha512-ErcKwJTF54uRzzNMXq2X5sMIy88zJvfN2DmdoQvy7PAFJ+tPRU6ydWuOKNMyfmOjdyBQTFREi60s0Y0SyI0G0g==", + "license": "MIT" + }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz", + "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "devOptional": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz", + "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json index f7e77194e..56e32fcc8 100644 --- a/package.json +++ b/package.json @@ -1,20 +1,26 @@ { "name": "evolution-api", - "version": "2.2.0", + "version": "2.3.7", "description": "Rest api for communication with WhatsApp", "main": "./dist/main.js", "type": "commonjs", "scripts": { "build": "tsc --noEmit && tsup", - "start": "tsnd -r tsconfig-paths/register --files --transpile-only ./src/main.ts", + "start": "tsx ./src/main.ts", "start:prod": "node dist/main", - "dev:server": "tsnd -r tsconfig-paths/register --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts", - "test": "tsnd -r tsconfig-paths/register --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts", + "dev:server": "tsx watch ./src/main.ts", + "test": "tsx watch ./test/all.test.ts", "lint": "eslint --fix --ext .ts src", + "lint:check": "eslint --ext .ts src", + "commit": "cz", + "commitlint": "commitlint --edit", "db:generate": "node runWithProvider.js \"npx prisma generate --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", "db:deploy": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate deploy --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", + "db:deploy:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate deploy --schema prisma\\DATABASE_PROVIDER-schema.prisma\"", "db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"", - "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"" + "db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"", + "db:migrate:dev:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate dev --schema prisma\\DATABASE_PROVIDER-schema.prisma\"", + "prepare": "husky" }, "repository": { "type": "git", @@ -38,81 +44,115 @@ ], "author": { "name": "Davidson Gomes", - "email": "contato@atendai.com" + "email": "contato@evolution-api.com" }, "license": "Apache-2.0", "bugs": { "url": "https://github.com/EvolutionAPI/evolution-api/issues" }, "homepage": "https://github.com/EvolutionAPI/evolution-api#readme", + "lint-staged": { + "src/**/*.{ts,js}": [ + "eslint --fix" + ], + "src/**/*.ts": [ + "sh -c 'tsc --noEmit'" + ] + }, + "config": { + "commitizen": { + "path": "cz-conventional-changelog" + } + }, "dependencies": { "@adiwajshing/keyed-db": "^0.2.4", - "@aws-sdk/client-sqs": "^3.569.0", + "@aws-sdk/client-sqs": "^3.891.0", "@ffmpeg-installer/ffmpeg": "^1.1.0", "@figuro/chatwoot-sdk": "^1.1.16", "@hapi/boom": "^10.0.1", - "@prisma/client": "^5.15.0", - "@sentry/node": "^8.28.0", - "amqplib": "^0.10.3", - "axios": "^1.6.5", - "baileys": "github:EvolutionAPI/Baileys", + "@paralleldrive/cuid2": "^2.2.2", + "@prisma/client": "^6.16.2", + "@sentry/node": "^10.12.0", + "@types/uuid": "^10.0.0", + "amqplib": "^0.10.5", + "audio-decode": "^2.2.3", + "axios": "^1.7.9", + "baileys": "7.0.0-rc.9", "class-validator": "^0.14.1", - "compression": "^1.7.4", + "compression": "^1.7.5", "cors": "^2.8.5", - "dayjs": "^1.11.7", - "dotenv": "^16.4.5", + "dayjs": "^1.11.13", + "dotenv": "^16.4.7", + "emoji-regex": "^10.4.0", "eventemitter2": "^6.4.9", - "express": "^4.18.2", + "express": "^4.21.2", "express-async-errors": "^3.1.1", - "fluent-ffmpeg": "^2.1.2", - "form-data": "^4.0.0", - "https-proxy-agent": "^7.0.2", + "fluent-ffmpeg": "^2.1.3", + "form-data": "^4.0.1", + "https-proxy-agent": "^7.0.6", + "fetch-socks": "^1.3.2", "i18next": "^23.7.19", - "jimp": "^0.16.13", + "jimp": "^1.6.0", "json-schema": "^0.4.0", "jsonschema": "^1.4.1", - "link-preview-js": "^3.0.4", + "jsonwebtoken": "^9.0.2", + "kafkajs": "^2.2.4", + "libphonenumber-js": "^1.12.25", + "link-preview-js": "^3.0.13", "long": "^5.2.3", - "mediainfo.js": "^0.3.2", - "mime": "^3.0.0", - "minio": "^8.0.1", - "multer": "^1.4.5-lts.1", + "mediainfo.js": "^0.3.4", + "mime": "^4.0.0", + "mime-types": "^2.1.35", + "minio": "^8.0.3", + "multer": "^2.0.2", + "nats": "^2.29.1", "node-cache": "^5.1.2", "node-cron": "^3.0.3", - "openai": "^4.52.7", - "pg": "^8.11.3", - "pino": "^8.11.0", - "prisma": "^5.15.0", + "openai": "^4.77.3", + "pg": "^8.13.1", + "pino": "^9.10.0", + "prisma": "^6.1.0", "pusher": "^5.2.0", - "qrcode": "^1.5.1", + "qrcode": "^1.5.4", "qrcode-terminal": "^0.12.0", - "redis": "^4.6.5", - "sharp": "^0.32.2", - "socket.io": "^4.7.1", - "tsup": "^8.2.4", - "uuid": "^9.0.0" + "redis": "^4.7.0", + "rxjs": "^7.8.2", + "sharp": "^0.34.2", + "socket.io": "^4.8.1", + "socket.io-client": "^4.8.1", + "socks-proxy-agent": "^8.0.5", + "swagger-ui-express": "^5.0.1", + "tsup": "^8.3.5", + "undici": "^7.16.0", + "uuid": "^13.0.0" }, "devDependencies": { - "@types/compression": "^1.7.2", - "@types/cors": "^2.8.13", - "@types/express": "^4.17.17", + "@commitlint/cli": "^19.8.1", + "@commitlint/config-conventional": "^19.8.1", + "@types/compression": "^1.7.5", + "@types/cors": "^2.8.17", + "@types/express": "^4.17.18", "@types/json-schema": "^7.0.15", - "@types/mime": "3.0.0", - "@types/node": "^18.15.11", + "@types/mime": "^4.0.0", + "@types/mime-types": "^2.1.4", + "@types/node": "^24.5.2", "@types/node-cron": "^3.0.11", - "@types/qrcode": "^1.5.0", - "@types/qrcode-terminal": "^0.12.0", - "@types/uuid": "^8.3.4", - "@typescript-eslint/eslint-plugin": "^5.62.0", - "@typescript-eslint/parser": "^5.62.0", + "@types/qrcode": "^1.5.5", + "@types/qrcode-terminal": "^0.12.2", + "@typescript-eslint/eslint-plugin": "^8.44.0", + "@typescript-eslint/parser": "^8.44.0", + "commitizen": "^4.3.1", + "cz-conventional-changelog": "^3.3.0", "eslint": "^8.45.0", - "eslint-config-prettier": "^8.8.0", - "eslint-plugin-import": "^2.27.5", - "eslint-plugin-prettier": "^4.2.1", - "eslint-plugin-simple-import-sort": "^10.0.0", - "prettier": "^2.8.8", - "ts-node-dev": "^2.0.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-import": "^2.31.0", + "eslint-plugin-prettier": "^5.2.1", + "eslint-plugin-simple-import-sort": "^12.1.1", + "husky": "^9.1.7", + "lint-staged": "^16.1.6", + "prettier": "^3.4.2", "tsconfig-paths": "^4.2.0", - "typescript": "^5.5.4" + "tsx": "^4.20.5", + "typescript": "^5.7.2" } } diff --git a/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql b/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql new file mode 100644 index 000000000..ae17f418b --- /dev/null +++ b/prisma/mysql-migrations/20241108101333_fix_message_status_as_string/migration.sql @@ -0,0 +1,232 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- AlterTable +ALTER TABLE `Chat` ADD COLUMN `unreadMessages` INTEGER NOT NULL DEFAULT 0, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBot` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBotSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `IsOnWhatsapp` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Message` MODIFY `status` VARCHAR(30) NULL; + +-- AlterTable +ALTER TABLE `OpenaiBot` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` ADD COLUMN `splitMessages` BOOLEAN NULL DEFAULT false, + ADD COLUMN `timePerChar` INTEGER NULL DEFAULT 50, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateTable +CREATE TABLE `Pusher` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `appId` VARCHAR(100) NOT NULL, + `key` VARCHAR(100) NOT NULL, + `secret` VARCHAR(100) NOT NULL, + `cluster` VARCHAR(100) NOT NULL, + `useTLS` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Pusher_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE INDEX `Chat_remoteJid_idx` ON `Chat`(`remoteJid`); + +-- CreateIndex +CREATE INDEX `Contact_remoteJid_idx` ON `Contact`(`remoteJid`); + +-- CreateIndex +CREATE INDEX `Setting_instanceId_idx` ON `Setting`(`instanceId`); + +-- CreateIndex +CREATE INDEX `Webhook_instanceId_idx` ON `Webhook`(`instanceId`); + +-- AddForeignKey +ALTER TABLE `Pusher` ADD CONSTRAINT `Pusher_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- RenameIndex +ALTER TABLE `Chat` RENAME INDEX `Chat_instanceId_fkey` TO `Chat_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `Contact` RENAME INDEX `Contact_instanceId_fkey` TO `Contact_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `Message` RENAME INDEX `Message_instanceId_fkey` TO `Message_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `MessageUpdate` RENAME INDEX `MessageUpdate_instanceId_fkey` TO `MessageUpdate_instanceId_idx`; + +-- RenameIndex +ALTER TABLE `MessageUpdate` RENAME INDEX `MessageUpdate_messageId_fkey` TO `MessageUpdate_messageId_idx`; diff --git a/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql b/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql new file mode 100644 index 000000000..547111b6c --- /dev/null +++ b/prisma/mysql-migrations/20250214181954_add_wavoip_token_column/migration.sql @@ -0,0 +1,175 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - A unique constraint covering the columns `[instanceId,remoteJid]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. + +*/ +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `IsOnWhatsapp` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Pusher` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` ADD COLUMN `wavoipToken` VARCHAR(100) NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateIndex +CREATE UNIQUE INDEX `Chat_instanceId_remoteJid_key` ON `Chat`(`instanceId`, `remoteJid`); diff --git a/prisma/mysql-migrations/20250225180031_add_nats_integration/migration.sql b/prisma/mysql-migrations/20250225180031_add_nats_integration/migration.sql new file mode 100644 index 000000000..bd90c55c9 --- /dev/null +++ b/prisma/mysql-migrations/20250225180031_add_nats_integration/migration.sql @@ -0,0 +1,17 @@ +-- CreateTable +CREATE TABLE `Nats` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE UNIQUE INDEX `Nats_instanceId_key` ON `Nats`(`instanceId`); + +-- AddForeignKey +ALTER TABLE `Nats` ADD CONSTRAINT `Nats_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; \ No newline at end of file diff --git a/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql b/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql new file mode 100644 index 000000000..11bdb5f55 --- /dev/null +++ b/prisma/mysql-migrations/20250510035200_add_wavoip_token_to_settings_table/migration.sql @@ -0,0 +1,26 @@ +/* +Warnings: + +- A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. + +*/ + +-- AlterTable +SET @column_exists := ( + SELECT COUNT(*) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'Setting' + AND column_name = 'wavoipToken' +); + +SET @sql := IF(@column_exists = 0, + 'ALTER TABLE Setting ADD COLUMN wavoipToken VARCHAR(100);', + 'SELECT "Column already exists";' +); + +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +ALTER TABLE Chat ADD CONSTRAINT unique_remote_instance UNIQUE (remoteJid, instanceId); diff --git a/prisma/mysql-migrations/20250514232744_add_n8n_table/migration.sql b/prisma/mysql-migrations/20250514232744_add_n8n_table/migration.sql new file mode 100644 index 000000000..3024583d0 --- /dev/null +++ b/prisma/mysql-migrations/20250514232744_add_n8n_table/migration.sql @@ -0,0 +1,62 @@ +-- CreateTable +CREATE TABLE `N8n` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255), + `webhookUrl` VARCHAR(255), + `basicAuthUser` VARCHAR(255), + `basicAuthPass` VARCHAR(255), + `expire` INTEGER DEFAULT 0, + `keywordFinish` VARCHAR(100), + `delayMessage` INTEGER, + `unknownMessage` VARCHAR(100), + `listeningFromMe` BOOLEAN DEFAULT false, + `stopBotFromMe` BOOLEAN DEFAULT false, + `keepOpen` BOOLEAN DEFAULT false, + `debounceTime` INTEGER, + `ignoreJids` JSON, + `splitMessages` BOOLEAN DEFAULT false, + `timePerChar` INTEGER DEFAULT 50, + `triggerType` ENUM('all', 'keyword', 'none') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `N8nSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER DEFAULT 0, + `keywordFinish` VARCHAR(100), + `delayMessage` INTEGER, + `unknownMessage` VARCHAR(100), + `listeningFromMe` BOOLEAN DEFAULT false, + `stopBotFromMe` BOOLEAN DEFAULT false, + `keepOpen` BOOLEAN DEFAULT false, + `debounceTime` INTEGER, + `ignoreJids` JSON, + `splitMessages` BOOLEAN DEFAULT false, + `timePerChar` INTEGER DEFAULT 50, + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `n8nIdFallback` VARCHAR(100), + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE UNIQUE INDEX `N8nSetting_instanceId_key` ON `N8nSetting`(`instanceId`); + +-- AddForeignKey +ALTER TABLE `N8n` ADD CONSTRAINT `N8n_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `N8nSetting` ADD CONSTRAINT `N8nSetting_n8nIdFallback_fkey` FOREIGN KEY (`n8nIdFallback`) REFERENCES `N8n`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `N8nSetting` ADD CONSTRAINT `N8nSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/20250515211815_add_evoai_table/migration.sql b/prisma/mysql-migrations/20250515211815_add_evoai_table/migration.sql new file mode 100644 index 000000000..0fe549f6d --- /dev/null +++ b/prisma/mysql-migrations/20250515211815_add_evoai_table/migration.sql @@ -0,0 +1,61 @@ +-- CreateTable +CREATE TABLE `Evoai` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT true, + `description` VARCHAR(255), + `agentUrl` VARCHAR(255), + `apiKey` VARCHAR(255), + `expire` INTEGER DEFAULT 0, + `keywordFinish` VARCHAR(100), + `delayMessage` INTEGER, + `unknownMessage` VARCHAR(100), + `listeningFromMe` BOOLEAN DEFAULT false, + `stopBotFromMe` BOOLEAN DEFAULT false, + `keepOpen` BOOLEAN DEFAULT false, + `debounceTime` INTEGER, + `ignoreJids` JSON, + `splitMessages` BOOLEAN DEFAULT false, + `timePerChar` INTEGER DEFAULT 50, + `triggerType` ENUM('all', 'keyword', 'none') NULL, + `triggerOperator` ENUM('contains', 'equals', 'startsWith', 'endsWith', 'regex') NULL, + `triggerValue` VARCHAR(191) NULL, + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `EvoaiSetting` ( + `id` VARCHAR(191) NOT NULL, + `expire` INTEGER DEFAULT 0, + `keywordFinish` VARCHAR(100), + `delayMessage` INTEGER, + `unknownMessage` VARCHAR(100), + `listeningFromMe` BOOLEAN DEFAULT false, + `stopBotFromMe` BOOLEAN DEFAULT false, + `keepOpen` BOOLEAN DEFAULT false, + `debounceTime` INTEGER, + `ignoreJids` JSON, + `splitMessages` BOOLEAN DEFAULT false, + `timePerChar` INTEGER DEFAULT 50, + `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `evoaiIdFallback` VARCHAR(100), + `instanceId` VARCHAR(191) NOT NULL, + + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateIndex +CREATE UNIQUE INDEX `EvoaiSetting_instanceId_key` ON `EvoaiSetting`(`instanceId`); + +-- AddForeignKey +ALTER TABLE `Evoai` ADD CONSTRAINT `Evoai_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `EvoaiSetting` ADD CONSTRAINT `EvoaiSetting_evoaiIdFallback_fkey` FOREIGN KEY (`evoaiIdFallback`) REFERENCES `Evoai`(`id`) ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE `EvoaiSetting` ADD CONSTRAINT `EvoaiSetting_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql b/prisma/mysql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql new file mode 100644 index 000000000..09211634f --- /dev/null +++ b/prisma/mysql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql @@ -0,0 +1,2 @@ +-- DropIndex +ALTER TABLE `Media` DROP INDEX `Media_fileName_key`; diff --git a/prisma/mysql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql b/prisma/mysql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql new file mode 100644 index 000000000..3e97649ce --- /dev/null +++ b/prisma/mysql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE `Typebot` ADD COLUMN `splitMessages` BOOLEAN DEFAULT false, +ADD COLUMN `timePerChar` INTEGER DEFAULT 50; + +-- AlterTable +ALTER TABLE `TypebotSetting` ADD COLUMN `splitMessages` BOOLEAN DEFAULT false, +ADD COLUMN `timePerChar` INTEGER DEFAULT 50; diff --git a/prisma/mysql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql b/prisma/mysql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql new file mode 100644 index 000000000..78cf8bd11 --- /dev/null +++ b/prisma/mysql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE `IsOnWhatsapp` ADD COLUMN `lid` VARCHAR(100); diff --git a/prisma/mysql-migrations/20250918183910_add_kafka_integration/migration.sql b/prisma/mysql-migrations/20250918183910_add_kafka_integration/migration.sql new file mode 100644 index 000000000..c3a089bd0 --- /dev/null +++ b/prisma/mysql-migrations/20250918183910_add_kafka_integration/migration.sql @@ -0,0 +1,231 @@ +/* + Warnings: + + - You are about to alter the column `createdAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chat` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Chatwoot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Contact` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Dify` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `DifySetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Evoai` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Evoai` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvoaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvoaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `EvolutionBotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Flowise` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `FlowiseSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `disconnectionAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Instance` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IntegrationSession` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the column `lid` on the `IsOnWhatsapp` table. All the data in the column will be lost. + - You are about to alter the column `createdAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `IsOnWhatsapp` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Label` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Media` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `N8n` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `N8n` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `N8nSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `N8nSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Nats` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Nats` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiBot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiCreds` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `OpenaiSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Proxy` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Pusher` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Rabbitmq` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Session` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Setting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Sqs` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Template` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the column `splitMessages` on the `Typebot` table. All the data in the column will be lost. + - You are about to drop the column `timePerChar` on the `Typebot` table. All the data in the column will be lost. + - You are about to alter the column `createdAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Typebot` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to drop the column `splitMessages` on the `TypebotSetting` table. All the data in the column will be lost. + - You are about to drop the column `timePerChar` on the `TypebotSetting` table. All the data in the column will be lost. + - You are about to alter the column `createdAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `TypebotSetting` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Webhook` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `createdAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + - You are about to alter the column `updatedAt` on the `Websocket` table. The data in that column could be lost. The data in that column will be cast from `Timestamp(0)` to `Timestamp`. + +*/ +-- DropIndex +DROP INDEX `unique_remote_instance` ON `Chat`; + +-- AlterTable +ALTER TABLE `Chat` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Chatwoot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Contact` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `Dify` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `DifySetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Evoai` MODIFY `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvoaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `EvolutionBotSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Flowise` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `FlowiseSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Instance` MODIFY `disconnectionAt` TIMESTAMP NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `IntegrationSession` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `IsOnWhatsapp` DROP COLUMN `lid`, + MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Label` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Media` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `N8n` MODIFY `triggerType` ENUM('all', 'keyword', 'none', 'advanced') NULL, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `N8nSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Nats` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiBot` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiCreds` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `OpenaiSetting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Proxy` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Pusher` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Rabbitmq` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Session` MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- AlterTable +ALTER TABLE `Setting` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Sqs` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Template` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Typebot` DROP COLUMN `splitMessages`, + DROP COLUMN `timePerChar`, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NULL; + +-- AlterTable +ALTER TABLE `TypebotSetting` DROP COLUMN `splitMessages`, + DROP COLUMN `timePerChar`, + MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Webhook` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- AlterTable +ALTER TABLE `Websocket` MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + MODIFY `updatedAt` TIMESTAMP NOT NULL; + +-- CreateTable +CREATE TABLE `Kafka` ( + `id` VARCHAR(191) NOT NULL, + `enabled` BOOLEAN NOT NULL DEFAULT false, + `events` JSON NOT NULL, + `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, + `updatedAt` TIMESTAMP NOT NULL, + `instanceId` VARCHAR(191) NOT NULL, + + UNIQUE INDEX `Kafka_instanceId_key`(`instanceId`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `Kafka` ADD CONSTRAINT `Kafka_instanceId_fkey` FOREIGN KEY (`instanceId`) REFERENCES `Instance`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/mysql-migrations/migration_lock.toml b/prisma/mysql-migrations/migration_lock.toml index e5a788a7a..8a21669ab 100644 --- a/prisma/mysql-migrations/migration_lock.toml +++ b/prisma/mysql-migrations/migration_lock.toml @@ -1,3 +1,3 @@ # Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) +# It should be added in your version-control system (e.g., Git) provider = "mysql" \ No newline at end of file diff --git a/prisma/mysql-schema.prisma b/prisma/mysql-schema.prisma index ff968882b..71b5a743f 100644 --- a/prisma/mysql-schema.prisma +++ b/prisma/mysql-schema.prisma @@ -86,7 +86,9 @@ model Instance { Proxy Proxy? Setting Setting? Rabbitmq Rabbitmq? + Nats Nats? Sqs Sqs? + Kafka Kafka? Websocket Websocket? Typebot Typebot[] Session Session? @@ -99,11 +101,15 @@ model Instance { Template Template[] Dify Dify[] DifySetting DifySetting? - integrationSessions IntegrationSession[] + IntegrationSession IntegrationSession[] EvolutionBot EvolutionBot[] EvolutionBotSetting EvolutionBotSetting? Flowise Flowise[] FlowiseSetting FlowiseSetting? + N8n N8n[] + N8nSetting N8nSetting? + Evoai Evoai[] + EvoaiSetting EvoaiSetting? Pusher Pusher? } @@ -116,15 +122,17 @@ model Session { } model Chat { - id String @id @default(cuid()) - remoteJid String @db.VarChar(100) - name String? @db.VarChar(100) - labels Json? @db.Json - createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp - updatedAt DateTime? @updatedAt @db.Timestamp - Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) - instanceId String + id String @id @default(cuid()) + remoteJid String @db.VarChar(100) + name String? @db.VarChar(100) + labels Json? @db.Json + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String unreadMessages Int @default(0) + + @@unique([instanceId, remoteJid]) @@index([instanceId]) @@index([remoteJid]) } @@ -169,6 +177,7 @@ model Message { sessionId String? session IntegrationSession? @relation(fields: [sessionId], references: [id]) + @@index([instanceId]) } @@ -184,6 +193,7 @@ model MessageUpdate { messageId String Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + @@index([instanceId]) @@index([messageId]) } @@ -200,6 +210,7 @@ model Webhook { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -263,10 +274,12 @@ model Setting { readMessages Boolean @default(false) readStatus Boolean @default(false) syncFullHistory Boolean @default(false) + wavoipToken String? @db.VarChar(100) createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -280,6 +293,16 @@ model Rabbitmq { instanceId String @unique } +model Nats { + id String @id @default(cuid()) + enabled Boolean @default(false) + events Json @db.Json + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Sqs { id String @id @default(cuid()) enabled Boolean @default(false) @@ -290,6 +313,16 @@ model Sqs { instanceId String @unique } +model Kafka { + id String @id @default(cuid()) + enabled Boolean @default(false) + events Json @db.Json + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Websocket { id String @id @default(cuid()) enabled Boolean @default(false) @@ -380,7 +413,7 @@ model IntegrationSession { model Media { id String @id @default(cuid()) - fileName String @unique @db.VarChar(500) + fileName String @db.VarChar(500) type String @db.VarChar(100) mimetype String @db.VarChar(100) createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp @@ -625,3 +658,100 @@ model IsOnWhatsapp { createdAt DateTime @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp } + +model N8n { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.TinyInt() + description String? @db.VarChar(255) + webhookUrl String? @db.VarChar(255) + basicAuthUser String? @db.VarChar(255) + basicAuthPass String? @db.VarChar(255) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + splitMessages Boolean? @default(false) + timePerChar Int? @default(50) @db.Int + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + N8nSetting N8nSetting[] +} + +model N8nSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + splitMessages Boolean? @default(false) + timePerChar Int? @default(50) @db.Int + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback N8n? @relation(fields: [n8nIdFallback], references: [id]) + n8nIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Evoai { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.TinyInt() + description String? @db.VarChar(255) + agentUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + splitMessages Boolean? @default(false) + timePerChar Int? @default(50) @db.Int + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvoaiSetting EvoaiSetting[] +} + +model EvoaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Int + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Int + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) + stopBotFromMe Boolean? @default(false) + keepOpen Boolean? @default(false) + debounceTime Int? @db.Int + ignoreJids Json? + splitMessages Boolean? @default(false) + timePerChar Int? @default(50) @db.Int + createdAt DateTime? @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Evoai? @relation(fields: [evoaiIdFallback], references: [id]) + evoaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} diff --git a/prisma/postgresql-migrations/20250116001415_add_wavoip_token_to_settings_table/migration.sql b/prisma/postgresql-migrations/20250116001415_add_wavoip_token_to_settings_table/migration.sql new file mode 100644 index 000000000..00f9bc7d2 --- /dev/null +++ b/prisma/postgresql-migrations/20250116001415_add_wavoip_token_to_settings_table/migration.sql @@ -0,0 +1,9 @@ +/* +Warnings: + +- A unique constraint covering the columns `[remoteJid,instanceId]` on the table `Chat` will be added. If there are existing duplicate values, this will fail. + +*/ + +-- AlterTable +ALTER TABLE "Setting" ADD COLUMN IF NOT EXISTS "wavoipToken" VARCHAR(100); diff --git a/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql b/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql new file mode 100644 index 000000000..1e6c0e60f --- /dev/null +++ b/prisma/postgresql-migrations/20250225180031_add_nats_integration/migration.sql @@ -0,0 +1,17 @@ +-- CreateTable +CREATE TABLE "Nats" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "events" JSONB NOT NULL, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Nats_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Nats_instanceId_key" ON "Nats"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Nats" ADD CONSTRAINT "Nats_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql b/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql new file mode 100644 index 000000000..18a0d23d7 --- /dev/null +++ b/prisma/postgresql-migrations/20250514232744_add_n8n_table/migration.sql @@ -0,0 +1,62 @@ +-- CreateTable +CREATE TABLE "N8n" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "webhookUrl" VARCHAR(255), + "basicAuthUser" VARCHAR(255), + "basicAuthPass" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "N8n_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "N8nSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "n8nIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "N8nSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "N8nSetting_instanceId_key" ON "N8nSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "N8n" ADD CONSTRAINT "N8n_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "N8nSetting" ADD CONSTRAINT "N8nSetting_n8nIdFallback_fkey" FOREIGN KEY ("n8nIdFallback") REFERENCES "N8n"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "N8nSetting" ADD CONSTRAINT "N8nSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql b/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql new file mode 100644 index 000000000..1350d8eb2 --- /dev/null +++ b/prisma/postgresql-migrations/20250515211815_add_evoai_table/migration.sql @@ -0,0 +1,61 @@ +-- CreateTable +CREATE TABLE "Evoai" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT true, + "description" VARCHAR(255), + "agentUrl" VARCHAR(255), + "apiKey" VARCHAR(255), + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "triggerType" "TriggerType", + "triggerOperator" "TriggerOperator", + "triggerValue" TEXT, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Evoai_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "EvoaiSetting" ( + "id" TEXT NOT NULL, + "expire" INTEGER DEFAULT 0, + "keywordFinish" VARCHAR(100), + "delayMessage" INTEGER, + "unknownMessage" VARCHAR(100), + "listeningFromMe" BOOLEAN DEFAULT false, + "stopBotFromMe" BOOLEAN DEFAULT false, + "keepOpen" BOOLEAN DEFAULT false, + "debounceTime" INTEGER, + "ignoreJids" JSONB, + "splitMessages" BOOLEAN DEFAULT false, + "timePerChar" INTEGER DEFAULT 50, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "evoaiIdFallback" VARCHAR(100), + "instanceId" TEXT NOT NULL, + + CONSTRAINT "EvoaiSetting_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "EvoaiSetting_instanceId_key" ON "EvoaiSetting"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Evoai" ADD CONSTRAINT "Evoai_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvoaiSetting" ADD CONSTRAINT "EvoaiSetting_evoaiIdFallback_fkey" FOREIGN KEY ("evoaiIdFallback") REFERENCES "Evoai"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "EvoaiSetting" ADD CONSTRAINT "EvoaiSetting_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql b/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql new file mode 100644 index 000000000..25c1eda5c --- /dev/null +++ b/prisma/postgresql-migrations/20250516012152_remove_unique_atribute_for_file_name_in_media/migration.sql @@ -0,0 +1,2 @@ +-- DropIndex +DROP INDEX "Media_fileName_key"; diff --git a/prisma/postgresql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql b/prisma/postgresql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql new file mode 100644 index 000000000..5234bd469 --- /dev/null +++ b/prisma/postgresql-migrations/20250612155048_add_coluns_trypebot_tables/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE "Typebot" ADD COLUMN "splitMessages" BOOLEAN DEFAULT false, +ADD COLUMN "timePerChar" INTEGER DEFAULT 50; + +-- AlterTable +ALTER TABLE "TypebotSetting" ADD COLUMN "splitMessages" BOOLEAN DEFAULT false, +ADD COLUMN "timePerChar" INTEGER DEFAULT 50; diff --git a/prisma/postgresql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql b/prisma/postgresql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql new file mode 100644 index 000000000..c9510fcb1 --- /dev/null +++ b/prisma/postgresql-migrations/20250613143000_add_lid_column_to_is_onwhatsapp/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "IsOnWhatsapp" ADD COLUMN "lid" VARCHAR(100); diff --git a/prisma/postgresql-migrations/20250918182355_add_kafka_integration/migration.sql b/prisma/postgresql-migrations/20250918182355_add_kafka_integration/migration.sql new file mode 100644 index 000000000..2985c5502 --- /dev/null +++ b/prisma/postgresql-migrations/20250918182355_add_kafka_integration/migration.sql @@ -0,0 +1,17 @@ +-- CreateTable +CREATE TABLE "Kafka" ( + "id" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "events" JSONB NOT NULL, + "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP NOT NULL, + "instanceId" TEXT NOT NULL, + + CONSTRAINT "Kafka_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Kafka_instanceId_key" ON "Kafka"("instanceId"); + +-- AddForeignKey +ALTER TABLE "Kafka" ADD CONSTRAINT "Kafka_instanceId_fkey" FOREIGN KEY ("instanceId") REFERENCES "Instance"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/postgresql-migrations/20251122003044_add_chat_instance_remotejid_unique/migration.sql b/prisma/postgresql-migrations/20251122003044_add_chat_instance_remotejid_unique/migration.sql new file mode 100644 index 000000000..8b27cc1ef --- /dev/null +++ b/prisma/postgresql-migrations/20251122003044_add_chat_instance_remotejid_unique/migration.sql @@ -0,0 +1,16 @@ +-- 1. Cleanup: Remove duplicate chats, keeping the most recently updated one +DELETE FROM "Chat" +WHERE id IN ( + SELECT id FROM ( + SELECT id, + ROW_NUMBER() OVER ( + PARTITION BY "instanceId", "remoteJid" + ORDER BY "updatedAt" DESC + ) as row_num + FROM "Chat" + ) t + WHERE t.row_num > 1 +); + +-- 2. Create the unique index (Constraint) +CREATE UNIQUE INDEX "Chat_instanceId_remoteJid_key" ON "Chat"("instanceId", "remoteJid"); diff --git a/prisma/postgresql-migrations/migration_lock.toml b/prisma/postgresql-migrations/migration_lock.toml index fbffa92c2..648c57fd5 100644 --- a/prisma/postgresql-migrations/migration_lock.toml +++ b/prisma/postgresql-migrations/migration_lock.toml @@ -1,3 +1,3 @@ # Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) +# It should be added in your version-control system (e.g., Git) provider = "postgresql" \ No newline at end of file diff --git a/prisma/postgresql-schema.prisma b/prisma/postgresql-schema.prisma index 011de9a09..6b98f88da 100644 --- a/prisma/postgresql-schema.prisma +++ b/prisma/postgresql-schema.prisma @@ -86,7 +86,9 @@ model Instance { Proxy Proxy? Setting Setting? Rabbitmq Rabbitmq? + Nats Nats? Sqs Sqs? + Kafka Kafka? Websocket Websocket? Typebot Typebot[] Session Session? @@ -99,12 +101,16 @@ model Instance { Template Template[] Dify Dify[] DifySetting DifySetting? - integrationSessions IntegrationSession[] + IntegrationSession IntegrationSession[] EvolutionBot EvolutionBot[] EvolutionBotSetting EvolutionBotSetting? Flowise Flowise[] FlowiseSetting FlowiseSetting? Pusher Pusher? + N8n N8n[] + N8nSetting N8nSetting[] + Evoai Evoai[] + EvoaiSetting EvoaiSetting? } model Session { @@ -125,6 +131,8 @@ model Chat { Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String unreadMessages Int @default(0) + + @@unique([instanceId, remoteJid]) @@index([instanceId]) @@index([remoteJid]) } @@ -168,6 +176,7 @@ model Message { sessionId String? session IntegrationSession? @relation(fields: [sessionId], references: [id]) + @@index([instanceId]) } @@ -183,6 +192,7 @@ model MessageUpdate { messageId String Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String + @@index([instanceId]) @@index([messageId]) } @@ -199,6 +209,7 @@ model Webhook { updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -264,10 +275,12 @@ model Setting { readMessages Boolean @default(false) @db.Boolean readStatus Boolean @default(false) @db.Boolean syncFullHistory Boolean @default(false) @db.Boolean + wavoipToken String? @db.VarChar(100) createdAt DateTime? @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String @unique + @@index([instanceId]) } @@ -281,6 +294,16 @@ model Rabbitmq { instanceId String @unique } +model Nats { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Sqs { id String @id @default(cuid()) enabled Boolean @default(false) @db.Boolean @@ -291,6 +314,16 @@ model Sqs { instanceId String @unique } +model Kafka { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + model Websocket { id String @id @default(cuid()) enabled Boolean @default(false) @db.Boolean @@ -336,6 +369,8 @@ model Typebot { triggerType TriggerType? triggerOperator TriggerOperator? triggerValue String? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) instanceId String TypebotSetting TypebotSetting[] @@ -353,6 +388,8 @@ model TypebotSetting { debounceTime Int? @db.Integer typebotIdFallback String? @db.VarChar(100) ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer createdAt DateTime? @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp Fallback Typebot? @relation(fields: [typebotIdFallback], references: [id]) @@ -362,7 +399,7 @@ model TypebotSetting { model Media { id String @id @default(cuid()) - fileName String @unique @db.VarChar(500) + fileName String @db.VarChar(500) type String @db.VarChar(100) mimetype String @db.VarChar(100) createdAt DateTime? @default(now()) @db.Date @@ -623,6 +660,104 @@ model IsOnWhatsapp { id String @id @default(cuid()) remoteJid String @unique @db.VarChar(100) jidOptions String + lid String? @db.VarChar(100) createdAt DateTime @default(now()) @db.Timestamp updatedAt DateTime @updatedAt @db.Timestamp } + +model N8n { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + webhookUrl String? @db.VarChar(255) + basicAuthUser String? @db.VarChar(255) + basicAuthPass String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + N8nSetting N8nSetting[] +} + +model N8nSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback N8n? @relation(fields: [n8nIdFallback], references: [id]) + n8nIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Evoai { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + agentUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvoaiSetting EvoaiSetting[] +} + +model EvoaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Evoai? @relation(fields: [evoaiIdFallback], references: [id]) + evoaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} diff --git a/prisma/psql_bouncer-schema.prisma b/prisma/psql_bouncer-schema.prisma new file mode 100644 index 000000000..a3f4dbe90 --- /dev/null +++ b/prisma/psql_bouncer-schema.prisma @@ -0,0 +1,763 @@ +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions? +// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_BOUNCER_CONNECTION_URI") + directUrl = env("DATABASE_CONNECTION_URI") +} + +enum InstanceConnectionStatus { + open + close + connecting +} + +enum DeviceMessage { + ios + android + web + unknown + desktop +} + +enum SessionStatus { + opened + closed + paused +} + +enum TriggerType { + all + keyword + none + advanced +} + +enum TriggerOperator { + contains + equals + startsWith + endsWith + regex +} + +enum OpenaiBotType { + assistant + chatCompletion +} + +enum DifyBotType { + chatBot + textGenerator + agent + workflow +} + +model Instance { + id String @id @default(cuid()) + name String @unique @db.VarChar(255) + connectionStatus InstanceConnectionStatus @default(open) + ownerJid String? @db.VarChar(100) + profileName String? @db.VarChar(100) + profilePicUrl String? @db.VarChar(500) + integration String? @db.VarChar(100) + number String? @db.VarChar(100) + businessId String? @db.VarChar(100) + token String? @db.VarChar(255) + clientName String? @db.VarChar(100) + disconnectionReasonCode Int? @db.Integer + disconnectionObject Json? @db.JsonB + disconnectionAt DateTime? @db.Timestamp + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Chat Chat[] + Contact Contact[] + Message Message[] + Webhook Webhook? + Chatwoot Chatwoot? + Label Label[] + Proxy Proxy? + Setting Setting? + Rabbitmq Rabbitmq? + Nats Nats? + Sqs Sqs? + Kafka Kafka? + Websocket Websocket? + Typebot Typebot[] + Session Session? + MessageUpdate MessageUpdate[] + TypebotSetting TypebotSetting? + Media Media[] + OpenaiCreds OpenaiCreds[] + OpenaiBot OpenaiBot[] + OpenaiSetting OpenaiSetting? + Template Template[] + Dify Dify[] + DifySetting DifySetting? + IntegrationSession IntegrationSession[] + EvolutionBot EvolutionBot[] + EvolutionBotSetting EvolutionBotSetting? + Flowise Flowise[] + FlowiseSetting FlowiseSetting? + Pusher Pusher? + N8n N8n[] + N8nSetting N8nSetting[] + Evoai Evoai[] + EvoaiSetting EvoaiSetting? +} + +model Session { + id String @id @default(cuid()) + sessionId String @unique + creds String? @db.Text + createdAt DateTime @default(now()) @db.Timestamp + Instance Instance @relation(fields: [sessionId], references: [id], onDelete: Cascade) +} + +model Chat { + id String @id @default(cuid()) + remoteJid String @db.VarChar(100) + name String? @db.VarChar(100) + labels Json? @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + unreadMessages Int @default(0) + + @@index([instanceId]) + @@index([remoteJid]) +} + +model Contact { + id String @id @default(cuid()) + remoteJid String @db.VarChar(100) + pushName String? @db.VarChar(100) + profilePicUrl String? @db.VarChar(500) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + + @@unique([remoteJid, instanceId]) + @@index([remoteJid]) + @@index([instanceId]) +} + +model Message { + id String @id @default(cuid()) + key Json @db.JsonB + pushName String? @db.VarChar(100) + participant String? @db.VarChar(100) + messageType String @db.VarChar(100) + message Json @db.JsonB + contextInfo Json? @db.JsonB + source DeviceMessage + messageTimestamp Int @db.Integer + chatwootMessageId Int? @db.Integer + chatwootInboxId Int? @db.Integer + chatwootConversationId Int? @db.Integer + chatwootContactInboxSourceId String? @db.VarChar(100) + chatwootIsRead Boolean? @db.Boolean + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + MessageUpdate MessageUpdate[] + Media Media? + webhookUrl String? @db.VarChar(500) + status String? @db.VarChar(30) + + sessionId String? + session IntegrationSession? @relation(fields: [sessionId], references: [id]) + + @@index([instanceId]) +} + +model MessageUpdate { + id String @id @default(cuid()) + keyId String @db.VarChar(100) + remoteJid String @db.VarChar(100) + fromMe Boolean @db.Boolean + participant String? @db.VarChar(100) + pollUpdates Json? @db.JsonB + status String @db.VarChar(30) + Message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + messageId String + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + + @@index([instanceId]) + @@index([messageId]) +} + +model Webhook { + id String @id @default(cuid()) + url String @db.VarChar(500) + headers Json? @db.JsonB + enabled Boolean? @default(true) @db.Boolean + events Json? @db.JsonB + webhookByEvents Boolean? @default(false) @db.Boolean + webhookBase64 Boolean? @default(false) @db.Boolean + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique + + @@index([instanceId]) +} + +model Chatwoot { + id String @id @default(cuid()) + enabled Boolean? @default(true) @db.Boolean + accountId String? @db.VarChar(100) + token String? @db.VarChar(100) + url String? @db.VarChar(500) + nameInbox String? @db.VarChar(100) + signMsg Boolean? @default(false) @db.Boolean + signDelimiter String? @db.VarChar(100) + number String? @db.VarChar(100) + reopenConversation Boolean? @default(false) @db.Boolean + conversationPending Boolean? @default(false) @db.Boolean + mergeBrazilContacts Boolean? @default(false) @db.Boolean + importContacts Boolean? @default(false) @db.Boolean + importMessages Boolean? @default(false) @db.Boolean + daysLimitImportMessages Int? @db.Integer + organization String? @db.VarChar(100) + logo String? @db.VarChar(500) + ignoreJids Json? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Label { + id String @id @default(cuid()) + labelId String? @db.VarChar(100) + name String @db.VarChar(100) + color String @db.VarChar(100) + predefinedId String? @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + + @@unique([labelId, instanceId]) +} + +model Proxy { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + host String @db.VarChar(100) + port String @db.VarChar(100) + protocol String @db.VarChar(100) + username String @db.VarChar(100) + password String @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Setting { + id String @id @default(cuid()) + rejectCall Boolean @default(false) @db.Boolean + msgCall String? @db.VarChar(100) + groupsIgnore Boolean @default(false) @db.Boolean + alwaysOnline Boolean @default(false) @db.Boolean + readMessages Boolean @default(false) @db.Boolean + readStatus Boolean @default(false) @db.Boolean + syncFullHistory Boolean @default(false) @db.Boolean + wavoipToken String? @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique + + @@index([instanceId]) +} + +model Rabbitmq { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Nats { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Sqs { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Kafka { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Websocket { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Pusher { + id String @id @default(cuid()) + enabled Boolean @default(false) @db.Boolean + appId String @db.VarChar(100) + key String @db.VarChar(100) + secret String @db.VarChar(100) + cluster String @db.VarChar(100) + useTLS Boolean @default(false) @db.Boolean + events Json @db.JsonB + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Typebot { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + url String @db.VarChar(500) + typebot String @db.VarChar(100) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime? @updatedAt @db.Timestamp + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + TypebotSetting TypebotSetting[] +} + +model TypebotSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + typebotIdFallback String? @db.VarChar(100) + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Typebot? @relation(fields: [typebotIdFallback], references: [id]) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Media { + id String @id @default(cuid()) + fileName String @db.VarChar(500) + type String @db.VarChar(100) + mimetype String @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Date + Message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + messageId String @unique + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String +} + +model OpenaiCreds { + id String @id @default(cuid()) + name String? @unique @db.VarChar(255) + apiKey String? @unique @db.VarChar(255) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + OpenaiAssistant OpenaiBot[] + OpenaiSetting OpenaiSetting? +} + +model OpenaiBot { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + botType OpenaiBotType + assistantId String? @db.VarChar(255) + functionUrl String? @db.VarChar(500) + model String? @db.VarChar(100) + systemMessages Json? @db.JsonB + assistantMessages Json? @db.JsonB + userMessages Json? @db.JsonB + maxTokens Int? @db.Integer + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + ignoreJids Json? + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + OpenaiCreds OpenaiCreds @relation(fields: [openaiCredsId], references: [id], onDelete: Cascade) + openaiCredsId String + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + OpenaiSetting OpenaiSetting[] +} + +model IntegrationSession { + id String @id @default(cuid()) + sessionId String @db.VarChar(255) + remoteJid String @db.VarChar(100) + pushName String? + status SessionStatus + awaitUser Boolean @default(false) @db.Boolean + context Json? + type String? @db.VarChar(100) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Message Message[] + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + parameters Json? @db.JsonB + + botId String? +} + +model OpenaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + speechToText Boolean? @default(false) @db.Boolean + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + OpenaiCreds OpenaiCreds? @relation(fields: [openaiCredsId], references: [id]) + openaiCredsId String @unique + Fallback OpenaiBot? @relation(fields: [openaiIdFallback], references: [id]) + openaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Template { + id String @id @default(cuid()) + templateId String @unique @db.VarChar(255) + name String @unique @db.VarChar(255) + template Json @db.JsonB + webhookUrl String? @db.VarChar(500) + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String +} + +model Dify { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + botType DifyBotType + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + DifySetting DifySetting[] +} + +model DifySetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Dify? @relation(fields: [difyIdFallback], references: [id]) + difyIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model EvolutionBot { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvolutionBotSetting EvolutionBotSetting[] +} + +model EvolutionBotSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback EvolutionBot? @relation(fields: [botIdFallback], references: [id]) + botIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Flowise { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + apiUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + FlowiseSetting FlowiseSetting[] +} + +model FlowiseSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Flowise? @relation(fields: [flowiseIdFallback], references: [id]) + flowiseIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model IsOnWhatsapp { + id String @id @default(cuid()) + remoteJid String @unique @db.VarChar(100) + jidOptions String + lid String? @db.VarChar(100) + createdAt DateTime @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp +} + +model N8n { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + webhookUrl String? @db.VarChar(255) + basicAuthUser String? @db.VarChar(255) + basicAuthPass String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + N8nSetting N8nSetting[] +} + +model N8nSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback N8n? @relation(fields: [n8nIdFallback], references: [id]) + n8nIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} + +model Evoai { + id String @id @default(cuid()) + enabled Boolean @default(true) @db.Boolean + description String? @db.VarChar(255) + agentUrl String? @db.VarChar(255) + apiKey String? @db.VarChar(255) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + triggerType TriggerType? + triggerOperator TriggerOperator? + triggerValue String? + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String + EvoaiSetting EvoaiSetting[] +} + +model EvoaiSetting { + id String @id @default(cuid()) + expire Int? @default(0) @db.Integer + keywordFinish String? @db.VarChar(100) + delayMessage Int? @db.Integer + unknownMessage String? @db.VarChar(100) + listeningFromMe Boolean? @default(false) @db.Boolean + stopBotFromMe Boolean? @default(false) @db.Boolean + keepOpen Boolean? @default(false) @db.Boolean + debounceTime Int? @db.Integer + ignoreJids Json? + splitMessages Boolean? @default(false) @db.Boolean + timePerChar Int? @default(50) @db.Integer + createdAt DateTime? @default(now()) @db.Timestamp + updatedAt DateTime @updatedAt @db.Timestamp + Fallback Evoai? @relation(fields: [evoaiIdFallback], references: [id]) + evoaiIdFallback String? @db.VarChar(100) + Instance Instance @relation(fields: [instanceId], references: [id], onDelete: Cascade) + instanceId String @unique +} diff --git a/prometheus.yml.example b/prometheus.yml.example new file mode 100644 index 000000000..bcb3b332d --- /dev/null +++ b/prometheus.yml.example @@ -0,0 +1,76 @@ +# Prometheus configuration example for Evolution API +# Copy this file to prometheus.yml and adjust the settings + +global: + scrape_interval: 15s + evaluation_interval: 15s + +rule_files: + # - "first_rules.yml" + # - "second_rules.yml" + +scrape_configs: + # Evolution API metrics + - job_name: 'evolution-api' + static_configs: + - targets: ['localhost:8080'] # Adjust to your Evolution API URL + + # Metrics endpoint path + metrics_path: '/metrics' + + # Scrape interval for this job + scrape_interval: 30s + + # Basic authentication (if METRICS_AUTH_REQUIRED=true) + basic_auth: + username: 'prometheus' # Should match METRICS_USER + password: 'secure_random_password_here' # Should match METRICS_PASSWORD + + # Optional: Add custom labels + relabel_configs: + - source_labels: [__address__] + target_label: __param_target + - source_labels: [__param_target] + target_label: instance + - target_label: __address__ + replacement: localhost:8080 # Evolution API address + +# Alerting configuration (optional) +alerting: + alertmanagers: + - static_configs: + - targets: + # - alertmanager:9093 + +# Example alert rules for Evolution API +# Create a file called evolution_alerts.yml with these rules: +# +# groups: +# - name: evolution-api +# rules: +# - alert: EvolutionAPIDown +# expr: up{job="evolution-api"} == 0 +# for: 1m +# labels: +# severity: critical +# annotations: +# summary: "Evolution API is down" +# description: "Evolution API has been down for more than 1 minute." +# +# - alert: EvolutionInstanceDown +# expr: evolution_instance_up == 0 +# for: 2m +# labels: +# severity: warning +# annotations: +# summary: "Evolution instance {{ $labels.instance }} is down" +# description: "Instance {{ $labels.instance }} has been down for more than 2 minutes." +# +# - alert: HighInstanceCount +# expr: evolution_instances_total > 100 +# for: 5m +# labels: +# severity: warning +# annotations: +# summary: "High number of Evolution instances" +# description: "Evolution API is managing {{ $value }} instances." diff --git a/runWithProvider.js b/runWithProvider.js index a82757634..b4f0dabb1 100644 --- a/runWithProvider.js +++ b/runWithProvider.js @@ -1,23 +1,52 @@ const dotenv = require('dotenv'); const { execSync } = require('child_process'); +const { existsSync } = require('fs'); + dotenv.config(); const { DATABASE_PROVIDER } = process.env; -const databaseProviderDefault = DATABASE_PROVIDER ?? "postgresql" +const databaseProviderDefault = DATABASE_PROVIDER ?? 'postgresql'; if (!DATABASE_PROVIDER) { - console.error(`DATABASE_PROVIDER is not set in the .env file, using default: ${databaseProviderDefault}`); - // process.exit(1); + console.warn(`DATABASE_PROVIDER is not set in the .env file, using default: ${databaseProviderDefault}`); +} + +// Função para determinar qual pasta de migrations usar +// Função para determinar qual pasta de migrations usar +function getMigrationsFolder(provider) { + switch (provider) { + case 'psql_bouncer': + return 'postgresql-migrations'; // psql_bouncer usa as migrations do postgresql + default: + return `${provider}-migrations`; + } } -const command = process.argv +const migrationsFolder = getMigrationsFolder(databaseProviderDefault); + +let command = process.argv .slice(2) .join(' ') - .replace(/\DATABASE_PROVIDER/g, databaseProviderDefault); + .replace(/DATABASE_PROVIDER/g, databaseProviderDefault); + +// Substituir referências à pasta de migrations pela pasta correta +const migrationsPattern = new RegExp(`${databaseProviderDefault}-migrations`, 'g'); +command = command.replace(migrationsPattern, migrationsFolder); + +if (command.includes('rmdir') && existsSync('prisma\\migrations')) { + try { + execSync('rmdir /S /Q prisma\\migrations', { stdio: 'inherit' }); + } catch (error) { + console.error(`Error removing directory: prisma\\migrations`); + process.exit(1); + } +} else if (command.includes('rmdir')) { + console.warn(`Directory 'prisma\\migrations' does not exist, skipping removal.`); +} try { execSync(command, { stdio: 'inherit' }); } catch (error) { console.error(`Error executing command: ${command}`); process.exit(1); -} +} \ No newline at end of file diff --git a/src/api/controllers/business.controller.ts b/src/api/controllers/business.controller.ts new file mode 100644 index 000000000..3c7f166cc --- /dev/null +++ b/src/api/controllers/business.controller.ts @@ -0,0 +1,15 @@ +import { getCatalogDto, getCollectionsDto } from '@api/dto/business.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; + +export class BusinessController { + constructor(private readonly waMonitor: WAMonitoringService) {} + + public async fetchCatalog({ instanceName }: InstanceDto, data: getCatalogDto) { + return await this.waMonitor.waInstances[instanceName].fetchCatalog(instanceName, data); + } + + public async fetchCollections({ instanceName }: InstanceDto, data: getCollectionsDto) { + return await this.waMonitor.waInstances[instanceName].fetchCollections(instanceName, data); + } +} diff --git a/src/api/controllers/chat.controller.ts b/src/api/controllers/chat.controller.ts index 207d8ba59..22e90b9fa 100644 --- a/src/api/controllers/chat.controller.ts +++ b/src/api/controllers/chat.controller.ts @@ -70,6 +70,10 @@ export class ChatController { return await this.waMonitor.waInstances[instanceName].fetchChats(query); } + public async findChatByRemoteJid({ instanceName }: InstanceDto, remoteJid: string) { + return await this.waMonitor.waInstances[instanceName].findChatByRemoteJid(remoteJid); + } + public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) { return await this.waMonitor.waInstances[instanceName].sendPresence(data); } diff --git a/src/api/controllers/instance.controller.ts b/src/api/controllers/instance.controller.ts index f68379e89..6a6910688 100644 --- a/src/api/controllers/instance.controller.ts +++ b/src/api/controllers/instance.controller.ts @@ -63,6 +63,9 @@ export class InstanceController { instanceId, integration: instanceData.integration, instanceName: instanceData.instanceName, + ownerJid: instanceData.ownerJid, + profileName: instanceData.profileName, + profilePicUrl: instanceData.profilePicUrl, hash, number: instanceData.number, businessId: instanceData.businessId, @@ -89,6 +92,15 @@ export class InstanceController { instanceId: instanceId, }); + const instanceDto: InstanceDto = { + instanceName: instance.instanceName, + instanceId: instance.instanceId, + connectionStatus: + typeof instance.connectionStatus === 'string' + ? instance.connectionStatus + : instance.connectionStatus?.state || 'unknown', + }; + if (instanceData.proxyHost && instanceData.proxyPort && instanceData.proxyProtocol) { const testProxy = await this.proxyService.testProxy({ host: instanceData.proxyHost, @@ -100,8 +112,7 @@ export class InstanceController { if (!testProxy) { throw new BadRequestException('Invalid proxy'); } - - await this.proxyService.createProxy(instance, { + await this.proxyService.createProxy(instanceDto, { enabled: true, host: instanceData.proxyHost, port: instanceData.proxyPort, @@ -119,9 +130,10 @@ export class InstanceController { readMessages: instanceData.readMessages === true, readStatus: instanceData.readStatus === true, syncFullHistory: instanceData.syncFullHistory === true, + wavoipToken: instanceData.wavoipToken || '', }; - await this.settingsService.create(instance, settings); + await this.settingsService.create(instanceDto, settings); let webhookWaBusiness = null, accessTokenWaBusiness = ''; @@ -151,7 +163,10 @@ export class InstanceController { integration: instanceData.integration, webhookWaBusiness, accessTokenWaBusiness, - status: instance.connectionStatus.state, + status: + typeof instance.connectionStatus === 'string' + ? instance.connectionStatus + : instance.connectionStatus?.state || 'unknown', }, hash, webhook: { @@ -166,6 +181,9 @@ export class InstanceController { rabbitmq: { enabled: instanceData?.rabbitmq?.enabled, }, + nats: { + enabled: instanceData?.nats?.enabled, + }, sqs: { enabled: instanceData?.sqs?.enabled, }, @@ -210,7 +228,7 @@ export class InstanceController { const urlServer = this.configService.get('SERVER').URL; try { - this.chatwootService.create(instance, { + this.chatwootService.create(instanceDto, { enabled: true, accountId: instanceData.chatwootAccountId, token: instanceData.chatwootToken, @@ -239,7 +257,10 @@ export class InstanceController { integration: instanceData.integration, webhookWaBusiness, accessTokenWaBusiness, - status: instance.connectionStatus.state, + status: + typeof instance.connectionStatus === 'string' + ? instance.connectionStatus + : instance.connectionStatus?.state || 'unknown', }, hash, webhook: { @@ -254,6 +275,9 @@ export class InstanceController { rabbitmq: { enabled: instanceData?.rabbitmq?.enabled, }, + nats: { + enabled: instanceData?.nats?.enabled, + }, sqs: { enabled: instanceData?.sqs?.enabled, }, @@ -328,20 +352,38 @@ export class InstanceController { throw new BadRequestException('The "' + instanceName + '" instance does not exist'); } - if (state == 'close') { + if (state === 'close') { throw new BadRequestException('The "' + instanceName + '" instance is not connected'); - } else if (state == 'open') { + } + this.logger.info(`Restarting instance: ${instanceName}`); + + if (typeof instance.restart === 'function') { + await instance.restart(); + // Wait a bit for the reconnection to be established + await new Promise((r) => setTimeout(r, 2000)); + return { + instance: { + instanceName: instanceName, + status: instance.connectionStatus?.state || 'connecting', + }, + }; + } + + // Fallback for Baileys (uses different mechanism) + if (state === 'open' || state === 'connecting') { if (this.configService.get('CHATWOOT').ENABLED) instance.clearCacheChatwoot(); - this.logger.info('restarting instance' + instanceName); - instance.client?.ws?.close(); - instance.client?.end(new Error('restart')); - return await this.connectToWhatsapp({ instanceName }); - } else if (state == 'connecting') { instance.client?.ws?.close(); instance.client?.end(new Error('restart')); return await this.connectToWhatsapp({ instanceName }); } + + return { + instance: { + instanceName: instanceName, + status: state, + }, + }; } catch (error) { this.logger.error(error); return { error: true, message: error.toString() }; @@ -399,7 +441,7 @@ export class InstanceController { } try { - this.waMonitor.waInstances[instanceName]?.logoutInstance(); + await this.waMonitor.waInstances[instanceName]?.logoutInstance(); return { status: 'SUCCESS', error: false, response: { message: 'Instance logged out' } }; } catch (error) { @@ -409,15 +451,11 @@ export class InstanceController { public async deleteInstance({ instanceName }: InstanceDto) { const { instance } = await this.connectionState({ instanceName }); - - if (instance.state === 'open') { - throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected'); - } try { const waInstances = this.waMonitor.waInstances[instanceName]; if (this.configService.get('CHATWOOT').ENABLED) waInstances?.clearCacheChatwoot(); - if (instance.state === 'connecting') { + if (instance.state === 'connecting' || instance.state === 'open') { await this.logout({ instanceName }); } diff --git a/src/api/controllers/proxy.controller.ts b/src/api/controllers/proxy.controller.ts index 3fcde3bb9..b6e7d153a 100644 --- a/src/api/controllers/proxy.controller.ts +++ b/src/api/controllers/proxy.controller.ts @@ -10,7 +10,10 @@ import axios from 'axios'; const logger = new Logger('ProxyController'); export class ProxyController { - constructor(private readonly proxyService: ProxyService, private readonly waMonitor: WAMonitoringService) {} + constructor( + private readonly proxyService: ProxyService, + private readonly waMonitor: WAMonitoringService, + ) {} public async createProxy(instance: InstanceDto, data: ProxyDto) { if (!this.waMonitor.waInstances[instance.instanceName]) { @@ -50,15 +53,21 @@ export class ProxyController { httpsAgent: makeProxyAgent(proxy), }); - return response?.data !== serverIp?.data; + const result = response?.data !== serverIp?.data; + if (result) { + logger.info('testProxy: proxy connection successful'); + } else { + logger.warn("testProxy: proxy connection doesn't change the origin IP"); + } + + return result; } catch (error) { - if (axios.isAxiosError(error) && error.response?.data) { - logger.error('testProxy error: ' + error.response.data); - } else if (axios.isAxiosError(error)) { - logger.error('testProxy error: '); + if (axios.isAxiosError(error)) { + logger.error('testProxy error: axios error: ' + error.message); } else { - logger.error('testProxy error: '); + logger.error('testProxy error: unexpected error: ' + error); } + return false; } } diff --git a/src/api/controllers/sendMessage.controller.ts b/src/api/controllers/sendMessage.controller.ts index ac40562c6..64aa1c846 100644 --- a/src/api/controllers/sendMessage.controller.ts +++ b/src/api/controllers/sendMessage.controller.ts @@ -17,6 +17,16 @@ import { import { WAMonitoringService } from '@api/services/monitor.service'; import { BadRequestException } from '@exceptions'; import { isBase64, isURL } from 'class-validator'; +import emojiRegex from 'emoji-regex'; + +const regex = emojiRegex(); + +function isEmoji(str: string) { + if (str === '') return true; + + const match = str.match(regex); + return match?.length === 1 && match[0] === str; +} export class SendMessageController { constructor(private readonly waMonitor: WAMonitoringService) {} @@ -81,8 +91,8 @@ export class SendMessageController { } public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) { - if (!data.reaction.match(/[^()\w\sà-ú"-+]+/)) { - throw new BadRequestException('"reaction" must be an emoji'); + if (!isEmoji(data.reaction)) { + throw new BadRequestException('Reaction must be a single emoji or empty string'); } return await this.waMonitor.waInstances[instanceName].reactionMessage(data); } diff --git a/src/api/controllers/template.controller.ts b/src/api/controllers/template.controller.ts index d9b620457..52f8182b3 100644 --- a/src/api/controllers/template.controller.ts +++ b/src/api/controllers/template.controller.ts @@ -12,4 +12,15 @@ export class TemplateController { public async findTemplate(instance: InstanceDto) { return this.templateService.find(instance); } + + public async editTemplate( + instance: InstanceDto, + data: { templateId: string; category?: string; components?: any; allowCategoryChange?: boolean; ttl?: number }, + ) { + return this.templateService.edit(instance, data); + } + + public async deleteTemplate(instance: InstanceDto, data: { name: string; hsmId?: string }) { + return this.templateService.delete(instance, data); + } } diff --git a/src/api/dto/business.dto.ts b/src/api/dto/business.dto.ts new file mode 100644 index 000000000..d29b3cf97 --- /dev/null +++ b/src/api/dto/business.dto.ts @@ -0,0 +1,14 @@ +export class NumberDto { + number: string; +} + +export class getCatalogDto { + number?: string; + limit?: number; + cursor?: string; +} + +export class getCollectionsDto { + number?: string; + limit?: number; +} diff --git a/src/api/dto/chat.dto.ts b/src/api/dto/chat.dto.ts index 00da7fdd4..b11f32b05 100644 --- a/src/api/dto/chat.dto.ts +++ b/src/api/dto/chat.dto.ts @@ -13,6 +13,7 @@ export class OnWhatsAppDto { public readonly exists: boolean, public readonly number: string, public readonly name?: string, + public readonly lid?: string, ) {} } diff --git a/src/api/dto/instance.dto.ts b/src/api/dto/instance.dto.ts index 3bb48b5e3..85c5b69c3 100644 --- a/src/api/dto/instance.dto.ts +++ b/src/api/dto/instance.dto.ts @@ -1,4 +1,5 @@ import { IntegrationDto } from '@api/integrations/integration.dto'; +import { JsonValue } from '@prisma/client/runtime/library'; import { WAPresence } from 'baileys'; export class InstanceDto extends IntegrationDto { @@ -10,6 +11,10 @@ export class InstanceDto extends IntegrationDto { integration?: string; token?: string; status?: string; + ownerJid?: string; + connectionStatus?: string; + profileName?: string; + profilePicUrl?: string; // settings rejectCall?: boolean; msgCall?: string; @@ -18,12 +23,35 @@ export class InstanceDto extends IntegrationDto { readMessages?: boolean; readStatus?: boolean; syncFullHistory?: boolean; + wavoipToken?: string; // proxy proxyHost?: string; proxyPort?: string; proxyProtocol?: string; proxyUsername?: string; proxyPassword?: string; + webhook?: { + enabled?: boolean; + events?: string[]; + headers?: JsonValue; + url?: string; + byEvents?: boolean; + base64?: boolean; + }; + chatwootAccountId?: string; + chatwootConversationPending?: boolean; + chatwootAutoCreate?: boolean; + chatwootDaysLimitImportMessages?: number; + chatwootImportContacts?: boolean; + chatwootImportMessages?: boolean; + chatwootLogo?: string; + chatwootMergeBrazilContacts?: boolean; + chatwootNameInbox?: string; + chatwootOrganization?: string; + chatwootReopenConversation?: boolean; + chatwootSignMsg?: boolean; + chatwootToken?: string; + chatwootUrl?: string; } export class SetPresenceDto { diff --git a/src/api/dto/sendMessage.dto.ts b/src/api/dto/sendMessage.dto.ts index 1c9b11545..ba9ecf527 100644 --- a/src/api/dto/sendMessage.dto.ts +++ b/src/api/dto/sendMessage.dto.ts @@ -44,6 +44,7 @@ export class Metadata { mentionsEveryOne?: boolean; mentioned?: string[]; encoding?: boolean; + notConvertSticker?: boolean; } export class SendTextDto extends Metadata { diff --git a/src/api/dto/settings.dto.ts b/src/api/dto/settings.dto.ts index 09302a42e..4779ef499 100644 --- a/src/api/dto/settings.dto.ts +++ b/src/api/dto/settings.dto.ts @@ -6,4 +6,5 @@ export class SettingsDto { readMessages?: boolean; readStatus?: boolean; syncFullHistory?: boolean; + wavoipToken?: string; } diff --git a/src/api/dto/template.dto.ts b/src/api/dto/template.dto.ts index cec7d6c53..9b0339e88 100644 --- a/src/api/dto/template.dto.ts +++ b/src/api/dto/template.dto.ts @@ -6,3 +6,16 @@ export class TemplateDto { components: any; webhookUrl?: string; } + +export class TemplateEditDto { + templateId: string; + category?: 'AUTHENTICATION' | 'MARKETING' | 'UTILITY'; + allowCategoryChange?: boolean; + ttl?: number; + components?: any; +} + +export class TemplateDeleteDto { + name: string; + hsmId?: string; +} diff --git a/src/api/integrations/channel/channel.controller.ts b/src/api/integrations/channel/channel.controller.ts index 3304d987d..051be7262 100644 --- a/src/api/integrations/channel/channel.controller.ts +++ b/src/api/integrations/channel/channel.controller.ts @@ -75,8 +75,6 @@ export class ChannelController { data.prismaRepository, data.cache, data.chatwootCache, - data.baileysCache, - data.providerFiles, ); } diff --git a/src/api/integrations/channel/channel.router.ts b/src/api/integrations/channel/channel.router.ts index c5bce859b..5d878471f 100644 --- a/src/api/integrations/channel/channel.router.ts +++ b/src/api/integrations/channel/channel.router.ts @@ -2,14 +2,16 @@ import { Router } from 'express'; import { EvolutionRouter } from './evolution/evolution.router'; import { MetaRouter } from './meta/meta.router'; +import { BaileysRouter } from './whatsapp/baileys.router'; export class ChannelRouter { public readonly router: Router; - constructor(configService: any) { + constructor(configService: any, ...guards: any[]) { this.router = Router(); this.router.use('/', new EvolutionRouter(configService).router); this.router.use('/', new MetaRouter(configService).router); + this.router.use('/baileys', new BaileysRouter(...guards).router); } } diff --git a/src/api/integrations/channel/evolution/evolution.channel.service.ts b/src/api/integrations/channel/evolution/evolution.channel.service.ts index 10b28a4db..87bea08e6 100644 --- a/src/api/integrations/channel/evolution/evolution.channel.service.ts +++ b/src/api/integrations/channel/evolution/evolution.channel.service.ts @@ -1,16 +1,28 @@ -import { MediaMessage, Options, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto'; -import { ProviderFiles } from '@api/provider/sessions'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { + MediaMessage, + Options, + SendAudioDto, + SendButtonsDto, + SendMediaDto, + SendTextDto, +} from '@api/dto/sendMessage.dto'; +import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; import { PrismaRepository } from '@api/repository/repository.service'; import { chatbotController } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; import { ChannelStartupService } from '@api/services/channel.service'; import { Events, wa } from '@api/types/wa.types'; -import { Chatwoot, ConfigService, Openai } from '@config/env.config'; +import { AudioConverter, Chatwoot, ConfigService, Openai, S3 } from '@config/env.config'; import { BadRequestException, InternalServerErrorException } from '@exceptions'; -import { status } from '@utils/renderStatus'; -import { isURL } from 'class-validator'; +import { createJid } from '@utils/createJid'; +import { sendTelemetry } from '@utils/sendTelemetry'; +import axios from 'axios'; +import { isBase64, isURL } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; -import mime from 'mime'; +import FormData from 'form-data'; +import mimeTypes from 'mime-types'; +import { join } from 'path'; import { v4 } from 'uuid'; export class EvolutionStartupService extends ChannelStartupService { @@ -20,8 +32,6 @@ export class EvolutionStartupService extends ChannelStartupService { public readonly prismaRepository: PrismaRepository, public readonly cache: CacheService, public readonly chatwootCache: CacheService, - public readonly baileysCache: CacheService, - private readonly providerFiles: ProviderFiles, ) { super(configService, eventEmitter, prismaRepository, chatwootCache); @@ -56,8 +66,34 @@ export class EvolutionStartupService extends ChannelStartupService { await this.closeClient(); } + public setInstance(instance: InstanceDto) { + this.logger.setInstance(instance.instanceId); + + this.instance.name = instance.instanceName; + this.instance.id = instance.instanceId; + this.instance.integration = instance.integration; + this.instance.number = instance.number; + this.instance.token = instance.token; + this.instance.businessId = instance.businessId; + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + this.chatwootService.eventWhatsapp( + Events.STATUS_INSTANCE, + { + instanceName: this.instance.name, + instanceId: this.instance.id, + integration: instance.integration, + }, + { + instance: this.instance.name, + status: 'created', + }, + ); + } + } + public async profilePicture(number: string) { - const jid = this.createJid(number); + const jid = createJid(number); return { wuid: jid, @@ -78,11 +114,12 @@ export class EvolutionStartupService extends ChannelStartupService { } public async connectToWhatsapp(data?: any): Promise { - if (!data) return; - - try { + if (!data) { this.loadChatwoot(); + return; + } + try { this.eventHandler(data); } catch (error) { this.logger.error(error); @@ -99,6 +136,7 @@ export class EvolutionStartupService extends ChannelStartupService { id: received.key.id || v4(), remoteJid: received.key.remoteJid, fromMe: received.key.fromMe, + profilePicUrl: received.profilePicUrl, }; messageRaw = { key, @@ -110,7 +148,9 @@ export class EvolutionStartupService extends ChannelStartupService { instanceId: this.instanceId, }; - if (this.configService.get('OPENAI').ENABLED) { + const isAudio = received?.message?.audioMessage; + + if (this.configService.get('OPENAI').ENABLED && isAudio) { const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ where: { instanceId: this.instanceId, @@ -126,16 +166,14 @@ export class EvolutionStartupService extends ChannelStartupService { openAiDefaultSettings.speechToText && received?.message?.audioMessage ) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText(received, this)}`; } } this.logger.log(messageRaw); + sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`); + this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); await chatbotController.emit({ @@ -165,7 +203,7 @@ export class EvolutionStartupService extends ChannelStartupService { await this.updateContact({ remoteJid: messageRaw.key.remoteJid, - pushName: messageRaw.key.fromMe ? '' : messageRaw.key.fromMe == null ? '' : received.pushName, + pushName: messageRaw.pushName, profilePicUrl: received.profilePicUrl, }); } @@ -175,47 +213,47 @@ export class EvolutionStartupService extends ChannelStartupService { } private async updateContact(data: { remoteJid: string; pushName?: string; profilePicUrl?: string }) { - const contact = await this.prismaRepository.contact.findFirst({ - where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, - }); + const contactRaw: any = { + remoteJid: data.remoteJid, + pushName: data?.pushName, + instanceId: this.instanceId, + profilePicUrl: data?.profilePicUrl, + }; - if (contact) { - const contactRaw: any = { + const existingContact = await this.prismaRepository.contact.findFirst({ + where: { remoteJid: data.remoteJid, - pushName: data?.pushName, instanceId: this.instanceId, - profilePicUrl: data?.profilePicUrl, - }; - - this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); - - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { - await this.chatwootService.eventWhatsapp( - Events.CONTACTS_UPDATE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - contactRaw, - ); - } + }, + }); + if (existingContact) { await this.prismaRepository.contact.updateMany({ - where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, + where: { + remoteJid: data.remoteJid, + instanceId: this.instanceId, + }, + data: contactRaw, + }); + } else { + await this.prismaRepository.contact.create({ data: contactRaw, }); - return; } - const contactRaw: any = { - remoteJid: data.remoteJid, - pushName: data?.pushName, - instanceId: this.instanceId, - profilePicUrl: data?.profilePicUrl, - }; - this.sendDataWebhook(Events.CONTACTS_UPSERT, contactRaw); - await this.prismaRepository.contact.create({ - data: contactRaw, - }); + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { + await this.chatwootService.eventWhatsapp( + Events.CONTACTS_UPDATE, + { + instanceName: this.instance.name, + instanceId: this.instanceId, + integration: this.instance.integration, + }, + contactRaw, + ); + } const chat = await this.prismaRepository.chat.findFirst({ where: { instanceId: this.instanceId, remoteJid: data.remoteJid }, @@ -247,7 +285,13 @@ export class EvolutionStartupService extends ChannelStartupService { }); } - protected async sendMessageWithTyping(number: string, message: any, options?: Options, isIntegration = false) { + protected async sendMessageWithTyping( + number: string, + message: any, + options?: Options, + file?: any, + isIntegration = false, + ) { try { let quoted: any; let webhookUrl: any; @@ -272,64 +316,194 @@ export class EvolutionStartupService extends ChannelStartupService { webhookUrl = options.webhookUrl; } + let audioFile; + const messageId = v4(); - let messageRaw: any = { - key: { fromMe: true, id: messageId, remoteJid: number }, - messageTimestamp: Math.round(new Date().getTime() / 1000), - webhookUrl, - source: 'unknown', - instanceId: this.instanceId, - status: status[1], - }; + let messageRaw: any; if (message?.mediaType === 'image') { messageRaw = { - ...messageRaw, + key: { fromMe: true, id: messageId, remoteJid: number }, message: { - mediaUrl: message.media, + base64: isBase64(message.media) ? message.media : null, + mediaUrl: isURL(message.media) ? message.media : null, quoted, }, messageType: 'imageMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, }; } else if (message?.mediaType === 'video') { messageRaw = { - ...messageRaw, + key: { fromMe: true, id: messageId, remoteJid: number }, message: { - mediaUrl: message.media, + base64: isBase64(message.media) ? message.media : null, + mediaUrl: isURL(message.media) ? message.media : null, quoted, }, messageType: 'videoMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, }; } else if (message?.mediaType === 'audio') { messageRaw = { - ...messageRaw, + key: { fromMe: true, id: messageId, remoteJid: number }, message: { - mediaUrl: message.media, + base64: isBase64(message.media) ? message.media : null, + mediaUrl: isURL(message.media) ? message.media : null, quoted, }, messageType: 'audioMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + + const buffer = Buffer.from(message.media, 'base64'); + audioFile = { + buffer, + mimetype: 'audio/mp4', + originalname: `${messageId}.mp4`, }; } else if (message?.mediaType === 'document') { messageRaw = { - ...messageRaw, + key: { fromMe: true, id: messageId, remoteJid: number }, message: { - mediaUrl: message.media, + base64: isBase64(message.media) ? message.media : null, + mediaUrl: isURL(message.media) ? message.media : null, quoted, }, messageType: 'documentMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (message.buttonMessage) { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + ...message.buttonMessage, + buttons: message.buttonMessage.buttons, + footer: message.buttonMessage.footer, + body: message.buttonMessage.body, + quoted, + }, + messageType: 'buttonMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (message.listMessage) { + messageRaw = { + key: { fromMe: true, id: messageId, remoteJid: number }, + message: { + ...message.listMessage, + quoted, + }, + messageType: 'listMessage', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, }; } else { messageRaw = { - ...messageRaw, + key: { fromMe: true, id: messageId, remoteJid: number }, message: { ...message, quoted, }, messageType: 'conversation', + messageTimestamp: Math.round(new Date().getTime() / 1000), + webhookUrl, + source: 'unknown', + instanceId: this.instanceId, + }; + } + + if (messageRaw.message.contextInfo) { + messageRaw.contextInfo = { + ...messageRaw.message.contextInfo, }; } + if (messageRaw.contextInfo?.stanzaId) { + const key: any = { + id: messageRaw.contextInfo.stanzaId, + }; + + const findMessage = await this.prismaRepository.message.findFirst({ + where: { + instanceId: this.instanceId, + key, + }, + }); + + if (findMessage) { + messageRaw.contextInfo.quotedMessage = findMessage.message; + } + } + + const { base64 } = messageRaw.message; + delete messageRaw.message.base64; + + if (base64 || file || audioFile) { + if (this.configService.get('S3').ENABLE) { + try { + // Verificação adicional para garantir que há conteúdo de mídia real + const hasRealMedia = this.hasValidMediaContent(messageRaw); + + if (!hasRealMedia) { + this.logger.warn('Message detected as media but contains no valid media content'); + } else { + const fileBuffer = audioFile?.buffer || file?.buffer; + const buffer = base64 ? Buffer.from(base64, 'base64') : fileBuffer; + + let mediaType: string; + let mimetype = audioFile?.mimetype || file.mimetype; + + if (messageRaw.messageType === 'documentMessage') { + mediaType = 'document'; + mimetype = !mimetype ? 'application/pdf' : mimetype; + } else if (messageRaw.messageType === 'imageMessage') { + mediaType = 'image'; + mimetype = !mimetype ? 'image/png' : mimetype; + } else if (messageRaw.messageType === 'audioMessage') { + mediaType = 'audio'; + mimetype = !mimetype ? 'audio/mp4' : mimetype; + } else if (messageRaw.messageType === 'videoMessage') { + mediaType = 'video'; + mimetype = !mimetype ? 'video/mp4' : mimetype; + } + + const fileName = `${messageRaw.key.id}.${mimetype.split('/')[1]}`; + + const size = buffer.byteLength; + + const fullName = join(`${this.instance.id}`, messageRaw.key.remoteJid, mediaType, fileName); + + await s3Service.uploadFile(fullName, buffer, size, { + 'Content-Type': mimetype, + }); + + const mediaUrl = await s3Service.getObjectUrl(fullName); + + messageRaw.message.mediaUrl = mediaUrl; + } + } catch (error) { + this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); + } + } + } + this.logger.log(messageRaw); this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); @@ -375,6 +549,7 @@ export class EvolutionStartupService extends ChannelStartupService { mentionsEveryOne: data?.mentionsEveryOne, mentioned: data?.mentioned, }, + null, isIntegration, ); return res; @@ -396,7 +571,7 @@ export class EvolutionStartupService extends ChannelStartupService { mediaMessage.fileName = 'video.mp4'; } - let mimetype: string; + let mimetype: string | false; const prepareMedia: any = { caption: mediaMessage?.caption, @@ -407,9 +582,9 @@ export class EvolutionStartupService extends ChannelStartupService { }; if (isURL(mediaMessage.media)) { - mimetype = mime.getType(mediaMessage.media); + mimetype = mimeTypes.lookup(mediaMessage.media); } else { - mimetype = mime.getType(mediaMessage.fileName); + mimetype = mimeTypes.lookup(mediaMessage.fileName); } prepareMedia.mimetype = mimetype; @@ -439,33 +614,79 @@ export class EvolutionStartupService extends ChannelStartupService { mentionsEveryOne: data?.mentionsEveryOne, mentioned: data?.mentioned, }, + file, isIntegration, ); return mediaSent; } - public async processAudio(audio: string, number: string) { + public async processAudio(audio: string, number: string, file: any) { number = number.replace(/\D/g, ''); const hash = `${number}-${new Date().getTime()}`; - let mimetype: string; + const audioConverterConfig = this.configService.get('AUDIO_CONVERTER'); + if (audioConverterConfig.API_URL) { + try { + this.logger.verbose('Using audio converter API'); + const formData = new FormData(); - const prepareMedia: any = { - fileName: `${hash}.mp4`, - mediaType: 'audio', - media: audio, - }; + if (file) { + formData.append('file', file.buffer, { + filename: file.originalname, + contentType: file.mimetype, + }); + } else if (isURL(audio)) { + formData.append('url', audio); + } else { + formData.append('base64', audio); + } - if (isURL(audio)) { - mimetype = mime.getType(audio); + formData.append('format', 'mp4'); + + const response = await axios.post(audioConverterConfig.API_URL, formData, { + headers: { + ...formData.getHeaders(), + apikey: audioConverterConfig.API_KEY, + }, + }); + + if (!response?.data?.audio) { + throw new InternalServerErrorException('Failed to convert audio'); + } + + const prepareMedia: any = { + fileName: `${hash}.mp4`, + mediaType: 'audio', + media: response?.data?.audio, + mimetype: 'audio/mpeg', + }; + + return prepareMedia; + } catch (error) { + this.logger.error(error?.response?.data || error); + throw new InternalServerErrorException(error?.response?.data?.message || error?.toString() || error); + } } else { - mimetype = mime.getType(prepareMedia.fileName); - } + let mimetype: string; + + const prepareMedia: any = { + fileName: `${hash}.mp3`, + mediaType: 'audio', + media: audio, + mimetype: 'audio/mpeg', + }; - prepareMedia.mimetype = mimetype; + if (isURL(audio)) { + mimetype = mimeTypes.lookup(audio).toString(); + } else { + mimetype = mimeTypes.lookup(prepareMedia.fileName).toString(); + } - return prepareMedia; + prepareMedia.mimetype = mimetype; + + return prepareMedia; + } } public async audioWhatsapp(data: SendAudioDto, file?: any, isIntegration = false) { @@ -478,7 +699,7 @@ export class EvolutionStartupService extends ChannelStartupService { throw new Error('File or buffer is undefined.'); } - const message = await this.processAudio(mediaData.audio, data.number); + const message = await this.processAudio(mediaData.audio, data.number, file); const audioSent = await this.sendMessageWithTyping( data.number, @@ -491,14 +712,34 @@ export class EvolutionStartupService extends ChannelStartupService { mentionsEveryOne: data?.mentionsEveryOne, mentioned: data?.mentioned, }, + file, isIntegration, ); return audioSent; } - public async buttonMessage() { - throw new BadRequestException('Method not available on Evolution Channel'); + public async buttonMessage(data: SendButtonsDto, isIntegration = false) { + return await this.sendMessageWithTyping( + data.number, + { + buttonMessage: { + title: data.title, + description: data.description, + footer: data.footer, + buttons: data.buttons, + }, + }, + { + delay: data?.delay, + presence: 'composing', + quoted: data?.quoted, + mentionsEveryOne: data?.mentionsEveryOne, + mentioned: data?.mentioned, + }, + null, + isIntegration, + ); } public async locationMessage() { throw new BadRequestException('Method not available on Evolution Channel'); diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 65c879614..1e4808c15 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -20,15 +20,16 @@ import { chatbotController } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; import { ChannelStartupService } from '@api/services/channel.service'; import { Events, wa } from '@api/types/wa.types'; -import { Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config'; +import { AudioConverter, Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config'; import { BadRequestException, InternalServerErrorException } from '@exceptions'; +import { createJid } from '@utils/createJid'; import { status } from '@utils/renderStatus'; +import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; import { arrayUnique, isURL } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; import FormData from 'form-data'; -import { createReadStream } from 'fs'; -import mime from 'mime'; +import mimeTypes from 'mime-types'; import { join } from 'path'; export class BusinessStartupService extends ChannelStartupService { @@ -70,6 +71,10 @@ export class BusinessStartupService extends ChannelStartupService { await this.closeClient(); } + private isMediaMessage(message: any) { + return message.document || message.image || message.audio || message.video; + } + private async post(message: any, params: string) { try { let urlServer = this.configService.get('WA_BUSINESS').URL; @@ -84,7 +89,7 @@ export class BusinessStartupService extends ChannelStartupService { } public async profilePicture(number: string) { - const jid = this.createJid(number); + const jid = createJid(number); return { wuid: jid, @@ -128,9 +133,7 @@ export class BusinessStartupService extends ChannelStartupService { this.eventHandler(content); - this.phoneNumber = this.createJid( - content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id, - ); + this.phoneNumber = createJid(content.messages ? content.messages[0].from : content.statuses[0]?.recipient_id); } catch (error) { this.logger.error(error); throw new InternalServerErrorException(error?.toString()); @@ -144,11 +147,20 @@ export class BusinessStartupService extends ChannelStartupService { const version = this.configService.get('WA_BUSINESS').VERSION; urlServer = `${urlServer}/${version}/${id}`; const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; + + // Primeiro, obtenha a URL do arquivo let result = await axios.get(urlServer, { headers }); - result = await axios.get(result.data.url, { headers, responseType: 'arraybuffer' }); + + // Depois, baixe o arquivo usando a URL retornada + result = await axios.get(result.data.url, { + headers: { Authorization: `Bearer ${this.token}` }, // Use apenas o token de autorização para download + responseType: 'arraybuffer', + }); + return result.data; } catch (e) { - this.logger.error(e); + this.logger.error(`Error downloading media: ${e}`); + throw e; } } @@ -156,7 +168,23 @@ export class BusinessStartupService extends ChannelStartupService { const message = received.messages[0]; let content: any = message.type + 'Message'; content = { [content]: message[message.type] }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } + return content; + } + + private messageAudioJson(received: any) { + const message = received.messages[0]; + let content: any = { + audioMessage: { + ...message.audio, + ptt: message.audio.voice || false, // Define se é mensagem de voz + }, + }; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } return content; } @@ -189,17 +217,77 @@ export class BusinessStartupService extends ChannelStartupService { } private messageTextJson(received: any) { - let content: any; + // Verificar que received y received.messages existen + if (!received || !received.messages || received.messages.length === 0) { + this.logger.error('Error: received object or messages array is undefined or empty'); + return null; + } + const message = received.messages[0]; + let content: any; + + // Verificar si es un mensaje de tipo sticker, location u otro tipo que no tiene text + if (!message.text) { + // Si no hay texto, manejamos diferente según el tipo de mensaje + if (message.type === 'sticker') { + content = { stickerMessage: {} }; + } else if (message.type === 'location') { + content = { + locationMessage: { + degreesLatitude: message.location?.latitude, + degreesLongitude: message.location?.longitude, + name: message.location?.name, + address: message.location?.address, + }, + }; + } else { + // Para otros tipos de mensajes sin texto, creamos un contenido genérico + this.logger.log(`Mensaje de tipo ${message.type} sin campo text`); + content = { [message.type + 'Message']: message[message.type] || {} }; + } + + // Añadir contexto si existe + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } + + return content; + } + + // Si el mensaje tiene texto, procesamos normalmente + if (!received.metadata || !received.metadata.phone_number_id) { + this.logger.error('Error: metadata or phone_number_id is undefined'); + return null; + } + if (message.from === received.metadata.phone_number_id) { content = { extendedTextMessage: { text: message.text.body }, }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } } else { content = { conversation: message.text.body }; - message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; + if (message.context) { + content = { ...content, contextInfo: { stanzaId: message.context.id } }; + } } + + return content; + } + + private messageLocationJson(received: any) { + const message = received.messages[0]; + let content: any = { + locationMessage: { + degreesLatitude: message.location.latitude, + degreesLongitude: message.location.longitude, + name: message.location?.name, + address: message.location?.address, + }, + }; + message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content; return content; } @@ -227,7 +315,7 @@ export class BusinessStartupService extends ChannelStartupService { } if (!contact.phones[0]?.wa_id) { - contact.phones[0].wa_id = this.createJid(contact.phones[0].phone); + contact.phones[0].wa_id = createJid(contact.phones[0].phone); } result += @@ -280,6 +368,12 @@ export class BusinessStartupService extends ChannelStartupService { case 'template': messageType = 'conversation'; break; + case 'location': + messageType = 'locationMessage'; + break; + case 'sticker': + messageType = 'stickerMessage'; + break; default: messageType = 'conversation'; break; @@ -296,22 +390,36 @@ export class BusinessStartupService extends ChannelStartupService { if (received.contacts) pushName = received.contacts[0].profile.name; if (received.messages) { + const message = received.messages[0]; // Añadir esta línea para definir message + const key = { - id: received.messages[0].id, + id: message.id, remoteJid: this.phoneNumber, - fromMe: received.messages[0].from === received.metadata.phone_number_id, + fromMe: message.from === received.metadata.phone_number_id, }; - if ( - received?.messages[0].document || - received?.messages[0].image || - received?.messages[0].audio || - received?.messages[0].video - ) { + + if (message.type === 'sticker') { + this.logger.log('Procesando mensaje de tipo sticker'); + messageRaw = { + key, + pushName, + message: { + stickerMessage: message.sticker || {}, + }, + messageType: 'stickerMessage', + messageTimestamp: parseInt(message.timestamp) as number, + source: 'unknown', + instanceId: this.instanceId, + }; + } else if (this.isMediaMessage(message)) { + const messageContent = + message.type === 'audio' ? this.messageAudioJson(received) : this.messageMediaJson(received); + messageRaw = { key, pushName, - message: this.messageMediaJson(received), - contextInfo: this.messageMediaJson(received)?.contextInfo, + message: messageContent, + contextInfo: messageContent?.contextInfo, messageType: this.renderMessageType(received.messages[0].type), messageTimestamp: parseInt(received.messages[0].timestamp) as number, source: 'unknown', @@ -322,62 +430,170 @@ export class BusinessStartupService extends ChannelStartupService { try { const message: any = received; - const id = message.messages[0][message.messages[0].type].id; - let urlServer = this.configService.get('WA_BUSINESS').URL; - const version = this.configService.get('WA_BUSINESS').VERSION; - urlServer = `${urlServer}/${version}/${id}`; - const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; - const result = await axios.get(urlServer, { headers }); - - const buffer = await axios.get(result.data.url, { headers, responseType: 'arraybuffer' }); - - const mediaType = message.messages[0].document - ? 'document' - : message.messages[0].image - ? 'image' - : message.messages[0].audio - ? 'audio' - : 'video'; - - const mimetype = result.headers['content-type']; - - const contentDisposition = result.headers['content-disposition']; - let fileName = `${message.messages[0].id}.${mimetype.split('/')[1]}`; - if (contentDisposition) { - const match = contentDisposition.match(/filename="(.+?)"/); - if (match) { - fileName = match[1]; + // Verificação adicional para garantir que há conteúdo de mídia real + const hasRealMedia = this.hasValidMediaContent(messageRaw); + + if (!hasRealMedia) { + this.logger.warn('Message detected as media but contains no valid media content'); + } else { + const id = message.messages[0][message.messages[0].type].id; + let urlServer = this.configService.get('WA_BUSINESS').URL; + const version = this.configService.get('WA_BUSINESS').VERSION; + urlServer = `${urlServer}/${version}/${id}`; + const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; + const result = await axios.get(urlServer, { headers }); + + const buffer = await axios.get(result.data.url, { + headers: { Authorization: `Bearer ${this.token}` }, // Use apenas o token de autorização para download + responseType: 'arraybuffer', + }); + + let mediaType; + + if (message.messages[0].document) { + mediaType = 'document'; + } else if (message.messages[0].image) { + mediaType = 'image'; + } else if (message.messages[0].audio) { + mediaType = 'audio'; + } else { + mediaType = 'video'; } - } - const size = result.headers['content-length'] || buffer.data.byteLength; + if (mediaType == 'video' && !this.configService.get('S3').SAVE_VIDEO) { + this.logger?.info?.('Video upload attempted but is disabled by configuration.'); + return { + success: false, + message: + 'Video upload is currently disabled. Please contact support if you need this feature enabled.', + }; + } - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); + const mimetype = result.data?.mime_type || result.headers['content-type']; - await s3Service.uploadFile(fullName, buffer.data, size, { - 'Content-Type': mimetype, - }); + const contentDisposition = result.headers['content-disposition']; + let fileName = `${message.messages[0].id}.${mimetype.split('/')[1]}`; + if (contentDisposition) { + const match = contentDisposition.match(/filename="(.+?)"/); + if (match) { + fileName = match[1]; + } + } - await this.prismaRepository.media.create({ - data: { - messageId: received.messages[0].id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); + // Para áudio, garantir extensão correta baseada no mimetype + if (mediaType === 'audio') { + if (mimetype.includes('ogg')) { + fileName = `${message.messages[0].id}.ogg`; + } else if (mimetype.includes('mp3')) { + fileName = `${message.messages[0].id}.mp3`; + } else if (mimetype.includes('m4a')) { + fileName = `${message.messages[0].id}.m4a`; + } + } + + const size = result.headers['content-length'] || buffer.data.byteLength; + + const fullName = join(`${this.instance.id}`, key.remoteJid, mediaType, fileName); + + await s3Service.uploadFile(fullName, buffer.data, size, { + 'Content-Type': mimetype, + }); + + const createdMessage = await this.prismaRepository.message.create({ + data: messageRaw, + }); + + await this.prismaRepository.media.create({ + data: { + messageId: createdMessage.id, + instanceId: this.instanceId, + type: mediaType, + fileName: fullName, + mimetype, + }, + }); - const mediaUrl = await s3Service.getObjectUrl(fullName); + const mediaUrl = await s3Service.getObjectUrl(fullName); - messageRaw.message.mediaUrl = mediaUrl; + messageRaw.message.mediaUrl = mediaUrl; + if (this.localWebhook.enabled && this.localWebhook.webhookBase64) { + messageRaw.message.base64 = buffer.data.toString('base64'); + } + + // Processar OpenAI speech-to-text para áudio após o mediaUrl estar disponível + if (this.configService.get('OPENAI').ENABLED && mediaType === 'audio') { + const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ + where: { + instanceId: this.instanceId, + }, + include: { + OpenaiCreds: true, + }, + }); + + if ( + openAiDefaultSettings && + openAiDefaultSettings.openaiCredsId && + openAiDefaultSettings.speechToText + ) { + try { + messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText( + openAiDefaultSettings.OpenaiCreds, + { + message: { + mediaUrl: messageRaw.message.mediaUrl, + ...messageRaw, + }, + }, + )}`; + } catch (speechError) { + this.logger.error(`Error processing speech-to-text: ${speechError}`); + } + } + } + } } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); } } else { - const buffer = await this.downloadMediaMessage(received?.messages[0]); + if (this.localWebhook.enabled && this.localWebhook.webhookBase64) { + const buffer = await this.downloadMediaMessage(received?.messages[0]); + messageRaw.message.base64 = buffer.toString('base64'); + } + + // Processar OpenAI speech-to-text para áudio mesmo sem S3 + if (this.configService.get('OPENAI').ENABLED && message.type === 'audio') { + let openAiBase64 = messageRaw.message.base64; + if (!openAiBase64) { + const buffer = await this.downloadMediaMessage(received?.messages[0]); + openAiBase64 = buffer.toString('base64'); + } + + const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ + where: { + instanceId: this.instanceId, + }, + include: { + OpenaiCreds: true, + }, + }); - messageRaw.message.base64 = buffer.toString('base64'); + if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { + try { + messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText( + openAiDefaultSettings.OpenaiCreds, + { + message: { + base64: openAiBase64, + ...messageRaw, + }, + }, + )}`; + } catch (speechError) { + this.logger.error(`Error processing speech-to-text: ${speechError}`); + } + } + } } } else if (received?.messages[0].interactive) { messageRaw = { @@ -448,32 +664,10 @@ export class BusinessStartupService extends ChannelStartupService { // await this.client.readMessages([received.key]); } - if (this.configService.get('OPENAI').ENABLED) { - const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: this.instanceId, - }, - include: { - OpenaiCreds: true, - }, - }); - - if ( - openAiDefaultSettings && - openAiDefaultSettings.openaiCredsId && - openAiDefaultSettings.speechToText && - received?.message?.audioMessage - ) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, - ); - } - } - this.logger.log(messageRaw); + sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`); + this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); await chatbotController.emit({ @@ -497,9 +691,11 @@ export class BusinessStartupService extends ChannelStartupService { } } - await this.prismaRepository.message.create({ - data: messageRaw, - }); + if (!this.isMediaMessage(message) && message.type !== 'sticker') { + await this.prismaRepository.message.create({ + data: messageRaw, + }); + } const contact = await this.prismaRepository.contact.findFirst({ where: { instanceId: this.instanceId, remoteJid: key.remoteJid }, @@ -698,17 +894,54 @@ export class BusinessStartupService extends ChannelStartupService { } protected async eventHandler(content: any) { - const database = this.configService.get('DATABASE'); - const settings = await this.findSettings(); + try { + // Registro para depuración + this.logger.log('Contenido recibido en eventHandler:'); + this.logger.log(JSON.stringify(content, null, 2)); + + const database = this.configService.get('DATABASE'); + const settings = await this.findSettings(); - this.messageHandle(content, database, settings); + // Si hay mensajes, verificar primero el tipo + if (content.messages && content.messages.length > 0) { + const message = content.messages[0]; + this.logger.log(`Tipo de mensaje recibido: ${message.type}`); + + // Verificamos el tipo de mensaje antes de procesarlo + if ( + message.type === 'text' || + message.type === 'image' || + message.type === 'video' || + message.type === 'audio' || + message.type === 'document' || + message.type === 'sticker' || + message.type === 'location' || + message.type === 'contacts' || + message.type === 'interactive' || + message.type === 'button' || + message.type === 'reaction' + ) { + // Procesar el mensaje normalmente + this.messageHandle(content, database, settings); + } else { + this.logger.warn(`Tipo de mensaje no reconocido: ${message.type}`); + } + } else if (content.statuses) { + // Procesar actualizaciones de estado + this.messageHandle(content, database, settings); + } else { + this.logger.warn('No se encontraron mensajes ni estados en el contenido recibido'); + } + } catch (error) { + this.logger.error('Error en eventHandler:'); + this.logger.error(error); + } } protected async sendMessageWithTyping(number: string, message: any, options?: Options, isIntegration = false) { try { let quoted: any; let webhookUrl: any; - const linkPreview = options?.linkPreview != false ? undefined : false; if (options?.quoted) { const m = options?.quoted; @@ -776,13 +1009,15 @@ export class BusinessStartupService extends ChannelStartupService { to: number.replace(/\D/g, ''), text: { body: message['conversation'], - preview_url: linkPreview, + preview_url: Boolean(options?.linkPreview), }, }; quoted ? (content.context = { message_id: quoted.id }) : content; return await this.post(content, 'messages'); } if (message['media']) { + const isImage = message['mimetype']?.startsWith('image/'); + content = { messaging_product: 'whatsapp', recipient_type: 'individual', @@ -790,8 +1025,11 @@ export class BusinessStartupService extends ChannelStartupService { to: number.replace(/\D/g, ''), [message['mediaType']]: { [message['type']]: message['id'], - preview_url: linkPreview, - caption: message['caption'], + ...(message['mediaType'] !== 'audio' && + message['mediaType'] !== 'video' && + message['fileName'] && + !isImage && { filename: message['fileName'] }), + ...(message['mediaType'] !== 'audio' && message['caption'] && { caption: message['caption'] }), }, }; quoted ? (content.context = { message_id: quoted.id }) : content; @@ -889,13 +1127,13 @@ export class BusinessStartupService extends ChannelStartupService { } })(); - if (messageSent?.error_data) { + if (messageSent?.error_data || messageSent.message) { this.logger.error(messageSent); return messageSent; } const messageRaw: any = { - key: { fromMe: true, id: messageSent?.messages[0]?.id, remoteJid: this.createJid(number) }, + key: { fromMe: true, id: messageSent?.messages[0]?.id, remoteJid: createJid(number) }, message: this.convertMessageToRaw(message, content), messageType: this.renderMessageType(content.type), messageTimestamp: (messageSent?.messages[0]?.timestamp as number) || Math.round(new Date().getTime() / 1000), @@ -956,29 +1194,50 @@ export class BusinessStartupService extends ChannelStartupService { return res; } - private async getIdMedia(mediaMessage: any) { - const formData = new FormData(); + private async getIdMedia(mediaMessage: any, isFile = false) { + try { + const formData = new FormData(); + + if (isFile === false) { + if (isURL(mediaMessage.media)) { + const response = await axios.get(mediaMessage.media, { responseType: 'arraybuffer' }); + const buffer = Buffer.from(response.data, 'base64'); + formData.append('file', buffer, { + filename: mediaMessage.fileName || 'media', + contentType: mediaMessage.mimetype, + }); + } else { + const buffer = Buffer.from(mediaMessage.media, 'base64'); + formData.append('file', buffer, { + filename: mediaMessage.fileName || 'media', + contentType: mediaMessage.mimetype, + }); + } + } else { + formData.append('file', mediaMessage.media.buffer, { + filename: mediaMessage.media.originalname, + contentType: mediaMessage.media.mimetype, + }); + } - const fileStream = createReadStream(mediaMessage.media); + const mimetype = mediaMessage.mimetype || mediaMessage.media.mimetype; - formData.append('file', fileStream, { filename: 'media', contentType: mediaMessage.mimetype }); - formData.append('typeFile', mediaMessage.mimetype); - formData.append('messaging_product', 'whatsapp'); + formData.append('typeFile', mimetype); + formData.append('messaging_product', 'whatsapp'); - // const fileBuffer = await fs.readFile(mediaMessage.media); + const token = this.token; - // const fileBlob = new Blob([fileBuffer], { type: mediaMessage.mimetype }); - // formData.append('file', fileBlob); - // formData.append('typeFile', mediaMessage.mimetype); - // formData.append('messaging_product', 'whatsapp'); + const headers = { Authorization: `Bearer ${token}` }; + const url = `${this.configService.get('WA_BUSINESS').URL}/${ + this.configService.get('WA_BUSINESS').VERSION + }/${this.number}/media`; - const headers = { Authorization: `Bearer ${this.token}` }; - const res = await axios.post( - process.env.API_URL + '/' + process.env.VERSION + '/' + this.number + '/media', - formData, - { headers }, - ); - return res.data.id; + const res = await axios.post(url, formData, { headers }); + return res.data.id; + } catch (error) { + this.logger.error(error.response.data); + throw new InternalServerErrorException(error?.toString() || error); + } } protected async prepareMediaMessage(mediaMessage: MediaMessage) { @@ -997,7 +1256,7 @@ export class BusinessStartupService extends ChannelStartupService { mediaMessage.fileName = 'video.mp4'; } - let mimetype: string; + let mimetype: string | false; const prepareMedia: any = { caption: mediaMessage?.caption, @@ -1008,11 +1267,11 @@ export class BusinessStartupService extends ChannelStartupService { }; if (isURL(mediaMessage.media)) { - mimetype = mime.getType(mediaMessage.media); + mimetype = mimeTypes.lookup(mediaMessage.media); prepareMedia.id = mediaMessage.media; prepareMedia.type = 'link'; } else { - mimetype = mime.getType(mediaMessage.fileName); + mimetype = mimeTypes.lookup(mediaMessage.fileName); const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; @@ -1051,45 +1310,88 @@ export class BusinessStartupService extends ChannelStartupService { return mediaSent; } - public async processAudio(audio: string, number: string) { + public async processAudio(audio: string, number: string, file: any) { number = number.replace(/\D/g, ''); const hash = `${number}-${new Date().getTime()}`; - let mimetype: string; + const audioConverterConfig = this.configService.get('AUDIO_CONVERTER'); + if (audioConverterConfig.API_URL) { + this.logger.verbose('Using audio converter API'); + const formData = new FormData(); - const prepareMedia: any = { - fileName: `${hash}.mp3`, - mediaType: 'audio', - media: audio, - }; + if (file) { + formData.append('file', file.buffer, { + filename: file.originalname, + contentType: file.mimetype, + }); + } else if (isURL(audio)) { + formData.append('url', audio); + } else { + formData.append('base64', audio); + } + + formData.append('format', 'mp3'); + + const response = await axios.post(audioConverterConfig.API_URL, formData, { + headers: { + ...formData.getHeaders(), + apikey: audioConverterConfig.API_KEY, + }, + }); + + const audioConverter = response?.data?.audio || response?.data?.url; + + if (!audioConverter) { + throw new InternalServerErrorException('Failed to convert audio'); + } + + const prepareMedia: any = { + fileName: `${hash}.mp3`, + mediaType: 'audio', + media: audioConverter, + mimetype: 'audio/mpeg', + }; - if (isURL(audio)) { - mimetype = mime.getType(audio); - prepareMedia.id = audio; - prepareMedia.type = 'link'; - } else { - mimetype = mime.getType(prepareMedia.fileName); const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; - } - prepareMedia.mimetype = mimetype; + this.logger.verbose('Audio converted'); + return prepareMedia; + } else { + let mimetype: string | false; + + const prepareMedia: any = { + fileName: `${hash}.mp3`, + mediaType: 'audio', + media: audio, + }; - return prepareMedia; - } + if (isURL(audio)) { + mimetype = mimeTypes.lookup(audio); + prepareMedia.id = audio; + prepareMedia.type = 'link'; + } else if (audio && !file) { + mimetype = mimeTypes.lookup(prepareMedia.fileName); + const id = await this.getIdMedia(prepareMedia); + prepareMedia.id = id; + prepareMedia.type = 'id'; + } else if (file) { + prepareMedia.media = file; + const id = await this.getIdMedia(prepareMedia, true); + prepareMedia.id = id; + prepareMedia.type = 'id'; + mimetype = file.mimetype; + } - public async audioWhatsapp(data: SendAudioDto, file?: any, isIntegration = false) { - const mediaData: SendAudioDto = { ...data }; + prepareMedia.mimetype = mimetype; - if (file?.buffer) { - mediaData.audio = file.buffer.toString('base64'); - } else { - console.error('El archivo no tiene buffer o file es undefined'); - throw new Error('File or buffer is undefined'); + return prepareMedia; } + } - const message = await this.processAudio(mediaData.audio, data.number); + public async audioWhatsapp(data: SendAudioDto, file?: any, isIntegration = false) { + const message = await this.processAudio(data.audio, data.number, file); const audioSent = await this.sendMessageWithTyping( data.number, @@ -1251,7 +1553,7 @@ export class BusinessStartupService extends ChannelStartupService { } if (!contact.wuid) { - contact.wuid = this.createJid(contact.phoneNumber); + contact.wuid = createJid(contact.phoneNumber); } result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD'; @@ -1315,9 +1617,14 @@ export class BusinessStartupService extends ChannelStartupService { const messageType = msg.messageType.includes('Message') ? msg.messageType : msg.messageType + 'Message'; const mediaMessage = msg.message[messageType]; + if (!msg.message?.base64) { + const buffer = await this.downloadMediaMessage({ type: messageType, ...msg.message }); + msg.message.base64 = buffer.toString('base64'); + } + return { mediaType: msg.messageType, - fileName: mediaMessage?.fileName, + fileName: mediaMessage?.fileName || mediaMessage?.filename, caption: mediaMessage?.caption, size: { fileLength: mediaMessage?.fileLength, diff --git a/src/api/integrations/channel/whatsapp/baileys.controller.ts b/src/api/integrations/channel/whatsapp/baileys.controller.ts new file mode 100644 index 000000000..ee547338d --- /dev/null +++ b/src/api/integrations/channel/whatsapp/baileys.controller.ts @@ -0,0 +1,60 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { WAMonitoringService } from '@api/services/monitor.service'; + +export class BaileysController { + constructor(private readonly waMonitor: WAMonitoringService) {} + + public async onWhatsapp({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysOnWhatsapp(body?.jid); + } + + public async profilePictureUrl({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysProfilePictureUrl(body?.jid, body?.type, body?.timeoutMs); + } + + public async assertSessions({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysAssertSessions(body?.jids, body?.force); + } + + public async createParticipantNodes({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysCreateParticipantNodes(body?.jids, body?.message, body?.extraAttrs); + } + + public async getUSyncDevices({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysGetUSyncDevices(body?.jids, body?.useCache, body?.ignoreZeroDevices); + } + + public async generateMessageTag({ instanceName }: InstanceDto) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysGenerateMessageTag(); + } + + public async sendNode({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysSendNode(body?.stanza); + } + + public async signalRepositoryDecryptMessage({ instanceName }: InstanceDto, body: any) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysSignalRepositoryDecryptMessage(body?.jid, body?.type, body?.ciphertext); + } + + public async getAuthState({ instanceName }: InstanceDto) { + const instance = this.waMonitor.waInstances[instanceName]; + + return instance.baileysGetAuthState(); + } +} diff --git a/src/api/integrations/channel/whatsapp/baileys.router.ts b/src/api/integrations/channel/whatsapp/baileys.router.ts new file mode 100644 index 000000000..04a1d565f --- /dev/null +++ b/src/api/integrations/channel/whatsapp/baileys.router.ts @@ -0,0 +1,105 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { baileysController } from '@api/server.module'; +import { instanceSchema } from '@validate/instance.schema'; +import { RequestHandler, Router } from 'express'; + +export class BaileysRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('onWhatsapp'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.onWhatsapp(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('profilePictureUrl'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.profilePictureUrl(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('assertSessions'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.assertSessions(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('createParticipantNodes'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.createParticipantNodes(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('getUSyncDevices'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.getUSyncDevices(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('generateMessageTag'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.generateMessageTag(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('sendNode'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.sendNode(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('signalRepositoryDecryptMessage'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.signalRepositoryDecryptMessage(instance, req.body), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('getAuthState'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => baileysController.getAuthState(instance), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts new file mode 100644 index 000000000..fbe1864a1 --- /dev/null +++ b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts @@ -0,0 +1,75 @@ +import { Logger } from '@config/logger.config'; +import { BaileysEventMap, MessageUpsertType, WAMessage } from 'baileys'; +import { catchError, concatMap, delay, EMPTY, from, retryWhen, Subject, Subscription, take, tap } from 'rxjs'; + +type MessageUpsertPayload = BaileysEventMap['messages.upsert']; +type MountProps = { + onMessageReceive: (payload: MessageUpsertPayload, settings: any) => Promise; +}; + +export class BaileysMessageProcessor { + private processorLogs = new Logger('BaileysMessageProcessor'); + private subscription?: Subscription; + + protected messageSubject = new Subject<{ + messages: WAMessage[]; + type: MessageUpsertType; + requestId?: string; + settings: any; + }>(); + + mount({ onMessageReceive }: MountProps) { + // Se já existe subscription, fazer cleanup primeiro + if (this.subscription && !this.subscription.closed) { + this.subscription.unsubscribe(); + } + + // Se o Subject foi completado, recriar + if (this.messageSubject.closed) { + this.processorLogs.warn('MessageSubject was closed, recreating...'); + this.messageSubject = new Subject<{ + messages: WAMessage[]; + type: MessageUpsertType; + requestId?: string; + settings: any; + }>(); + } + + this.subscription = this.messageSubject + .pipe( + tap(({ messages }) => { + this.processorLogs.log(`Processing batch of ${messages.length} messages`); + }), + concatMap(({ messages, type, requestId, settings }) => + from(onMessageReceive({ messages, type, requestId }, settings)).pipe( + retryWhen((errors) => + errors.pipe( + tap((error) => this.processorLogs.warn(`Retrying message batch due to error: ${error.message}`)), + delay(1000), // 1 segundo de delay + take(3), // Máximo 3 tentativas + ), + ), + ), + ), + catchError((error) => { + this.processorLogs.error(`Error processing message batch: ${error}`); + return EMPTY; + }), + ) + .subscribe({ + error: (error) => { + this.processorLogs.error(`Message stream error: ${error}`); + }, + }); + } + + processMessage(payload: MessageUpsertPayload, settings: any) { + const { messages, type, requestId } = payload; + this.messageSubject.next({ messages, type, requestId, settings }); + } + + onDestroy() { + this.subscription?.unsubscribe(); + this.messageSubject.complete(); + } +} diff --git a/src/api/integrations/channel/whatsapp/voiceCalls/transport.type.ts b/src/api/integrations/channel/whatsapp/voiceCalls/transport.type.ts new file mode 100644 index 000000000..f03c10289 --- /dev/null +++ b/src/api/integrations/channel/whatsapp/voiceCalls/transport.type.ts @@ -0,0 +1,78 @@ +import { BinaryNode, Contact, JidWithDevice, proto, WAConnectionState } from 'baileys'; + +export interface ServerToClientEvents { + withAck: (d: string, callback: (e: number) => void) => void; + onWhatsApp: onWhatsAppType; + profilePictureUrl: ProfilePictureUrlType; + assertSessions: AssertSessionsType; + createParticipantNodes: CreateParticipantNodesType; + getUSyncDevices: GetUSyncDevicesType; + generateMessageTag: GenerateMessageTagType; + sendNode: SendNodeType; + 'signalRepository:decryptMessage': SignalRepositoryDecryptMessageType; +} + +export interface ClientToServerEvents { + init: ( + me: Contact | undefined, + account: proto.IADVSignedDeviceIdentity | undefined, + status: WAConnectionState, + ) => void; + 'CB:call': (packet: any) => void; + 'CB:ack,class:call': (packet: any) => void; + 'connection.update:status': ( + me: Contact | undefined, + account: proto.IADVSignedDeviceIdentity | undefined, + status: WAConnectionState, + ) => void; + 'connection.update:qr': (qr: string) => void; +} + +export type onWhatsAppType = (jid: string, callback: onWhatsAppCallback) => void; +export type onWhatsAppCallback = ( + response: { + exists: boolean; + jid: string; + }[], +) => void; + +export type ProfilePictureUrlType = ( + jid: string, + type: 'image' | 'preview', + timeoutMs: number | undefined, + callback: ProfilePictureUrlCallback, +) => void; +export type ProfilePictureUrlCallback = (response: string | undefined) => void; + +export type AssertSessionsType = (jids: string[], force: boolean, callback: AssertSessionsCallback) => void; +export type AssertSessionsCallback = (response: boolean) => void; + +export type CreateParticipantNodesType = ( + jids: string[], + message: any, + extraAttrs: any, + callback: CreateParticipantNodesCallback, +) => void; +export type CreateParticipantNodesCallback = (nodes: any, shouldIncludeDeviceIdentity: boolean) => void; + +export type GetUSyncDevicesType = ( + jids: string[], + useCache: boolean, + ignoreZeroDevices: boolean, + callback: GetUSyncDevicesTypeCallback, +) => void; +export type GetUSyncDevicesTypeCallback = (jids: JidWithDevice[]) => void; + +export type GenerateMessageTagType = (callback: GenerateMessageTagTypeCallback) => void; +export type GenerateMessageTagTypeCallback = (response: string) => void; + +export type SendNodeType = (stanza: BinaryNode, callback: SendNodeTypeCallback) => void; +export type SendNodeTypeCallback = (response: boolean) => void; + +export type SignalRepositoryDecryptMessageType = ( + jid: string, + type: 'pkmsg' | 'msg', + ciphertext: Buffer, + callback: SignalRepositoryDecryptMessageCallback, +) => void; +export type SignalRepositoryDecryptMessageCallback = (response: any) => void; diff --git a/src/api/integrations/channel/whatsapp/voiceCalls/useVoiceCallsBaileys.ts b/src/api/integrations/channel/whatsapp/voiceCalls/useVoiceCallsBaileys.ts new file mode 100644 index 000000000..cb667f9ca --- /dev/null +++ b/src/api/integrations/channel/whatsapp/voiceCalls/useVoiceCallsBaileys.ts @@ -0,0 +1,181 @@ +import { ConnectionState, WAConnectionState, WASocket } from 'baileys'; +import { io, Socket } from 'socket.io-client'; + +import { ClientToServerEvents, ServerToClientEvents } from './transport.type'; + +let baileys_connection_state: WAConnectionState = 'close'; + +export const useVoiceCallsBaileys = async ( + wavoip_token: string, + baileys_sock: WASocket, + status?: WAConnectionState, + logger?: boolean, +) => { + baileys_connection_state = status ?? 'close'; + + const socket: Socket = io('https://devices.wavoip.com/baileys', { + transports: ['websocket'], + path: `/${wavoip_token}/websocket`, + }); + + socket.on('connect', () => { + if (logger) console.log('[*] - Wavoip connected', socket.id); + + socket.emit( + 'init', + baileys_sock.authState.creds.me, + baileys_sock.authState.creds.account, + baileys_connection_state, + ); + }); + + socket.on('disconnect', () => { + if (logger) console.log('[*] - Wavoip disconnect'); + }); + + socket.on('connect_error', (error) => { + if (socket.active) { + if (logger) + console.log( + '[*] - Wavoip connection error temporary failure, the socket will automatically try to reconnect', + error, + ); + } else { + if (logger) console.log('[*] - Wavoip connection error', error.message); + } + }); + + socket.on('onWhatsApp', async (jid, callback) => { + try { + const response: any = await baileys_sock.onWhatsApp(jid); + + callback(response); + + if (logger) console.log('[*] Success on call onWhatsApp function', response, jid); + } catch (error) { + if (logger) console.error('[*] Error on call onWhatsApp function', error); + } + }); + + socket.on('profilePictureUrl', async (jid, type, timeoutMs, callback) => { + try { + const response = await baileys_sock.profilePictureUrl(jid, type, timeoutMs); + + callback(response); + + if (logger) console.log('[*] Success on call profilePictureUrl function', response); + } catch (error) { + if (logger) console.error('[*] Error on call profilePictureUrl function', error); + } + }); + + socket.on('assertSessions', async (jids, force, callback) => { + try { + const response = await baileys_sock.assertSessions(jids); + + callback(response); + + if (logger) console.log('[*] Success on call assertSessions function', response); + } catch (error) { + if (logger) console.error('[*] Error on call assertSessions function', error); + } + }); + + socket.on('createParticipantNodes', async (jids, message, extraAttrs, callback) => { + try { + const response = await baileys_sock.createParticipantNodes(jids, message, extraAttrs); + + callback(response, true); + + if (logger) console.log('[*] Success on call createParticipantNodes function', response); + } catch (error) { + if (logger) console.error('[*] Error on call createParticipantNodes function', error); + } + }); + + socket.on('getUSyncDevices', async (jids, useCache, ignoreZeroDevices, callback) => { + try { + const response = await baileys_sock.getUSyncDevices(jids, useCache, ignoreZeroDevices); + + callback(response); + + if (logger) console.log('[*] Success on call getUSyncDevices function', response); + } catch (error) { + if (logger) console.error('[*] Error on call getUSyncDevices function', error); + } + }); + + socket.on('generateMessageTag', async (callback) => { + try { + const response = await baileys_sock.generateMessageTag(); + + callback(response); + + if (logger) console.log('[*] Success on call generateMessageTag function', response); + } catch (error) { + if (logger) console.error('[*] Error on call generateMessageTag function', error); + } + }); + + socket.on('sendNode', async (stanza, callback) => { + try { + console.log('sendNode', JSON.stringify(stanza)); + const response = await baileys_sock.sendNode(stanza); + + callback(true); + + if (logger) console.log('[*] Success on call sendNode function', response); + } catch (error) { + if (logger) console.error('[*] Error on call sendNode function', error); + } + }); + + socket.on('signalRepository:decryptMessage', async (jid, type, ciphertext, callback) => { + try { + const response = await baileys_sock.signalRepository.decryptMessage({ + jid: jid, + type: type, + ciphertext: ciphertext, + }); + + callback(response); + + if (logger) console.log('[*] Success on call signalRepository:decryptMessage function', response); + } catch (error) { + if (logger) console.error('[*] Error on call signalRepository:decryptMessage function', error); + } + }); + + // we only use this connection data to inform the webphone that the device is connected and creeds account to generate e2e whatsapp key for make call packets + baileys_sock.ev.on('connection.update', (update: Partial) => { + const { connection } = update; + + if (connection) { + baileys_connection_state = connection; + socket + .timeout(1000) + .emit( + 'connection.update:status', + baileys_sock.authState.creds.me, + baileys_sock.authState.creds.account, + connection, + ); + } + + if (update.qr) { + socket.timeout(1000).emit('connection.update:qr', update.qr); + } + }); + + baileys_sock.ws.on('CB:call', (packet) => { + if (logger) console.log('[*] Signling received'); + socket.volatile.timeout(1000).emit('CB:call', packet); + }); + + baileys_sock.ws.on('CB:ack,class:call', (packet) => { + if (logger) console.log('[*] Signling ack received'); + socket.volatile.timeout(1000).emit('CB:ack,class:call', packet); + }); + + return socket; +}; diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 0afd5318a..60e857fcc 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -1,3 +1,4 @@ +import { getCollectionsDto } from '@api/dto/business.dto'; import { OfferCallDto } from '@api/dto/call.dto'; import { ArchiveChatDto, @@ -54,13 +55,14 @@ import { import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper'; import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; import { ProviderFiles } from '@api/provider/sessions'; -import { PrismaRepository } from '@api/repository/repository.service'; +import { PrismaRepository, Query } from '@api/repository/repository.service'; import { chatbotController, waMonitor } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; import { ChannelStartupService } from '@api/services/channel.service'; import { Events, MessageSubtype, TypeMediaMessage, wa } from '@api/types/wa.types'; import { CacheEngine } from '@cache/cacheengine'; import { + AudioConverter, CacheConf, Chatwoot, ConfigService, @@ -76,10 +78,14 @@ import { import { BadRequestException, InternalServerErrorException, NotFoundException } from '@exceptions'; import ffmpegPath from '@ffmpeg-installer/ffmpeg'; import { Boom } from '@hapi/boom'; -import { Instance } from '@prisma/client'; -import { makeProxyAgent } from '@utils/makeProxyAgent'; +import { createId as cuid } from '@paralleldrive/cuid2'; +import { Instance, Message } from '@prisma/client'; +import { createJid } from '@utils/createJid'; +import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion'; +import { makeProxyAgent, makeProxyAgentUndici } from '@utils/makeProxyAgent'; import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache'; import { status } from '@utils/renderStatus'; +import { sendTelemetry } from '@utils/sendTelemetry'; import useMultiFileAuthStatePrisma from '@utils/use-multi-file-auth-state-prisma'; import { AuthStateProvider } from '@utils/use-multi-file-auth-state-provider-files'; import { useMultiFileAuthStateRedisDb } from '@utils/use-multi-file-auth-state-redis-db'; @@ -89,34 +95,39 @@ import makeWASocket, { BufferedEventData, BufferJSON, CacheStore, + CatalogCollection, Chat, ConnectionState, Contact, + decryptPollVote, delay, DisconnectReason, + downloadContentFromMessage, downloadMediaMessage, - fetchLatestBaileysVersion, generateWAMessageFromContent, getAggregateVotesInPollMessage, + GetCatalogOptions, getContentType, getDevice, GroupMetadata, isJidBroadcast, isJidGroup, isJidNewsletter, - isJidUser, + isPnUser, + jidNormalizedUser, makeCacheableSignalKeyStore, MessageUpsertType, MessageUserReceiptUpdate, MiscMessageGenerationOptions, ParticipantAction, prepareWAMessageMedia, + Product, proto, UserFacingSocketConfig, WABrowserDescription, WAMediaUpload, WAMessage, - WAMessageUpdate, + WAMessageKey, WAPresence, WASocket, } from 'baileys'; @@ -124,13 +135,12 @@ import { Label } from 'baileys/lib/Types/Label'; import { LabelAssociation } from 'baileys/lib/Types/LabelAssociation'; import { spawn } from 'child_process'; import { isArray, isBase64, isURL } from 'class-validator'; -import { randomBytes } from 'crypto'; +import { createHash } from 'crypto'; import EventEmitter2 from 'eventemitter2'; import ffmpeg from 'fluent-ffmpeg'; import FormData from 'form-data'; -import { readFileSync } from 'fs'; import Long from 'long'; -import mime from 'mime'; +import mimeTypes from 'mime-types'; import NodeCache from 'node-cache'; import cron from 'node-cron'; import { release } from 'os'; @@ -142,6 +152,16 @@ import sharp from 'sharp'; import { PassThrough, Readable } from 'stream'; import { v4 } from 'uuid'; +import { BaileysMessageProcessor } from './baileysMessage.processor'; +import { useVoiceCallsBaileys } from './voiceCalls/useVoiceCallsBaileys'; + +export interface ExtendedIMessageKey extends proto.IMessageKey { + remoteJidAlt?: string; + participantAlt?: string; + server_id?: string; + isViewOnce?: boolean; +} + const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine()); // Adicione a função getVideoDuration no início do arquivo @@ -205,6 +225,8 @@ async function getVideoDuration(input: Buffer | string | Readable): Promise('LOG').BAILEYS; + private eventProcessingQueue: Promise = Promise.resolve(); + + // Cache TTL constants (in seconds) + private readonly MESSAGE_CACHE_TTL_SECONDS = 5 * 60; // 5 minutes - avoid duplicate message processing + private readonly UPDATE_CACHE_TTL_SECONDS = 30 * 60; // 30 minutes - avoid duplicate status updates public stateConnection: wa.StateConnection = { state: 'close' }; @@ -235,28 +265,43 @@ export class BaileysStartupService extends ChannelStartupService { } public async logoutInstance() { + this.messageProcessor.onDestroy(); await this.client?.logout('Log out instance: ' + this.instanceName); this.client?.ws?.close(); - const sessionExists = await this.prismaRepository.session.findFirst({ - where: { sessionId: this.instanceId }, - }); + const db = this.configService.get('DATABASE'); + const cache = this.configService.get('CACHE'); + const provider = this.configService.get('PROVIDER'); + + if (provider?.ENABLED) { + const authState = await this.authStateProvider.authStateProvider(this.instance.id); + + await authState.removeCreds(); + } + + if (cache?.REDIS.ENABLED && cache?.REDIS.SAVE_INSTANCES) { + const authState = await useMultiFileAuthStateRedisDb(this.instance.id, this.cache); + + await authState.removeCreds(); + } + + if (db.SAVE_DATA.INSTANCE) { + const authState = await useMultiFileAuthStatePrisma(this.instance.id, this.cache); + + await authState.removeCreds(); + } + + const sessionExists = await this.prismaRepository.session.findFirst({ where: { sessionId: this.instanceId } }); if (sessionExists) { - await this.prismaRepository.session.delete({ - where: { - sessionId: this.instanceId, - }, - }); + await this.prismaRepository.session.delete({ where: { sessionId: this.instanceId } }); } } public async getProfileName() { let profileName = this.client.user?.name ?? this.client.user?.verifiedName; if (!profileName) { - const data = await this.prismaRepository.session.findUnique({ - where: { sessionId: this.instanceId }, - }); + const data = await this.prismaRepository.session.findUnique({ where: { sessionId: this.instanceId } }); if (data) { const creds = JSON.parse(JSON.stringify(data.creds), BufferJSON.reviver); @@ -270,7 +315,7 @@ export class BaileysStartupService extends ChannelStartupService { public async getProfileStatus() { const status = await this.client.fetchStatus(this.instance.wuid); - return status?.status; + return status[0]?.status; } public get profilePictureUrl() { @@ -298,10 +343,7 @@ export class BaileysStartupService extends ChannelStartupService { this.chatwootService.eventWhatsapp( Events.QRCODE_UPDATED, { instanceName: this.instance.name, instanceId: this.instanceId }, - { - message: 'QR code limit reached, please login again', - statusCode: DisconnectReason.badSession, - }, + { message: 'QR code limit reached, please login again', statusCode: DisconnectReason.badSession }, ); } @@ -309,6 +351,9 @@ export class BaileysStartupService extends ChannelStartupService { instance: this.instance.name, state: 'refused', statusReason: DisconnectReason.connectionClosed, + wuid: this.instance.wuid, + profileName: await this.getProfileName(), + profilePictureUrl: this.instance.profilePictureUrl, }); this.endSession = true; @@ -344,12 +389,7 @@ export class BaileysStartupService extends ChannelStartupService { this.instance.qrcode.code = qr; this.sendDataWebhook(Events.QRCODE_UPDATED, { - qrcode: { - instance: this.instance.name, - pairingCode: this.instance.qrcode.pairingCode, - code: qr, - base64, - }, + qrcode: { instance: this.instance.name, pairingCode: this.instance.qrcode.pairingCode, code: qr, base64 }, }); if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { @@ -357,12 +397,7 @@ export class BaileysStartupService extends ChannelStartupService { Events.QRCODE_UPDATED, { instanceName: this.instance.name, instanceId: this.instanceId }, { - qrcode: { - instance: this.instance.name, - pairingCode: this.instance.qrcode.pairingCode, - code: qr, - base64, - }, + qrcode: { instance: this.instance.name, pairingCode: this.instance.qrcode.pairingCode, code: qr, base64 }, }, ); } @@ -377,9 +412,7 @@ export class BaileysStartupService extends ChannelStartupService { await this.prismaRepository.instance.update({ where: { id: this.instanceId }, - data: { - connectionStatus: 'connecting', - }, + data: { connectionStatus: 'connecting' }, }); } @@ -388,11 +421,6 @@ export class BaileysStartupService extends ChannelStartupService { state: connection, statusReason: (lastDisconnect?.error as Boom)?.output?.statusCode ?? 200, }; - - this.sendDataWebhook(Events.CONNECTION_UPDATE, { - instance: this.instance.name, - ...this.stateConnection, - }); } if (connection === 'close') { @@ -424,16 +452,15 @@ export class BaileysStartupService extends ChannelStartupService { this.chatwootService.eventWhatsapp( Events.STATUS_INSTANCE, { instanceName: this.instance.name, instanceId: this.instanceId }, - { - instance: this.instance.name, - status: 'closed', - }, + { instance: this.instance.name, status: 'closed' }, ); } this.eventEmitter.emit('logout.instance', this.instance.name, 'inner'); this.client?.ws?.close(); this.client.end(new Error('Close connection')); + + this.sendDataWebhook(Events.CONNECTION_UPDATE, { instance: this.instance.name, ...this.stateConnection }); } } @@ -442,7 +469,7 @@ export class BaileysStartupService extends ChannelStartupService { try { const profilePic = await this.profilePicture(this.instance.wuid); this.instance.profilePictureUrl = profilePic.profilePictureUrl; - } catch (error) { + } catch { this.instance.profilePictureUrl = null; } const formattedWuid = this.instance.wuid.split('@')[0].padEnd(30, ' '); @@ -474,27 +501,34 @@ export class BaileysStartupService extends ChannelStartupService { this.chatwootService.eventWhatsapp( Events.CONNECTION_UPDATE, { instanceName: this.instance.name, instanceId: this.instanceId }, - { - instance: this.instance.name, - status: 'open', - }, + { instance: this.instance.name, status: 'open' }, ); this.syncChatwootLostMessages(); } + + this.sendDataWebhook(Events.CONNECTION_UPDATE, { + instance: this.instance.name, + wuid: this.instance.wuid, + profileName: await this.getProfileName(), + profilePictureUrl: this.instance.profilePictureUrl, + ...this.stateConnection, + }); + } + + if (connection === 'connecting') { + this.sendDataWebhook(Events.CONNECTION_UPDATE, { instance: this.instance.name, ...this.stateConnection }); } } private async getMessage(key: proto.IMessageKey, full = false) { try { - const webMessageInfo = (await this.prismaRepository.message.findMany({ - where: { - instanceId: this.instanceId, - key: { - path: ['id'], - equals: key.id, - }, - }, - })) as unknown as proto.IWebMessageInfo[]; + // Use raw SQL to avoid JSON path issues + const webMessageInfo = (await this.prismaRepository.$queryRaw` + SELECT * FROM "Message" + WHERE "instanceId" = ${this.instanceId} + AND "key"->>'id' = ${key.id} + `) as proto.IWebMessageInfo[]; + if (full) { return webMessageInfo[0]; } @@ -505,9 +539,7 @@ export class BaileysStartupService extends ChannelStartupService { const messageSecret = Buffer.from(messageSecretBase64, 'base64'); const msg = { - messageContextInfo: { - messageSecret, - }, + messageContextInfo: { messageSecret }, pollCreationMessage: webMessageInfo[0].message?.pollCreationMessage, }; @@ -516,7 +548,7 @@ export class BaileysStartupService extends ChannelStartupService { } return webMessageInfo[0].message; - } catch (error) { + } catch { return { conversation: '' }; } } @@ -559,17 +591,9 @@ export class BaileysStartupService extends ChannelStartupService { this.logger.info(`Browser: ${browser}`); } - let version; - let log; - - if (session.VERSION) { - version = session.VERSION.split('.'); - log = `Baileys version env: ${version}`; - } else { - const baileysVersion = await fetchLatestBaileysVersion(); - version = baileysVersion.version; - log = `Baileys version: ${version}`; - } + const baileysVersion = await fetchLatestWaWebVersion({}); + const version = baileysVersion.version; + const log = `Baileys version: ${version.join('.')}`; this.logger.info(log); @@ -587,11 +611,8 @@ export class BaileysStartupService extends ChannelStartupService { const proxyUrls = text.split('\r\n'); const rand = Math.floor(Math.random() * Math.floor(proxyUrls.length)); const proxyUrl = 'http://' + proxyUrls[rand]; - options = { - agent: makeProxyAgent(proxyUrl), - fetchAgent: makeProxyAgent(proxyUrl), - }; - } catch (error) { + options = { agent: makeProxyAgent(proxyUrl), fetchAgent: makeProxyAgentUndici(proxyUrl) }; + } catch { this.localProxy.enabled = false; } } else { @@ -603,7 +624,7 @@ export class BaileysStartupService extends ChannelStartupService { username: this.localProxy.username, password: this.localProxy.password, }), - fetchAgent: makeProxyAgent({ + fetchAgent: makeProxyAgentUndici({ host: this.localProxy.host, port: this.localProxy.port, protocol: this.localProxy.protocol, @@ -636,6 +657,10 @@ export class BaileysStartupService extends ChannelStartupService { qrTimeout: 45_000, emitOwnEvents: false, shouldIgnoreJid: (jid) => { + if (this.localSettings.syncFullHistory && isJidGroup(jid)) { + return false; + } + const isGroupJid = this.localSettings.groupsIgnore && isJidGroup(jid); const isBroadcast = !this.localSettings.readStatus && isJidBroadcast(jid); const isNewsletter = isJidNewsletter(jid); @@ -672,8 +697,24 @@ export class BaileysStartupService extends ChannelStartupService { this.client = makeWASocket(socketConfig); + if (this.localSettings.wavoipToken && this.localSettings.wavoipToken.length > 0) { + useVoiceCallsBaileys(this.localSettings.wavoipToken, this.client, this.connectionStatus.state as any, true); + } + this.eventHandler(); + this.client.ws.on('CB:call', (packet) => { + console.log('CB:call', packet); + const payload = { event: 'CB:call', packet: packet }; + this.sendDataWebhook(Events.CALL, payload, true, ['websocket']); + }); + + this.client.ws.on('CB:ack,class:call', (packet) => { + console.log('CB:ack,class:call', packet); + const payload = { event: 'CB:ack,class:call', packet: packet }; + this.sendDataWebhook(Events.CALL, payload, true, ['websocket']); + }); + this.phoneNumber = number; return this.client; @@ -686,6 +727,11 @@ export class BaileysStartupService extends ChannelStartupService { this.loadWebhook(); this.loadProxy(); + // Remontar o messageProcessor para garantir que está funcionando após reconexão + this.messageProcessor.mount({ + onMessageReceive: this.messageHandle['messages.upsert'].bind(this), + }); + return await this.createClient(number); } catch (error) { this.logger.error(error); @@ -724,18 +770,13 @@ export class BaileysStartupService extends ChannelStartupService { if (chatsToInsert.length > 0) { if (this.configService.get('DATABASE').SAVE_DATA.CHATS) - await this.prismaRepository.chat.createMany({ - data: chatsToInsert, - skipDuplicates: true, - }); + await this.prismaRepository.chat.createMany({ data: chatsToInsert, skipDuplicates: true }); } }, 'chats.update': async ( chats: Partial< - proto.IConversation & { - lastMessageRecvTimestamp?: number; - } & { + proto.IConversation & { lastMessageRecvTimestamp?: number } & { conditional: (bufferedData: BufferedEventData) => boolean; } >[], @@ -748,11 +789,7 @@ export class BaileysStartupService extends ChannelStartupService { for (const chat of chats) { await this.prismaRepository.chat.updateMany({ - where: { - instanceId: this.instanceId, - remoteJid: chat.id, - name: chat.name, - }, + where: { instanceId: this.instanceId, remoteJid: chat.id, name: chat.name }, data: { remoteJid: chat.id }, }); } @@ -761,9 +798,7 @@ export class BaileysStartupService extends ChannelStartupService { 'chats.delete': async (chats: string[]) => { chats.forEach( async (chat) => - await this.prismaRepository.chat.deleteMany({ - where: { instanceId: this.instanceId, remoteJid: chat }, - }), + await this.prismaRepository.chat.deleteMany({ where: { instanceId: this.instanceId, remoteJid: chat } }), ); this.sendDataWebhook(Events.CHATS_DELETE, [...chats]); @@ -784,10 +819,7 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPSERT, contactsRaw); if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) - await this.prismaRepository.contact.createMany({ - data: contactsRaw, - skipDuplicates: true, - }); + await this.prismaRepository.contact.createMany({ data: contactsRaw, skipDuplicates: true }); const usersContacts = contactsRaw.filter((c) => c.remoteJid.includes('@s.whatsapp')); if (usersContacts) { @@ -829,12 +861,12 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, updatedContacts); await Promise.all( updatedContacts.map(async (contact) => { - const update = this.prismaRepository.contact.updateMany({ - where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, - data: { - profilePicUrl: contact.profilePicUrl, - }, - }); + if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) { + await this.prismaRepository.contact.updateMany({ + where: { remoteJid: contact.remoteJid, instanceId: this.instanceId }, + data: { profilePicUrl: contact.profilePicUrl }, + }); + } if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { const instance = { instanceName: this.instance.name, instanceId: this.instance.id }; @@ -853,8 +885,6 @@ export class BaileysStartupService extends ChannelStartupService { avatar_url: contact.profilePicUrl, }); } - - return update; }), ); } @@ -865,13 +895,9 @@ export class BaileysStartupService extends ChannelStartupService { }, 'contacts.update': async (contacts: Partial[]) => { - const contactsRaw: { - remoteJid: string; - pushName?: string; - profilePicUrl?: string; - instanceId: string; - }[] = []; + const contactsRaw: { remoteJid: string; pushName?: string; profilePicUrl?: string; instanceId: string }[] = []; for await (const contact of contacts) { + this.logger.debug(`Updating contact: ${JSON.stringify(contact, null, 2)}`); contactsRaw.push({ remoteJid: contact.id, pushName: contact?.name ?? contact?.verifiedName, @@ -882,19 +908,18 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactsRaw); - const updateTransactions = contactsRaw.map((contact) => - this.prismaRepository.contact.upsert({ - where: { remoteJid_instanceId: { remoteJid: contact.remoteJid, instanceId: contact.instanceId } }, - create: contact, - update: contact, - }), - ); - await this.prismaRepository.$transaction(updateTransactions); - - const usersContacts = contactsRaw.filter((c) => c.remoteJid.includes('@s.whatsapp')); - if (usersContacts) { - await saveOnWhatsappCache(usersContacts.map((c) => ({ remoteJid: c.remoteJid }))); + if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) { + const updateTransactions = contactsRaw.map((contact) => + this.prismaRepository.contact.upsert({ + where: { remoteJid_instanceId: { remoteJid: contact.remoteJid, instanceId: contact.instanceId } }, + create: contact, + update: contact, + }), + ); + await this.prismaRepository.$transaction(updateTransactions); } + + //const usersContacts = contactsRaw.filter((c) => c.remoteJid.includes('@s.whatsapp')); }, }; @@ -909,7 +934,7 @@ export class BaileysStartupService extends ChannelStartupService { }: { chats: Chat[]; contacts: Contact[]; - messages: proto.IWebMessageInfo[]; + messages: WAMessage[]; isLatest?: boolean; progress?: number; syncType?: proto.HistorySync.HistorySyncType; @@ -941,13 +966,19 @@ export class BaileysStartupService extends ChannelStartupService { } } + const contactsMap = new Map(); + + for (const contact of contacts) { + if (contact.id && (contact.notify || contact.name)) { + contactsMap.set(contact.id, { name: contact.name ?? contact.notify, jid: contact.id }); + } + } + const chatsRaw: { remoteJid: string; instanceId: string; name?: string }[] = []; const chatsRepository = new Set( - ( - await this.prismaRepository.chat.findMany({ - where: { instanceId: this.instanceId }, - }) - ).map((chat) => chat.remoteJid), + (await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } })).map( + (chat) => chat.remoteJid, + ), ); for (const chat of chats) { @@ -955,25 +986,18 @@ export class BaileysStartupService extends ChannelStartupService { continue; } - chatsRaw.push({ - remoteJid: chat.id, - instanceId: this.instanceId, - name: chat.name, - }); + chatsRaw.push({ remoteJid: chat.id, instanceId: this.instanceId, name: chat.name }); } this.sendDataWebhook(Events.CHATS_SET, chatsRaw); if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - await this.prismaRepository.chat.createMany({ - data: chatsRaw, - skipDuplicates: true, - }); + await this.prismaRepository.chat.createMany({ data: chatsRaw, skipDuplicates: true }); } const messagesRaw: any[] = []; - const messagesRepository = new Set( + const messagesRepository: Set = new Set( chatwootImport.getRepositoryMessagesCache(instance) ?? ( await this.prismaRepository.message.findMany({ @@ -981,9 +1005,7 @@ export class BaileysStartupService extends ChannelStartupService { where: { instanceId: this.instanceId }, }) ).map((message) => { - const key = message.key as { - id: string; - }; + const key = message.key as { id: string }; return key.id; }), @@ -1012,16 +1034,25 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + if (!m.pushName && !m.key.fromMe) { + const participantJid = m.participant || m.key.participant || m.key.remoteJid; + if (participantJid && contactsMap.has(participantJid)) { + m.pushName = contactsMap.get(participantJid).name; + } else if (participantJid) { + m.pushName = participantJid.split('@')[0]; + } + } + messagesRaw.push(this.prepareMessage(m)); } - this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]); + this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw], true, undefined, { + isLatest, + progress, + }); if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - await this.prismaRepository.message.createMany({ - data: messagesRaw, - skipDuplicates: true, - }); + await this.prismaRepository.message.createMany({ data: messagesRaw, skipDuplicates: true }); } if ( @@ -1037,12 +1068,7 @@ export class BaileysStartupService extends ChannelStartupService { } await this.contactHandle['contacts.upsert']( - contacts - .filter((c) => !!c.notify || !!c.name) - .map((c) => ({ - id: c.id, - name: c.name ?? c.notify, - })), + contacts.filter((c) => !!c.notify || !!c.name).map((c) => ({ id: c.id, name: c.name ?? c.notify })), ); contacts = undefined; @@ -1054,19 +1080,28 @@ export class BaileysStartupService extends ChannelStartupService { }, 'messages.upsert': async ( - { - messages, - type, - requestId, - }: { - messages: proto.IWebMessageInfo[]; - type: MessageUpsertType; - requestId?: string; - }, + { messages, type, requestId }: { messages: WAMessage[]; type: MessageUpsertType; requestId?: string }, settings: any, ) => { try { for (const received of messages) { + if ( + received?.messageStubParameters?.some?.((param) => + [ + 'No matching sessions found for message', + 'Bad MAC', + 'failed to decrypt message', + 'SessionError', + 'Invalid PreKey ID', + 'No session record', + 'No session found to decrypt message', + 'Message absent from node', + ].some((err) => param?.includes?.(err)), + ) + ) { + this.logger.warn(`Message ignored with messageStubParameters: ${JSON.stringify(received, null, 2)}`); + continue; + } if (received.message?.conversation || received.message?.extendedTextMessage?.text) { const text = received.message?.conversation || received.message?.extendedTextMessage?.text; @@ -1084,45 +1119,51 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) { - const editedMessage = - received.message?.protocolMessage || received.message?.editedMessage?.message?.protocolMessage; - if (editedMessage) { - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) - this.chatwootService.eventWhatsapp( - 'messages.edit', - { instanceName: this.instance.name, instanceId: this.instance.id }, - editedMessage, - ); - - await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); - } - } + const editedMessage = + received?.message?.protocolMessage || received?.message?.editedMessage?.message?.protocolMessage; - if (received.messageStubParameters && received.messageStubParameters[0] === 'Message absent from node') { - this.logger.info(`Recovering message lost messageId: ${received.key.id}`); + if (editedMessage) { + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) + this.chatwootService.eventWhatsapp( + 'messages.edit', + { instanceName: this.instance.name, instanceId: this.instance.id }, + editedMessage, + ); - await this.baileysCache.set(received.key.id, { - message: received, - retry: 0, - }); + await this.sendDataWebhook(Events.MESSAGES_EDITED, editedMessage); - continue; - } + if (received.key?.id && editedMessage.key?.id) { + await this.baileysCache.set(`protocol_${received.key.id}`, editedMessage.key.id, 60 * 60 * 24); + } - const retryCache = (await this.baileysCache.get(received.key.id)) || null; + const oldMessage = await this.getMessage(editedMessage.key, true); + if ((oldMessage as any)?.id) { + const editedMessageTimestamp = Long.isLong(received?.messageTimestamp) + ? Math.floor(received?.messageTimestamp.toNumber()) + : Math.floor(received?.messageTimestamp as number); - if (retryCache) { - this.logger.info('Recovered message lost'); - await this.baileysCache.delete(received.key.id); + await this.prismaRepository.message.update({ + where: { id: (oldMessage as any).id }, + data: { + message: editedMessage.editedMessage as any, + messageTimestamp: editedMessageTimestamp, + status: 'EDITED', + }, + }); + await this.prismaRepository.messageUpdate.create({ + data: { + fromMe: editedMessage.key.fromMe, + keyId: editedMessage.key.id, + remoteJid: editedMessage.key.remoteJid, + status: 'EDITED', + instanceId: this.instanceId, + messageId: (oldMessage as any).id, + }, + }); + } } - if ( - (type !== 'notify' && type !== 'append') || - received.message?.protocolMessage || - received.message?.pollUpdateMessage || - !received?.message - ) { + if ((type !== 'notify' && type !== 'append') || editedMessage || !received?.message) { continue; } @@ -1133,28 +1174,136 @@ export class BaileysStartupService extends ChannelStartupService { if (settings?.groupsIgnore && received.key.remoteJid.includes('@g.us')) { continue; } + const existingChat = await this.prismaRepository.chat.findFirst({ where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, + select: { id: true, name: true }, }); - if (existingChat) { - const chatToInsert = { - remoteJid: received.key.remoteJid, - instanceId: this.instanceId, - name: received.pushName || '', - unreadMessages: 0, - }; - - this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); + if ( + existingChat && + received.pushName && + existingChat.name !== received.pushName && + received.pushName.trim().length > 0 && + !received.key.fromMe && + !received.key.remoteJid.includes('@g.us') + ) { + this.sendDataWebhook(Events.CHATS_UPSERT, [{ ...existingChat, name: received.pushName }]); if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - await this.prismaRepository.chat.create({ - data: chatToInsert, - }); + try { + await this.prismaRepository.chat.update({ + where: { id: existingChat.id }, + data: { name: received.pushName }, + }); + } catch { + console.log(`Chat insert record ignored: ${received.key.remoteJid} - ${this.instanceId}`); + } } } const messageRaw = this.prepareMessage(received); + if (messageRaw.messageType === 'pollUpdateMessage') { + const pollCreationKey = messageRaw.message.pollUpdateMessage.pollCreationMessageKey; + const pollMessage = (await this.getMessage(pollCreationKey, true)) as proto.IWebMessageInfo; + const pollMessageSecret = (await this.getMessage(pollCreationKey)) as any; + + if (pollMessage) { + const pollOptions = + (pollMessage.message as any).pollCreationMessage?.options || + (pollMessage.message as any).pollCreationMessageV3?.options || + []; + const pollVote = messageRaw.message.pollUpdateMessage.vote; + + const voterJid = received.key.fromMe + ? this.instance.wuid + : received.key.participant || received.key.remoteJid; + + let pollEncKey = pollMessageSecret?.messageContextInfo?.messageSecret; + + let successfulVoterJid = voterJid; + + if (typeof pollEncKey === 'string') { + pollEncKey = Buffer.from(pollEncKey, 'base64'); + } else if (pollEncKey?.type === 'Buffer' && Array.isArray(pollEncKey.data)) { + pollEncKey = Buffer.from(pollEncKey.data); + } + + if (Buffer.isBuffer(pollEncKey) && pollEncKey.length === 44) { + pollEncKey = Buffer.from(pollEncKey.toString('utf8'), 'base64'); + } + + if (pollVote.encPayload && pollEncKey) { + const creatorCandidates = [ + this.instance.wuid, + this.client.user?.lid, + pollMessage.key.participant, + (pollMessage.key as any).participantAlt, + pollMessage.key.remoteJid, + ]; + + const key = received.key as any; + const voterCandidates = [ + this.instance.wuid, + this.client.user?.lid, + key.participant, + key.participantAlt, + key.remoteJidAlt, + key.remoteJid, + ]; + + const uniqueCreators = [ + ...new Set(creatorCandidates.filter(Boolean).map((id) => jidNormalizedUser(id))), + ]; + const uniqueVoters = [...new Set(voterCandidates.filter(Boolean).map((id) => jidNormalizedUser(id)))]; + + let decryptedVote; + + for (const creator of uniqueCreators) { + for (const voter of uniqueVoters) { + try { + decryptedVote = decryptPollVote(pollVote, { + pollCreatorJid: creator, + pollMsgId: pollMessage.key.id, + pollEncKey, + voterJid: voter, + } as any); + if (decryptedVote) { + successfulVoterJid = voter; + break; + } + } catch { + // Continue trying + } + } + if (decryptedVote) break; + } + + if (decryptedVote) { + Object.assign(pollVote, decryptedVote); + } + } + + const selectedOptions = pollVote?.selectedOptions || []; + + const selectedOptionNames = pollOptions + .filter((option) => { + const hash = createHash('sha256').update(option.optionName).digest(); + return selectedOptions.some((selected) => Buffer.compare(selected, hash) === 0); + }) + .map((option) => option.optionName); + + messageRaw.message.pollUpdateMessage.vote.selectedOptions = selectedOptionNames; + + const pollUpdates = pollOptions.map((option) => ({ + name: option.optionName, + voters: selectedOptionNames.includes(option.optionName) ? [successfulVoterJid] : [], + })); + + messageRaw.pollUpdates = pollUpdates; + } + } + const isMedia = received?.message?.imageMessage || received?.message?.videoMessage || @@ -1164,6 +1313,8 @@ export class BaileysStartupService extends ChannelStartupService { received?.message?.ptvMessage || received?.message?.audioMessage; + const isVideo = received?.message?.videoMessage; + if (this.localSettings.readMessages && received.key.id !== 'status@broadcast') { await this.client.readMessages([received.key]); } @@ -1179,7 +1330,7 @@ export class BaileysStartupService extends ChannelStartupService { ) { const chatwootSentMessage = await this.chatwootService.eventWhatsapp( Events.MESSAGES_UPSERT, - { instanceName: this.instance.name, instanceId: this.instance.id }, + { instanceName: this.instance.name, instanceId: this.instanceId }, messageRaw, ); @@ -1192,81 +1343,97 @@ export class BaileysStartupService extends ChannelStartupService { if (this.configService.get('OPENAI').ENABLED && received?.message?.audioMessage) { const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: this.instanceId, - }, - include: { - OpenaiCreds: true, - }, + where: { instanceId: this.instanceId }, + include: { OpenaiCreds: true }, }); if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - received, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText(received, this)}`; } } if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { - const msg = await this.prismaRepository.message.create({ - data: messageRaw, - }); - - if (received.key.fromMe === false) { - if (msg.status === status[3]) { - this.logger.log(`Update not read messages ${received.key.remoteJid}`); - - await this.updateChatUnreadMessages(received.key.remoteJid); - } else if (msg.status === status[4]) { - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); - - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { pollUpdates, ...messageData } = messageRaw; + const msg = await this.prismaRepository.message.create({ data: messageData }); + + const { remoteJid } = received.key; + const timestamp = msg.messageTimestamp; + const fromMe = received.key.fromMe.toString(); + const messageKey = `${remoteJid}_${timestamp}_${fromMe}`; + + const cachedTimestamp = await this.baileysCache.get(messageKey); + + if (!cachedTimestamp) { + if (!received.key.fromMe) { + if (msg.status === status[3]) { + this.logger.log(`Update not read messages ${remoteJid}`); + await this.updateChatUnreadMessages(remoteJid); + } else if (msg.status === status[4]) { + this.logger.log(`Update readed messages ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); + } + } else { + // is send message by me + this.logger.log(`Update readed messages ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); } - } else { - // is send message by me - this.logger.log(`Update readed messages ${received.key.remoteJid} - ${msg.messageTimestamp}`); - await this.updateMessagesReadedByTimestamp(received.key.remoteJid, msg.messageTimestamp); + await this.baileysCache.set(messageKey, true, this.MESSAGE_CACHE_TTL_SECONDS); + } else { + this.logger.info(`Update readed messages duplicated ignored [avoid deadlock]: ${messageKey}`); } if (isMedia) { if (this.configService.get('S3').ENABLE) { try { + if (isVideo && !this.configService.get('S3').SAVE_VIDEO) { + this.logger.warn('Video upload is disabled. Skipping video upload.'); + // Skip video upload by returning early from this block + return; + } + const message: any = received; - const media = await this.getBase64FromMediaMessage( - { - message, - }, - true, - ); - const { buffer, mediaType, fileName, size } = media; - const mimetype = mime.getType(fileName).toString(); - const fullName = join(`${this.instance.id}`, received.key.remoteJid, mediaType, fileName); - await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { - 'Content-Type': mimetype, - }); - - await this.prismaRepository.media.create({ - data: { - messageId: msg.id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); - - const mediaUrl = await s3Service.getObjectUrl(fullName); - - messageRaw.message.mediaUrl = mediaUrl; - - await this.prismaRepository.message.update({ - where: { id: msg.id }, - data: messageRaw, - }); + // Verificação adicional para garantir que há conteúdo de mídia real + const hasRealMedia = this.hasValidMediaContent(message); + + if (!hasRealMedia) { + this.logger.warn('Message detected as media but contains no valid media content'); + } else { + const media = await this.getBase64FromMediaMessage({ message }, true); + + if (!media) { + this.logger.verbose('No valid media to upload (messageContextInfo only), skipping MinIO'); + return; + } + + const { buffer, mediaType, fileName, size } = media; + const mimetype = mimeTypes.lookup(fileName).toString(); + const fullName = join( + `${this.instance.id}`, + received.key.remoteJid, + mediaType, + `${Date.now()}_${fileName}`, + ); + await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { 'Content-Type': mimetype }); + + await this.prismaRepository.media.create({ + data: { + messageId: msg.id, + instanceId: this.instanceId, + type: mediaType, + fileName: fullName, + mimetype, + }, + }); + + const mediaUrl = await s3Service.getObjectUrl(fullName); + + messageRaw.message.mediaUrl = mediaUrl; + + await this.prismaRepository.message.update({ where: { id: msg.id }, data: messageRaw }); + } } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); } @@ -1276,21 +1443,42 @@ export class BaileysStartupService extends ChannelStartupService { if (this.localWebhook.enabled) { if (isMedia && this.localWebhook.webhookBase64) { - const buffer = await downloadMediaMessage( - { key: received.key, message: received?.message }, - 'buffer', - {}, - { - logger: P({ level: 'error' }) as any, - reuploadRequest: this.client.updateMediaMessage, - }, - ); + try { + const buffer = await downloadMediaMessage( + { key: received.key, message: received?.message }, + 'buffer', + {}, + { logger: P({ level: 'error' }) as any, reuploadRequest: this.client.updateMediaMessage }, + ); - messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } else { + // retry to download media + const buffer = await downloadMediaMessage( + { key: received.key, message: received?.message }, + 'buffer', + {}, + { logger: P({ level: 'error' }) as any, reuploadRequest: this.client.updateMediaMessage }, + ); + + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } + } + } catch (error) { + this.logger.error(['Error converting media to base64', error?.message]); + } } } - this.logger.log(messageRaw); + this.logger.verbose(messageRaw); + + sendTelemetry(`received.message.${messageRaw.messageType ?? 'unknown'}`); + if (messageRaw.key.remoteJid?.includes('@lid') && messageRaw.key.remoteJidAlt) { + messageRaw.key.remoteJid = messageRaw.key.remoteJidAlt; + } + console.log(messageRaw); this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw); @@ -1305,7 +1493,12 @@ export class BaileysStartupService extends ChannelStartupService { where: { remoteJid: received.key.remoteJid, instanceId: this.instanceId }, }); - const contactRaw: { remoteJid: string; pushName: string; profilePicUrl?: string; instanceId: string } = { + const contactRaw: { + remoteJid: string; + pushName: string; + profilePicUrl?: string; + instanceId: string; + } = { remoteJid: received.key.remoteJid, pushName: received.key.fromMe ? '' : received.key.fromMe == null ? '' : received.pushName, profilePicUrl: (await this.profilePicture(received.key.remoteJid)).profilePictureUrl, @@ -1316,6 +1509,17 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + if (contactRaw.remoteJid.includes('@s.whatsapp') || contactRaw.remoteJid.includes('@lid')) { + await saveOnWhatsappCache([ + { + remoteJid: + messageRaw.key.addressingMode === 'lid' ? messageRaw.key.remoteJidAlt : messageRaw.key.remoteJid, + remoteJidAlt: messageRaw.key.remoteJidAlt, + lid: messageRaw.key.addressingMode === 'lid' ? 'lid' : null, + }, + ]); + } + if (contact) { this.sendDataWebhook(Events.CONTACTS_UPDATE, contactRaw); @@ -1341,27 +1545,18 @@ export class BaileysStartupService extends ChannelStartupService { if (this.configService.get('DATABASE').SAVE_DATA.CONTACTS) await this.prismaRepository.contact.upsert({ - where: { - remoteJid_instanceId: { - remoteJid: contactRaw.remoteJid, - instanceId: contactRaw.instanceId, - }, - }, + where: { remoteJid_instanceId: { remoteJid: contactRaw.remoteJid, instanceId: contactRaw.instanceId } }, update: contactRaw, create: contactRaw, }); - - if (contactRaw.remoteJid.includes('@s.whatsapp')) { - await saveOnWhatsappCache([{ remoteJid: contactRaw.remoteJid }]); - } } } catch (error) { this.logger.error(error); } }, - 'messages.update': async (args: WAMessageUpdate[], settings: any) => { - this.logger.log(`Update messages ${JSON.stringify(args, undefined, 2)}`); + 'messages.update': async (args: { update: Partial; key: WAMessageKey }[], settings: any) => { + this.logger.verbose(`Update messages ${JSON.stringify(args, undefined, 2)}`); const readChatToUpdate: Record = {}; // {remoteJid: true} @@ -1370,6 +1565,27 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + const updateKey = `${this.instance.id}_${key.id}_${update.status}`; + + const cached = await this.baileysCache.get(updateKey); + + const secondsSinceEpoch = Math.floor(Date.now() / 1000); + console.log('CACHE:', { cached, updateKey, messageTimestamp: update.messageTimestamp, secondsSinceEpoch }); + + if ( + (update.messageTimestamp && update.messageTimestamp === cached) || + (!update.messageTimestamp && secondsSinceEpoch === cached) + ) { + this.logger.info(`Update Message duplicated ignored [avoid deadlock]: ${updateKey}`); + continue; + } + + if (update.messageTimestamp) { + await this.baileysCache.set(updateKey, update.messageTimestamp, 30 * 60); + } else { + await this.baileysCache.set(updateKey, secondsSinceEpoch, 30 * 60); + } + if (status[update.status] === 'READ' && key.fromMe) { if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( @@ -1380,7 +1596,7 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (key.remoteJid !== 'status@broadcast') { + if (key.remoteJid !== 'status@broadcast' && key.id !== undefined) { let pollUpdates: any; if (update.pollUpdates) { @@ -1394,37 +1610,53 @@ export class BaileysStartupService extends ChannelStartupService { } } - const findMessage = await this.prismaRepository.message.findFirst({ - where: { - instanceId: this.instanceId, - key: { - path: ['id'], - equals: key.id, - }, - }, - }); + const message: any = { + keyId: key.id, + remoteJid: key?.remoteJid, + fromMe: key.fromMe, + participant: key?.participant, + status: status[update.status] ?? 'SERVER_ACK', + pollUpdates, + instanceId: this.instanceId, + }; - if (!findMessage) { - continue; + if (update.message) { + message.message = update.message; + } + + let findMessage: any; + const configDatabaseData = this.configService.get('DATABASE').SAVE_DATA; + if (configDatabaseData.HISTORIC || configDatabaseData.NEW_MESSAGE) { + // Use raw SQL to avoid JSON path issues + const protocolMapKey = `protocol_${key.id}`; + const originalMessageId = (await this.baileysCache.get(protocolMapKey)) as string; + + if (originalMessageId) { + message.keyId = originalMessageId; + } + + const searchId = originalMessageId || key.id; + + const messages = (await this.prismaRepository.$queryRaw` + SELECT * FROM "Message" + WHERE "instanceId" = ${this.instanceId} + AND "key"->>'id' = ${searchId} + LIMIT 1 + `) as any[]; + findMessage = messages[0] || null; + + if (!findMessage?.id) { + this.logger.warn(`Original message not found for update. Skipping. Key: ${JSON.stringify(key)}`); + continue; + } + message.messageId = findMessage.id; } if (update.message === null && update.status === undefined) { - this.sendDataWebhook(Events.MESSAGES_DELETE, key); - - const message: any = { - messageId: findMessage.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: 'DELETED', - instanceId: this.instanceId, - }; + this.sendDataWebhook(Events.MESSAGES_DELETE, { ...key, status: 'DELETED' }); if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) - await this.prismaRepository.messageUpdate.create({ - data: message, - }); + await this.prismaRepository.messageUpdate.create({ data: message }); if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( @@ -1435,57 +1667,60 @@ export class BaileysStartupService extends ChannelStartupService { } continue; - } else if (update.status !== undefined && status[update.status] !== findMessage.status) { + } + + if (findMessage && update.status !== undefined && status[update.status] !== findMessage.status) { if (!key.fromMe && key.remoteJid) { readChatToUpdate[key.remoteJid] = true; - if (status[update.status] === status[4]) { - this.logger.log(`Update as read ${key.remoteJid} - ${findMessage.messageTimestamp}`); - this.updateMessagesReadedByTimestamp(key.remoteJid, findMessage.messageTimestamp); + const { remoteJid } = key; + const timestamp = findMessage.messageTimestamp; + const fromMe = key.fromMe.toString(); + const messageKey = `${remoteJid}_${timestamp}_${fromMe}`; + + const cachedTimestamp = await this.baileysCache.get(messageKey); + + if (!cachedTimestamp) { + if (status[update.status] === status[4]) { + this.logger.log(`Update as read in message.update ${remoteJid} - ${timestamp}`); + await this.updateMessagesReadedByTimestamp(remoteJid, timestamp); + await this.baileysCache.set(messageKey, true, this.MESSAGE_CACHE_TTL_SECONDS); + } + + await this.prismaRepository.message.update({ + where: { id: findMessage.id }, + data: { status: status[update.status] }, + }); + } else { + this.logger.info( + `Update readed messages duplicated ignored in message.update [avoid deadlock]: ${messageKey}`, + ); } } - - await this.prismaRepository.message.update({ - where: { id: findMessage.id }, - data: { status: status[update.status] }, - }); } - const message: any = { - messageId: findMessage.id, - keyId: key.id, - remoteJid: key.remoteJid, - fromMe: key.fromMe, - participant: key?.remoteJid, - status: status[update.status], - pollUpdates, - instanceId: this.instanceId, - }; - this.sendDataWebhook(Events.MESSAGES_UPDATE, message); - if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) - await this.prismaRepository.messageUpdate.create({ - data: message, - }); + if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { message: _msg, ...messageData } = message; + await this.prismaRepository.messageUpdate.create({ data: messageData }); + } const existingChat = await this.prismaRepository.chat.findFirst({ where: { instanceId: this.instanceId, remoteJid: message.remoteJid }, }); if (existingChat) { - const chatToInsert = { - remoteJid: message.remoteJid, - instanceId: this.instanceId, - name: message.pushName || '', - unreadMessages: 0, - }; + const chatToInsert = { remoteJid: message.remoteJid, instanceId: this.instanceId, unreadMessages: 0 }; this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]); if (this.configService.get('DATABASE').SAVE_DATA.CHATS) { - await this.prismaRepository.chat.create({ - data: chatToInsert, - }); + try { + await this.prismaRepository.chat.update({ where: { id: existingChat.id }, data: chatToInsert }); + } catch { + console.log(`Chat insert record ignored: ${chatToInsert.remoteJid} - ${chatToInsert.instanceId}`); + } } } } @@ -1510,22 +1745,76 @@ export class BaileysStartupService extends ChannelStartupService { }); }, - 'group-participants.update': (participantsUpdate: { + 'group-participants.update': async (participantsUpdate: { id: string; participants: string[]; action: ParticipantAction; }) => { - this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, participantsUpdate); + // ENHANCEMENT: Adds participantsData field while maintaining backward compatibility + // MAINTAINS: participants: string[] (original JID strings) + // ADDS: participantsData: { jid: string, phoneNumber: string, name?: string, imgUrl?: string }[] + // This enables LID to phoneNumber conversion without breaking existing webhook consumers + + // Helper to normalize participantId as phone number + const normalizePhoneNumber = (id: string | null | undefined): string => { + // Remove @lid, @s.whatsapp.net suffixes and extract just the number part + return String(id || '').split('@')[0]; + }; - this.updateGroupMetadataCache(participantsUpdate.id); - }, + try { + // Usa o mesmo método que o endpoint /group/participants + const groupParticipants = await this.findParticipants({ groupJid: participantsUpdate.id }); + + // Validação para garantir que temos dados válidos + if (!groupParticipants?.participants || !Array.isArray(groupParticipants.participants)) { + throw new Error('Invalid participant data received from findParticipants'); + } + + // Filtra apenas os participantes que estão no evento + const resolvedParticipants = participantsUpdate.participants.map((participantId) => { + const participantData = groupParticipants.participants.find((p) => p.id === participantId); + + let phoneNumber: string; + if (participantData?.phoneNumber) { + phoneNumber = participantData.phoneNumber; + } else { + phoneNumber = normalizePhoneNumber(participantId); + } + + return { + jid: participantId, + phoneNumber, + name: participantData?.name, + imgUrl: participantData?.imgUrl, + }; + }); + + // Mantém formato original + adiciona dados resolvidos + const enhancedParticipantsUpdate = { + ...participantsUpdate, + participants: participantsUpdate.participants, // Mantém array original de strings + // Adiciona dados resolvidos em campo separado + participantsData: resolvedParticipants, + }; + + this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, enhancedParticipantsUpdate); + } catch (error) { + this.logger.error( + `Failed to resolve participant data for GROUP_PARTICIPANTS_UPDATE webhook: ${error.message} | Group: ${participantsUpdate.id} | Participants: ${participantsUpdate.participants.length}`, + ); + // Fallback - envia sem conversão + this.sendDataWebhook(Events.GROUP_PARTICIPANTS_UPDATE, participantsUpdate); + } + + this.updateGroupMetadataCache(participantsUpdate.id); + }, }; private readonly labelHandle = { [Events.LABELS_EDIT]: async (label: Label) => { - const labelsRepository = await this.prismaRepository.label.findMany({ - where: { instanceId: this.instanceId }, - }); + this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name }); + + const labelsRepository = await this.prismaRepository.label.findMany({ where: { instanceId: this.instanceId } }); const savedLabel = labelsRepository.find((l) => l.labelId === label.id); if (label.deleted && savedLabel) { @@ -1547,17 +1836,11 @@ export class BaileysStartupService extends ChannelStartupService { instanceId: this.instanceId, }; await this.prismaRepository.label.upsert({ - where: { - labelId_instanceId: { - instanceId: labelData.instanceId, - labelId: labelData.labelId, - }, - }, + where: { labelId_instanceId: { instanceId: labelData.instanceId, labelId: labelData.labelId } }, update: labelData, create: labelData, }); } - this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name }); } }, @@ -1565,26 +1848,18 @@ export class BaileysStartupService extends ChannelStartupService { data: { association: LabelAssociation; type: 'remove' | 'add' }, database: Database, ) => { + this.logger.info( + `labels association - ${data?.association?.chatId} (${data.type}-${data?.association?.type}): ${data?.association?.labelId}`, + ); if (database.SAVE_DATA.CHATS) { - const chats = await this.prismaRepository.chat.findMany({ - where: { instanceId: this.instanceId }, - }); - const chat = chats.find((c) => c.remoteJid === data.association.chatId); - if (chat) { - const labelsArray = Array.isArray(chat.labels) ? chat.labels.map((event) => String(event)) : []; - let labels = [...labelsArray]; - - if (data.type === 'remove') { - labels = labels.filter((label) => label !== data.association.labelId); - } else if (data.type === 'add') { - labels = [...labels, data.association.labelId]; - } - await this.prismaRepository.chat.update({ - where: { id: chat.id }, - data: { - labels, - }, - }); + const instanceId = this.instanceId; + const chatId = data.association.chatId; + const labelId = data.association.labelId; + + if (data.type === 'add') { + await this.addLabel(labelId, instanceId, chatId); + } else if (data.type === 'remove') { + await this.removeLabel(labelId, instanceId, chatId); } } @@ -1599,135 +1874,141 @@ export class BaileysStartupService extends ChannelStartupService { private eventHandler() { this.client.ev.process(async (events) => { - if (!this.endSession) { - const database = this.configService.get('DATABASE'); - const settings = await this.findSettings(); - - if (events.call) { - const call = events.call[0]; + this.eventProcessingQueue = this.eventProcessingQueue.then(async () => { + try { + if (!this.endSession) { + const database = this.configService.get('DATABASE'); + const settings = await this.findSettings(); - if (settings?.rejectCall && call.status == 'offer') { - this.client.rejectCall(call.id, call.from); - } + if (events.call) { + const call = events.call[0]; - if (settings?.msgCall?.trim().length > 0 && call.status == 'offer') { - const msg = await this.client.sendMessage(call.from, { - text: settings.msgCall, - }); + if (settings?.rejectCall && call.status == 'offer') { + this.client.rejectCall(call.id, call.from); + } - this.client.ev.emit('messages.upsert', { - messages: [msg], - type: 'notify', - }); - } + if (settings?.msgCall?.trim().length > 0 && call.status == 'offer') { + if (call.from.endsWith('@lid')) { + call.from = await this.client.signalRepository.lidMapping.getPNForLID(call.from as string); + } + const msg = await this.client.sendMessage(call.from, { text: settings.msgCall }); - this.sendDataWebhook(Events.CALL, call); - } + this.client.ev.emit('messages.upsert', { messages: [msg], type: 'notify' }); + } - if (events['connection.update']) { - this.connectionUpdate(events['connection.update']); - } + this.sendDataWebhook(Events.CALL, call); + } - if (events['creds.update']) { - this.instance.authState.saveCreds(); - } + if (events['connection.update']) { + this.connectionUpdate(events['connection.update']); + } - if (events['messaging-history.set']) { - const payload = events['messaging-history.set']; - this.messageHandle['messaging-history.set'](payload); - } + if (events['creds.update']) { + this.instance.authState.saveCreds(); + } - if (events['messages.upsert']) { - const payload = events['messages.upsert']; - this.messageHandle['messages.upsert'](payload, settings); - } + if (events['messaging-history.set']) { + const payload = events['messaging-history.set']; + await this.messageHandle['messaging-history.set'](payload); + } - if (events['messages.update']) { - const payload = events['messages.update']; - this.messageHandle['messages.update'](payload, settings); - } + if (events['messages.upsert']) { + const payload = events['messages.upsert']; - if (events['message-receipt.update']) { - const payload = events['message-receipt.update'] as MessageUserReceiptUpdate[]; - const remotesJidMap: Record = {}; + // this.messageProcessor.processMessage(payload, settings); + await this.messageHandle['messages.upsert'](payload, settings); + } - for (const event of payload) { - if (typeof event.key.remoteJid === 'string' && typeof event.receipt.readTimestamp === 'number') { - remotesJidMap[event.key.remoteJid] = event.receipt.readTimestamp; + if (events['messages.update']) { + const payload = events['messages.update']; + await this.messageHandle['messages.update'](payload, settings); } - } - await Promise.all( - Object.keys(remotesJidMap).map(async (remoteJid) => - this.updateMessagesReadedByTimestamp(remoteJid, remotesJidMap[remoteJid]), - ), - ); - } + if (events['message-receipt.update']) { + const payload = events['message-receipt.update'] as MessageUserReceiptUpdate[]; + const remotesJidMap: Record = {}; - if (events['presence.update']) { - const payload = events['presence.update']; + for (const event of payload) { + if (typeof event.key.remoteJid === 'string' && typeof event.receipt.readTimestamp === 'number') { + remotesJidMap[event.key.remoteJid] = event.receipt.readTimestamp; + } + } - if (settings?.groupsIgnore && payload.id.includes('@g.us')) { - return; - } + await Promise.all( + Object.keys(remotesJidMap).map(async (remoteJid) => + this.updateMessagesReadedByTimestamp(remoteJid, remotesJidMap[remoteJid]), + ), + ); + } - this.sendDataWebhook(Events.PRESENCE_UPDATE, payload); - } + if (events['presence.update']) { + const payload = events['presence.update']; - if (!settings?.groupsIgnore) { - if (events['groups.upsert']) { - const payload = events['groups.upsert']; - this.groupHandler['groups.upsert'](payload); - } + if (settings?.groupsIgnore && payload.id.includes('@g.us')) { + return; + } - if (events['groups.update']) { - const payload = events['groups.update']; - this.groupHandler['groups.update'](payload); - } + this.sendDataWebhook(Events.PRESENCE_UPDATE, payload); + } - if (events['group-participants.update']) { - const payload = events['group-participants.update']; - this.groupHandler['group-participants.update'](payload); - } - } + if (!settings?.groupsIgnore) { + if (events['groups.upsert']) { + const payload = events['groups.upsert']; + this.groupHandler['groups.upsert'](payload); + } - if (events['chats.upsert']) { - const payload = events['chats.upsert']; - this.chatHandle['chats.upsert'](payload); - } + if (events['groups.update']) { + const payload = events['groups.update']; + this.groupHandler['groups.update'](payload); + } - if (events['chats.update']) { - const payload = events['chats.update']; - this.chatHandle['chats.update'](payload); - } + if (events['group-participants.update']) { + const payload = events['group-participants.update'] as any; + this.groupHandler['group-participants.update'](payload); + } + } - if (events['chats.delete']) { - const payload = events['chats.delete']; - this.chatHandle['chats.delete'](payload); - } + if (events['chats.upsert']) { + const payload = events['chats.upsert']; + this.chatHandle['chats.upsert'](payload); + } - if (events['contacts.upsert']) { - const payload = events['contacts.upsert']; - this.contactHandle['contacts.upsert'](payload); - } + if (events['chats.update']) { + const payload = events['chats.update']; + this.chatHandle['chats.update'](payload); + } - if (events['contacts.update']) { - const payload = events['contacts.update']; - this.contactHandle['contacts.update'](payload); - } + if (events['chats.delete']) { + const payload = events['chats.delete']; + this.chatHandle['chats.delete'](payload); + } - if (events[Events.LABELS_ASSOCIATION]) { - const payload = events[Events.LABELS_ASSOCIATION]; - this.labelHandle[Events.LABELS_ASSOCIATION](payload, database); - return; - } + if (events['contacts.upsert']) { + const payload = events['contacts.upsert']; + this.contactHandle['contacts.upsert'](payload); + } - if (events[Events.LABELS_EDIT]) { - const payload = events[Events.LABELS_EDIT]; - this.labelHandle[Events.LABELS_EDIT](payload); - return; + if (events['contacts.update']) { + const payload = events['contacts.update']; + this.contactHandle['contacts.update'](payload); + } + + if (events[Events.LABELS_ASSOCIATION]) { + const payload = events[Events.LABELS_ASSOCIATION]; + this.labelHandle[Events.LABELS_ASSOCIATION](payload, database); + return; + } + + if (events[Events.LABELS_EDIT]) { + const payload = events[Events.LABELS_EDIT]; + this.labelHandle[Events.LABELS_EDIT](payload); + return; + } + } + } catch (error) { + this.logger.error(error); } - } + }); }); } @@ -1762,41 +2043,29 @@ export class BaileysStartupService extends ChannelStartupService { } public async profilePicture(number: string) { - const jid = this.createJid(number); + const jid = createJid(number); try { const profilePictureUrl = await this.client.profilePictureUrl(jid, 'image'); - return { - wuid: jid, - profilePictureUrl, - }; - } catch (error) { - return { - wuid: jid, - profilePictureUrl: null, - }; + return { wuid: jid, profilePictureUrl }; + } catch { + return { wuid: jid, profilePictureUrl: null }; } } public async getStatus(number: string) { - const jid = this.createJid(number); + const jid = createJid(number); try { - return { - wuid: jid, - status: (await this.client.fetchStatus(jid))?.status, - }; - } catch (error) { - return { - wuid: jid, - status: null, - }; + return { wuid: jid, status: (await this.client.fetchStatus(jid))[0]?.status }; + } catch { + return { wuid: jid, status: null }; } } public async fetchProfile(instanceName: string, number?: string) { - const jid = number ? this.createJid(number) : this.client?.user?.id; + const jid = number ? createJid(number) : this.client?.user?.id; const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); @@ -1839,26 +2108,20 @@ export class BaileysStartupService extends ChannelStartupService { website: business?.website?.shift(), }; } - } catch (error) { - return { - wuid: jid, - name: null, - picture: null, - status: null, - os: null, - isBusiness: false, - }; + } catch { + return { wuid: jid, name: null, picture: null, status: null, os: null, isBusiness: false }; } } public async offerCall({ number, isVideo, callDuration }: OfferCallDto) { - const jid = this.createJid(number); + const jid = createJid(number); try { - const call = await this.client.offerCall(jid, isVideo); - setTimeout(() => this.client.terminateCall(call.id, call.to), callDuration * 1000); + // const call = await this.client.offerCall(jid, isVideo); + // setTimeout(() => this.client.terminateCall(call.id, call.to), callDuration * 1000); - return call; + // return call; + return { id: '123', jid, isVideo, callDuration }; } catch (error) { return error; } @@ -1872,13 +2135,12 @@ export class BaileysStartupService extends ChannelStartupService { quoted: any, messageId?: string, ephemeralExpiration?: number, + contextInfo?: any, // participants?: GroupParticipant[], ) { sender = sender.toLowerCase(); - const option: any = { - quoted, - }; + const option: any = { quoted }; if (isJidGroup(sender)) { option.useCachedGroupMetadata = true; @@ -1890,8 +2152,8 @@ export class BaileysStartupService extends ChannelStartupService { if (ephemeralExpiration) option.ephemeralExpiration = ephemeralExpiration; + // NOTE: NÃO DEVEMOS GERAR O messageId AQUI, SOMENTE SE VIER INFORMADO POR PARAMETRO. A GERAÇÃO ANTERIOR IMPEDE O WZAP DE IDENTIFICAR A SOURCE. if (messageId) option.messageId = messageId; - else option.messageId = '3EB0' + randomBytes(18).toString('hex').toUpperCase(); if (message['viewOnceMessage']) { const m = generateWAMessageFromContent(sender, message, { @@ -1901,12 +2163,7 @@ export class BaileysStartupService extends ChannelStartupService { quoted, }); const id = await this.client.relayMessage(sender, message, { messageId }); - m.key = { - id: id, - remoteJid: sender, - participant: isJidUser(sender) ? sender : undefined, - fromMe: true, - }; + m.key = { id: id, remoteJid: sender, participant: isPnUser(sender) ? sender : undefined, fromMe: true }; for (const [key, value] of Object.entries(m)) { if (!value || (isArray(value) && value.length) === 0) { delete m[key]; @@ -1926,16 +2183,17 @@ export class BaileysStartupService extends ChannelStartupService { return await this.client.sendMessage( sender, { - react: { - text: message['reactionMessage']['text'], - key: message['reactionMessage']['key'], - }, + react: { text: message['reactionMessage']['text'], key: message['reactionMessage']['key'] }, } as unknown as AnyMessageContent, option as unknown as MiscMessageGenerationOptions, ); } } + if (contextInfo) { + message['contextInfo'] = contextInfo; + } + if (message['conversation']) { return await this.client.sendMessage( sender, @@ -1943,6 +2201,7 @@ export class BaileysStartupService extends ChannelStartupService { text: message['conversation'], mentions, linkPreview: linkPreview, + contextInfo: message['contextInfo'], } as unknown as AnyMessageContent, option as unknown as MiscMessageGenerationOptions, ); @@ -1952,11 +2211,9 @@ export class BaileysStartupService extends ChannelStartupService { return await this.client.sendMessage( sender, { - forward: { - key: { remoteJid: this.instance.wuid, fromMe: true }, - message, - }, + forward: { key: { remoteJid: this.instance.wuid, fromMe: true }, message }, mentions, + contextInfo: message['contextInfo'], }, option as unknown as MiscMessageGenerationOptions, ); @@ -1966,14 +2223,7 @@ export class BaileysStartupService extends ChannelStartupService { let jidList; if (message['status'].option.allContacts) { const contacts = await this.prismaRepository.contact.findMany({ - where: { - instanceId: this.instanceId, - remoteJid: { - not: { - endsWith: '@g.us', - }, - }, - }, + where: { instanceId: this.instanceId, remoteJid: { not: { endsWith: '@g.us' } } }, }); jidList = contacts.map((contact) => contact.remoteJid); @@ -2095,7 +2345,7 @@ export class BaileysStartupService extends ChannelStartupService { if (options?.quoted) { const m = options?.quoted; - const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as proto.IWebMessageInfo); + const msg = m?.message ? m : ((await this.getMessage(m.key, true)) as WAMessage); if (msg) { quoted = msg; @@ -2105,13 +2355,16 @@ export class BaileysStartupService extends ChannelStartupService { let messageSent: WAMessage; let mentions: string[]; + let contextInfo: any; + if (isJidGroup(sender)) { let group; try { const cache = this.configService.get('CACHE'); if (!cache.REDIS.ENABLED && !cache.LOCAL.ENABLED) group = await this.findGroup({ groupJid: sender }, 'inner'); else group = await this.getGroupMetadataCache(sender); - } catch (error) { + // group = await this.findGroup({ groupJid: sender }, 'inner'); + } catch { throw new NotFoundException('Group not found'); } @@ -2121,9 +2374,9 @@ export class BaileysStartupService extends ChannelStartupService { if (options?.mentionsEveryOne) { mentions = group.participants.map((participant) => participant.id); - } else if (options.mentioned?.length) { + } else if (options?.mentioned?.length) { mentions = options.mentioned.map((mention) => { - const jid = this.createJid(mention); + const jid = createJid(mention); if (isJidGroup(jid)) { return null; } @@ -2142,7 +2395,27 @@ export class BaileysStartupService extends ChannelStartupService { // group?.participants, ); } else { - messageSent = await this.sendMessage(sender, message, mentions, linkPreview, quoted); + contextInfo = { + mentionedJid: [], + groupMentions: [], + //expiration: 7776000, + ephemeralSettingTimestamp: { + low: Math.floor(Date.now() / 1000) - 172800, + high: 0, + unsigned: false, + }, + disappearingMode: { initiator: 0 }, + }; + messageSent = await this.sendMessage( + sender, + message, + mentions, + linkPreview, + quoted, + null, + undefined, + contextInfo, + ); } if (Long.isLong(messageSent?.messageTimestamp)) { @@ -2161,6 +2434,8 @@ export class BaileysStartupService extends ChannelStartupService { messageSent?.message?.ptvMessage || messageSent?.message?.audioMessage; + const isVideo = messageSent?.message?.videoMessage; + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { this.chatwootService.eventWhatsapp( Events.SEND_MESSAGE, @@ -2171,72 +2446,63 @@ export class BaileysStartupService extends ChannelStartupService { if (this.configService.get('OPENAI').ENABLED && messageRaw?.message?.audioMessage) { const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ - where: { - instanceId: this.instanceId, - }, - include: { - OpenaiCreds: true, - }, + where: { instanceId: this.instanceId }, + include: { OpenaiCreds: true }, }); if (openAiDefaultSettings && openAiDefaultSettings.openaiCredsId && openAiDefaultSettings.speechToText) { - messageRaw.message.speechToText = await this.openaiService.speechToText( - openAiDefaultSettings.OpenaiCreds, - messageRaw, - this.client.updateMediaMessage, - ); + messageRaw.message.speechToText = `[audio] ${await this.openaiService.speechToText(messageRaw, this)}`; } } if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { - const msg = await this.prismaRepository.message.create({ - data: messageRaw, - }); + const msg = await this.prismaRepository.message.create({ data: messageRaw }); if (isMedia && this.configService.get('S3').ENABLE) { try { + if (isVideo && !this.configService.get('S3').SAVE_VIDEO) { + throw new Error('Video upload is disabled.'); + } + const message: any = messageRaw; - const media = await this.getBase64FromMediaMessage( - { - message, - }, - true, - ); - const { buffer, mediaType, fileName, size } = media; + // Verificação adicional para garantir que há conteúdo de mídia real + const hasRealMedia = this.hasValidMediaContent(message); + + if (!hasRealMedia) { + this.logger.warn('Message detected as media but contains no valid media content'); + } else { + const media = await this.getBase64FromMediaMessage({ message }, true); - const mimetype = mime.getType(fileName).toString(); + if (!media) { + this.logger.verbose('No valid media to upload (messageContextInfo only), skipping MinIO'); + return; + } - const fullName = join( - `${this.instance.id}`, - messageRaw.key.remoteJid, - `${messageRaw.key.id}`, - mediaType, - fileName, - ); + const { buffer, mediaType, fileName, size } = media; - await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { - 'Content-Type': mimetype, - }); + const mimetype = mimeTypes.lookup(fileName).toString(); - await this.prismaRepository.media.create({ - data: { - messageId: msg.id, - instanceId: this.instanceId, - type: mediaType, - fileName: fullName, - mimetype, - }, - }); + const fullName = join( + `${this.instance.id}`, + messageRaw.key.remoteJid, + `${messageRaw.key.id}`, + mediaType, + fileName, + ); + + await s3Service.uploadFile(fullName, buffer, size.fileLength?.low, { 'Content-Type': mimetype }); - const mediaUrl = await s3Service.getObjectUrl(fullName); + await this.prismaRepository.media.create({ + data: { messageId: msg.id, instanceId: this.instanceId, type: mediaType, fileName: fullName, mimetype }, + }); - messageRaw.message.mediaUrl = mediaUrl; + const mediaUrl = await s3Service.getObjectUrl(fullName); - await this.prismaRepository.message.update({ - where: { id: msg.id }, - data: messageRaw, - }); + messageRaw.message.mediaUrl = mediaUrl; + + await this.prismaRepository.message.update({ where: { id: msg.id }, data: messageRaw }); + } } catch (error) { this.logger.error(['Error on upload file to minio', error?.message, error?.stack]); } @@ -2245,21 +2511,36 @@ export class BaileysStartupService extends ChannelStartupService { if (this.localWebhook.enabled) { if (isMedia && this.localWebhook.webhookBase64) { - const buffer = await downloadMediaMessage( - { key: messageRaw.key, message: messageRaw?.message }, - 'buffer', - {}, - { - logger: P({ level: 'error' }) as any, - reuploadRequest: this.client.updateMediaMessage, - }, - ); + try { + const buffer = await downloadMediaMessage( + { key: messageRaw.key, message: messageRaw?.message }, + 'buffer', + {}, + { logger: P({ level: 'error' }) as any, reuploadRequest: this.client.updateMediaMessage }, + ); + + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } else { + // retry to download media + const buffer = await downloadMediaMessage( + { key: messageRaw.key, message: messageRaw?.message }, + 'buffer', + {}, + { logger: P({ level: 'error' }) as any, reuploadRequest: this.client.updateMediaMessage }, + ); - messageRaw.message.base64 = buffer ? buffer.toString('base64') : undefined; + if (buffer) { + messageRaw.message.base64 = buffer.toString('base64'); + } + } + } catch (error) { + this.logger.error(['Error converting media to base64', error?.message]); + } } } - this.logger.log(messageRaw); + this.logger.verbose(messageSent); this.sendDataWebhook(Events.SEND_MESSAGE, messageRaw); @@ -2354,9 +2635,7 @@ export class BaileysStartupService extends ChannelStartupService { return await this.sendMessageWithTyping( data.number, - { - conversation: data.text, - }, + { conversation: data.text }, { delay: data?.delay, presence: 'composing', @@ -2372,13 +2651,7 @@ export class BaileysStartupService extends ChannelStartupService { public async pollMessage(data: SendPollDto) { return await this.sendMessageWithTyping( data.number, - { - poll: { - name: data.name, - selectableCount: data.selectableCount, - values: data.values, - }, - }, + { poll: { name: data.name, selectableCount: data.selectableCount, values: data.values } }, { delay: data?.delay, presence: 'composing', @@ -2400,9 +2673,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (status.allContacts) { - const contacts = await this.prismaRepository.contact.findMany({ - where: { instanceId: this.instanceId }, - }); + const contacts = await this.prismaRepository.contact.findMany({ where: { instanceId: this.instanceId } }); if (!contacts.length) { throw new BadRequestException('Contacts not found'); @@ -2425,41 +2696,21 @@ export class BaileysStartupService extends ChannelStartupService { } return { - content: { - text: status.content, - }, - option: { - backgroundColor: status.backgroundColor, - font: status.font, - statusJidList: status.statusJidList, - }, + content: { text: status.content }, + option: { backgroundColor: status.backgroundColor, font: status.font, statusJidList: status.statusJidList }, }; } if (status.type === 'image') { return { - content: { - image: { - url: status.content, - }, - caption: status.caption, - }, - option: { - statusJidList: status.statusJidList, - }, + content: { image: { url: status.content }, caption: status.caption }, + option: { statusJidList: status.statusJidList }, }; } if (status.type === 'video') { return { - content: { - video: { - url: status.content, - }, - caption: status.caption, - }, - option: { - statusJidList: status.statusJidList, - }, + content: { video: { url: status.content }, caption: status.caption }, + option: { statusJidList: status.statusJidList }, }; } @@ -2467,14 +2718,8 @@ export class BaileysStartupService extends ChannelStartupService { const convert = await this.processAudioMp4(status.content); if (Buffer.isBuffer(convert)) { const result = { - content: { - audio: convert, - ptt: true, - mimetype: 'audio/ogg; codecs=opus', - }, - option: { - statusJidList: status.statusJidList, - }, + content: { audio: convert, ptt: true, mimetype: 'audio/ogg; codecs=opus' }, + option: { statusJidList: status.statusJidList }, }; return result; @@ -2493,9 +2738,7 @@ export class BaileysStartupService extends ChannelStartupService { const status = await this.formatStatusMessage(mediaData); - const statusSent = await this.sendMessageWithTyping('status@broadcast', { - status, - }); + const statusSent = await this.sendMessageWithTyping('status@broadcast', { status }); return statusSent; } @@ -2504,9 +2747,43 @@ export class BaileysStartupService extends ChannelStartupService { try { const type = mediaMessage.mediatype === 'ptv' ? 'video' : mediaMessage.mediatype; + let mediaInput: any; + if (mediaMessage.mediatype === 'image') { + let imageBuffer: Buffer; + if (isURL(mediaMessage.media)) { + let config: any = { responseType: 'arraybuffer' }; + + if (this.localProxy?.enabled) { + config = { + ...config, + httpsAgent: makeProxyAgent({ + host: this.localProxy.host, + port: this.localProxy.port, + protocol: this.localProxy.protocol, + username: this.localProxy.username, + password: this.localProxy.password, + }), + }; + } + + const response = await axios.get(mediaMessage.media, config); + imageBuffer = Buffer.from(response.data, 'binary'); + } else { + imageBuffer = Buffer.from(mediaMessage.media, 'base64'); + } + + mediaInput = await sharp(imageBuffer).jpeg().toBuffer(); + mediaMessage.fileName ??= 'image.jpg'; + mediaMessage.mimetype = 'image/jpeg'; + } else { + mediaInput = isURL(mediaMessage.media) + ? { url: mediaMessage.media } + : Buffer.from(mediaMessage.media, 'base64'); + } + const prepareMedia = await prepareWAMessageMedia( { - [type]: isURL(mediaMessage.media) ? { url: mediaMessage.media } : Buffer.from(mediaMessage.media, 'base64'), + [type]: mediaInput, } as any, { upload: this.client.waUploadToServer }, ); @@ -2520,24 +2797,22 @@ export class BaileysStartupService extends ChannelStartupService { } if (mediaMessage.mediatype === 'image' && !mediaMessage.fileName) { - mediaMessage.fileName = 'image.png'; + mediaMessage.fileName = 'image.jpg'; } if (mediaMessage.mediatype === 'video' && !mediaMessage.fileName) { mediaMessage.fileName = 'video.mp4'; } - let mimetype: string; + let mimetype: string | false; if (mediaMessage.mimetype) { mimetype = mediaMessage.mimetype; } else { - mimetype = mime.getType(mediaMessage.fileName); + mimetype = mimeTypes.lookup(mediaMessage.fileName); if (!mimetype && isURL(mediaMessage.media)) { - let config: any = { - responseType: 'arraybuffer', - }; + let config: any = { responseType: 'arraybuffer' }; if (this.localProxy?.enabled) { config = { @@ -2592,14 +2867,18 @@ export class BaileysStartupService extends ChannelStartupService { } } + if (mediaMessage?.fileName) { + mimetype = mimeTypes.lookup(mediaMessage.fileName).toString(); + if (mimetype === 'application/mp4') { + mimetype = 'video/mp4'; + } + } + prepareMedia[mediaType].caption = mediaMessage?.caption; prepareMedia[mediaType].mimetype = mimetype; prepareMedia[mediaType].fileName = mediaMessage.fileName; if (mediaMessage.mediatype === 'video') { - prepareMedia[mediaType].jpegThumbnail = Uint8Array.from( - readFileSync(join(process.cwd(), 'public', 'images', 'video-cover.png')), - ); prepareMedia[mediaType].gifPlayback = false; } @@ -2623,11 +2902,11 @@ export class BaileysStartupService extends ChannelStartupService { imageBuffer = Buffer.from(base64Data, 'base64'); } else { const timestamp = new Date().getTime(); - const url = `${image}?timestamp=${timestamp}`; + const parsedURL = new URL(image); + parsedURL.searchParams.set('timestamp', timestamp.toString()); + const url = parsedURL.toString(); - let config: any = { - responseType: 'arraybuffer', - }; + let config: any = { responseType: 'arraybuffer' }; if (this.localProxy?.enabled) { config = { @@ -2646,28 +2925,47 @@ export class BaileysStartupService extends ChannelStartupService { imageBuffer = Buffer.from(response.data, 'binary'); } - const webpBuffer = await sharp(imageBuffer).webp().toBuffer(); + const isAnimated = this.isAnimated(image, imageBuffer); - return webpBuffer; + if (isAnimated) { + return await sharp(imageBuffer, { animated: true }).webp({ quality: 80 }).toBuffer(); + } else { + return await sharp(imageBuffer).webp().toBuffer(); + } } catch (error) { console.error('Erro ao converter a imagem para WebP:', error); throw error; } } + private isAnimatedWebp(buffer: Buffer): boolean { + if (buffer.length < 12) return false; + + return buffer.indexOf(Buffer.from('ANIM')) !== -1; + } + + private isAnimated(image: string, buffer: Buffer): boolean { + const lowerCaseImage = image.toLowerCase(); + + if (lowerCaseImage.includes('.gif')) return true; + + if (lowerCaseImage.includes('.webp')) return this.isAnimatedWebp(buffer); + + return false; + } + public async mediaSticker(data: SendStickerDto, file?: any) { const mediaData: SendStickerDto = { ...data }; if (file) mediaData.sticker = file.buffer.toString('base64'); - const convert = await this.convertToWebP(data.sticker); + const convert = data?.notConvertSticker + ? Buffer.from(data.sticker, 'base64') + : await this.convertToWebP(data.sticker); const gifPlayback = data.sticker.includes('.gif'); const result = await this.sendMessageWithTyping( data.number, - { - sticker: convert, - gifPlayback, - }, + { sticker: convert, gifPlayback }, { delay: data?.delay, presence: 'composing', @@ -2802,7 +3100,8 @@ export class BaileysStartupService extends ChannelStartupService { } public async processAudio(audio: string): Promise { - if (process.env.API_AUDIO_CONVERTER) { + const audioConverterConfig = this.configService.get('AUDIO_CONVERTER'); + if (audioConverterConfig.API_URL) { this.logger.verbose('Using audio converter API'); const formData = new FormData(); @@ -2812,11 +3111,8 @@ export class BaileysStartupService extends ChannelStartupService { formData.append('base64', audio); } - const { data } = await axios.post(process.env.API_AUDIO_CONVERTER, formData, { - headers: { - ...formData.getHeaders(), - apikey: process.env.API_AUDIO_CONVERTER_KEY, - }, + const { data } = await axios.post(audioConverterConfig.API_URL, formData, { + headers: { ...formData.getHeaders(), apikey: audioConverterConfig.API_KEY }, }); if (!data.audio) { @@ -2830,11 +3126,11 @@ export class BaileysStartupService extends ChannelStartupService { if (isURL(audio)) { const timestamp = new Date().getTime(); - const url = `${audio}?timestamp=${timestamp}`; + const parsedURL = new URL(audio); + parsedURL.searchParams.set('timestamp', timestamp.toString()); + const url = parsedURL.toString(); - const config: any = { - responseType: 'stream', - }; + const config: any = { responseType: 'stream' }; const response = await axios.get(url, config); inputAudioStream = response.data.pipe(new PassThrough()); @@ -2844,6 +3140,8 @@ export class BaileysStartupService extends ChannelStartupService { inputAudioStream.end(audioBuffer); } + const isLpcm = isURL(audio) && /\.lpcm($|\?)/i.test(audio); + return new Promise((resolve, reject) => { const outputAudioStream = new PassThrough(); const chunks: Buffer[] = []; @@ -2861,12 +3159,41 @@ export class BaileysStartupService extends ChannelStartupService { ffmpeg.setFfmpegPath(ffmpegPath.path); - ffmpeg(inputAudioStream) + let command = ffmpeg(inputAudioStream); + + if (isLpcm) { + this.logger.verbose('Detected LPCM input – applying raw PCM settings'); + command = command.inputFormat('s16le').inputOptions(['-ar', '24000', '-ac', '1']); + } + + command .outputFormat('ogg') .noVideo() .audioCodec('libopus') .addOutputOptions('-avoid_negative_ts make_zero') + .audioBitrate('128k') + .audioFrequency(48000) .audioChannels(1) + .outputOptions([ + '-write_xing', + '0', + '-compression_level', + '10', + '-application', + 'voip', + '-fflags', + '+bitexact', + '-flags', + '+bitexact', + '-id3v2_version', + '0', + '-map_metadata', + '-1', + '-map_chapters', + '-1', + '-write_bext', + '0', + ]) .pipe(outputAudioStream, { end: true }) .on('error', function (error) { console.log('error', error); @@ -2896,11 +3223,7 @@ export class BaileysStartupService extends ChannelStartupService { if (Buffer.isBuffer(convert)) { const result = this.sendMessageWithTyping( data.number, - { - audio: convert, - ptt: true, - mimetype: 'audio/ogg; codecs=opus', - }, + { audio: convert, ptt: true, mimetype: 'audio/ogg; codecs=opus' }, { presence: 'recording', delay: data?.delay }, isIntegration, ); @@ -2939,41 +3262,19 @@ export class BaileysStartupService extends ChannelStartupService { call: () => toString({ display_text: button.displayText, phone_number: button.phoneNumber }), reply: () => toString({ display_text: button.displayText, id: button.id }), copy: () => toString({ display_text: button.displayText, copy_code: button.copyCode }), - url: () => - toString({ - display_text: button.displayText, - url: button.url, - merchant_url: button.url, - }), + url: () => toString({ display_text: button.displayText, url: button.url, merchant_url: button.url }), pix: () => toString({ currency: button.currency, - total_amount: { - value: 0, - offset: 100, - }, + total_amount: { value: 0, offset: 100 }, reference_id: this.generateRandomId(), type: 'physical-goods', order: { status: 'pending', - subtotal: { - value: 0, - offset: 100, - }, + subtotal: { value: 0, offset: 100 }, order_type: 'ORDER', items: [ - { - name: '', - amount: { - value: 0, - offset: 100, - }, - quantity: 0, - sale_amount: { - value: 0, - offset: 100, - }, - }, + { name: '', amount: { value: 0, offset: 100 }, quantity: 0, sale_amount: { value: 0, offset: 100 } }, ], }, payment_settings: [ @@ -3042,16 +3343,8 @@ export class BaileysStartupService extends ChannelStartupService { message: { interactiveMessage: { nativeFlowMessage: { - buttons: [ - { - name: this.mapType.get('pix'), - buttonParamsJson: this.toJSONString(data.buttons[0]), - }, - ], - messageParamsJson: JSON.stringify({ - from: 'api', - templateId: v4(), - }), + buttons: [{ name: this.mapType.get('pix'), buttonParamsJson: this.toJSONString(data.buttons[0]) }], + messageParamsJson: JSON.stringify({ from: 'api', templateId: v4() }), }, }, }, @@ -3069,18 +3362,12 @@ export class BaileysStartupService extends ChannelStartupService { const generate = await (async () => { if (data?.thumbnailUrl) { - return await this.prepareMediaMessage({ - mediatype: 'image', - media: data.thumbnailUrl, - }); + return await this.prepareMediaMessage({ mediatype: 'image', media: data.thumbnailUrl }); } })(); const buttons = data.buttons.map((value) => { - return { - name: this.mapType.get(value.type), - buttonParamsJson: this.toJSONString(value), - }; + return { name: this.mapType.get(value.type), buttonParamsJson: this.toJSONString(value) }; }); const message: proto.IMessage = { @@ -3098,9 +3385,7 @@ export class BaileysStartupService extends ChannelStartupService { return t; })(), }, - footer: { - text: data?.footer, - }, + footer: { text: data?.footer }, header: (() => { if (generate?.message?.imageMessage) { return { @@ -3111,10 +3396,7 @@ export class BaileysStartupService extends ChannelStartupService { })(), nativeFlowMessage: { buttons: buttons, - messageParamsJson: JSON.stringify({ - from: 'api', - templateId: v4(), - }), + messageParamsJson: JSON.stringify({ from: 'api', templateId: v4() }), }, }, }, @@ -3193,7 +3475,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (!contact.wuid) { - contact.wuid = this.createJid(contact.phoneNumber); + contact.wuid = createJid(contact.phoneNumber); } result += `item1.TEL;waid=${contact.wuid}:${contact.phoneNumber}\n` + 'item1.X-ABLabel:Celular\n' + 'END:VCARD'; @@ -3202,18 +3484,12 @@ export class BaileysStartupService extends ChannelStartupService { }; if (data.contact.length === 1) { - message.contactMessage = { - displayName: data.contact[0].fullName, - vcard: vcard(data.contact[0]), - }; + message.contactMessage = { displayName: data.contact[0].fullName, vcard: vcard(data.contact[0]) }; } else { message.contactsArrayMessage = { displayName: `${data.contact.length} contacts`, contacts: data.contact.map((contact) => { - return { - displayName: contact.fullName, - vcard: vcard(contact), - }; + return { displayName: contact.fullName, vcard: vcard(contact) }; }), }; } @@ -3223,10 +3499,7 @@ export class BaileysStartupService extends ChannelStartupService { public async reactionMessage(data: SendReactionDto) { return await this.sendMessageWithTyping(data.key.remoteJid, { - reactionMessage: { - key: data.key, - text: data.reaction, - }, + reactionMessage: { key: data.key, text: data.reaction }, }); } @@ -3236,14 +3509,10 @@ export class BaileysStartupService extends ChannelStartupService { groups: { number: string; jid: string }[]; broadcast: { number: string; jid: string }[]; users: { number: string; jid: string; name?: string }[]; - } = { - groups: [], - broadcast: [], - users: [], - }; + } = { groups: [], broadcast: [], users: [] }; data.numbers.forEach((number) => { - const jid = this.createJid(number); + const jid = createJid(number); if (isJidGroup(jid)) { jids.groups.push({ number, jid }); @@ -3265,46 +3534,68 @@ export class BaileysStartupService extends ChannelStartupService { const group = await this.findGroup({ groupJid: jid }, 'inner'); if (!group) { - new OnWhatsAppDto(jid, false, number); + return new OnWhatsAppDto(jid, false, number); } - return new OnWhatsAppDto(group.id, !!group?.id, number, group?.subject); + return new OnWhatsAppDto(group.id, true, number, group?.subject); }), ); onWhatsapp.push(...groups); // USERS const contacts: any[] = await this.prismaRepository.contact.findMany({ - where: { - instanceId: this.instanceId, - remoteJid: { - in: jids.users.map(({ jid }) => jid), - }, - }, + where: { instanceId: this.instanceId, remoteJid: { in: jids.users.map(({ jid }) => jid) } }, }); + // Unified cache verification for all numbers (normal and LID) const numbersToVerify = jids.users.map(({ jid }) => jid.replace('+', '')); + // Get all numbers from cache const cachedNumbers = await getOnWhatsappCache(numbersToVerify); - const filteredNumbers = numbersToVerify.filter( - (jid) => !cachedNumbers.some((cached) => cached.jidOptions.includes(jid)), - ); - const verify = await this.client.onWhatsApp(...filteredNumbers); - const users: OnWhatsAppDto[] = await Promise.all( - jids.users.map(async (user) => { - let numberVerified: (typeof verify)[0] | null = null; + // Separate numbers that are and are not in cache + const cachedJids = new Set(cachedNumbers.flatMap((cached) => cached.jidOptions)); + const numbersNotInCache = numbersToVerify.filter((jid) => !cachedJids.has(jid)); + + // Only call Baileys for normal numbers (@s.whatsapp.net) that are not in cache + let verify: { jid: string; exists: boolean }[] = []; + const normalNumbersNotInCache = numbersNotInCache.filter((jid) => !jid.includes('@lid')); + if (normalNumbersNotInCache.length > 0) { + this.logger.verbose(`Checking ${normalNumbersNotInCache.length} numbers via Baileys (not found in cache)`); + verify = await this.client.onWhatsApp(...normalNumbersNotInCache); + } + + const verifiedUsers = await Promise.all( + jids.users.map(async (user) => { + // Try to get from cache first (works for all: normal and LID) const cached = cachedNumbers.find((cached) => cached.jidOptions.includes(user.jid.replace('+', ''))); + if (cached) { - return { - exists: true, - jid: cached.remoteJid, - name: contacts.find((c) => c.remoteJid === cached.remoteJid)?.pushName, - number: user.number, - }; + this.logger.verbose(`Number ${user.number} found in cache`); + return new OnWhatsAppDto( + cached.remoteJid, + true, + user.number, + contacts.find((c) => c.remoteJid === cached.remoteJid)?.pushName, + cached.lid || (cached.remoteJid.includes('@lid') ? 'lid' : undefined), + ); + } + + // If it's a LID number and not in cache, consider it valid + if (user.jid.includes('@lid')) { + return new OnWhatsAppDto( + user.jid, + true, + user.number, + contacts.find((c) => c.remoteJid === user.jid)?.pushName, + 'lid', + ); } + // If not in cache and is a normal number, use Baileys verification + let numberVerified: (typeof verify)[0] | null = null; + // Brazilian numbers if (user.number.startsWith('55')) { const numberWithDigit = @@ -3324,7 +3615,7 @@ export class BaileysStartupService extends ChannelStartupService { if (!numberVerified && (user.number.startsWith('52') || user.number.startsWith('54'))) { let prefix = ''; if (user.number.startsWith('52')) { - prefix = ''; + prefix = '1'; } if (user.number.startsWith('54')) { prefix = '9'; @@ -3348,18 +3639,36 @@ export class BaileysStartupService extends ChannelStartupService { const numberJid = numberVerified?.jid || user.jid; - return { - exists: !!numberVerified?.exists, - jid: numberJid, - name: contacts.find((c) => c.remoteJid === numberJid)?.pushName, - number: user.number, - }; + return new OnWhatsAppDto( + numberJid, + !!numberVerified?.exists, + user.number, + contacts.find((c) => c.remoteJid === numberJid)?.pushName, + undefined, + ); }), ); - await saveOnWhatsappCache(users.filter((user) => user.exists).map((user) => ({ remoteJid: user.jid }))); + // Combine results + onWhatsapp.push(...verifiedUsers); - onWhatsapp.push(...users); + // TODO: Salvar no cache apenas números que NÃO estavam no cache + const numbersToCache = onWhatsapp.filter((user) => { + if (!user.exists) return false; + // Verifica se estava no cache usando jidOptions + const cached = cachedNumbers?.find((cached) => cached.jidOptions.includes(user.jid.replace('+', ''))); + return !cached; + }); + + if (numbersToCache.length > 0) { + this.logger.verbose(`Salvando ${numbersToCache.length} números no cache`); + await saveOnWhatsappCache( + numbersToCache.map((user) => ({ + remoteJid: user.jid, + lid: user.lid === 'lid' ? 'lid' : undefined, + })), + ); + } return onWhatsapp; } @@ -3368,12 +3677,8 @@ export class BaileysStartupService extends ChannelStartupService { try { const keys: proto.IMessageKey[] = []; data.readMessages.forEach((read) => { - if (isJidGroup(read.remoteJid) || isJidUser(read.remoteJid)) { - keys.push({ - remoteJid: read.remoteJid, - fromMe: read.fromMe, - id: read.id, - }); + if (isJidGroup(read.remoteJid) || isPnUser(read.remoteJid)) { + keys.push({ remoteJid: read.remoteJid, fromMe: read.fromMe, id: read.id }); } }); await this.client.readMessages(keys); @@ -3384,18 +3689,11 @@ export class BaileysStartupService extends ChannelStartupService { } public async getLastMessage(number: string) { - const where: any = { - key: { - remoteJid: number, - }, - instanceId: this.instance.id, - }; + const where: any = { key: { remoteJid: number }, instanceId: this.instance.id }; const messages = await this.prismaRepository.message.findMany({ where, - orderBy: { - messageTimestamp: 'desc', - }, + orderBy: { messageTimestamp: 'desc' }, take: 1, }); @@ -3431,18 +3729,9 @@ export class BaileysStartupService extends ChannelStartupService { throw new NotFoundException('Last message not found'); } - await this.client.chatModify( - { - archive: data.archive, - lastMessages: [last_message], - }, - this.createJid(number), - ); + await this.client.chatModify({ archive: data.archive, lastMessages: [last_message] }, createJid(number)); - return { - chatId: number, - archived: true, - }; + return { chatId: number, archived: true }; } catch (error) { throw new InternalServerErrorException({ archived: false, @@ -3468,18 +3757,9 @@ export class BaileysStartupService extends ChannelStartupService { throw new NotFoundException('Last message not found'); } - await this.client.chatModify( - { - markRead: false, - lastMessages: [last_message], - }, - this.createJid(number), - ); + await this.client.chatModify({ markRead: false, lastMessages: [last_message] }, createJid(number)); - return { - chatId: number, - markedChatUnread: true, - }; + return { chatId: number, markedChatUnread: true }; } catch (error) { throw new InternalServerErrorException({ markedChatUnread: false, @@ -3495,34 +3775,38 @@ export class BaileysStartupService extends ChannelStartupService { const messageId = response.message?.protocolMessage?.key?.id; if (messageId) { const isLogicalDeleted = configService.get('DATABASE').DELETE_DATA.LOGICAL_MESSAGE_DELETE; - let message = await this.prismaRepository.message.findUnique({ - where: { id: messageId }, + let message = await this.prismaRepository.message.findFirst({ + where: { key: { path: ['id'], equals: messageId } }, }); if (isLogicalDeleted) { if (!message) return response; const existingKey = typeof message?.key === 'object' && message.key !== null ? message.key : {}; message = await this.prismaRepository.message.update({ - where: { id: messageId }, - data: { - key: { - ...existingKey, - deleted: true, - }, - }, + where: { id: message.id }, + data: { key: { ...existingKey, deleted: true }, status: 'DELETED' }, }); + if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) { + const messageUpdate: any = { + messageId: message.id, + keyId: messageId, + remoteJid: response.key.remoteJid, + fromMe: response.key.fromMe, + participant: response.key?.participant, + status: 'DELETED', + instanceId: this.instanceId, + }; + await this.prismaRepository.messageUpdate.create({ data: messageUpdate }); + } } else { - await this.prismaRepository.message.deleteMany({ - where: { - id: messageId, - }, - }); + if (!message) return response; + await this.prismaRepository.message.deleteMany({ where: { id: message.id } }); } this.sendDataWebhook(Events.MESSAGES_DELETE, { id: message.id, instanceId: message.instanceId, key: message.key, messageType: message.messageType, - status: message.status, + status: 'DELETED', source: message.source, messageTimestamp: message.messageTimestamp, pushName: message.pushName, @@ -3538,6 +3822,18 @@ export class BaileysStartupService extends ChannelStartupService { } } + public async mapMediaType(mediaType) { + const map = { + imageMessage: 'image', + videoMessage: 'video', + documentMessage: 'document', + stickerMessage: 'sticker', + audioMessage: 'audio', + ptvMessage: 'video', + }; + return map[mediaType] || null; + } + public async getBase64FromMediaMessage(data: getBase64FromMediaMessageDto, getBuffer = false) { try { const m = data?.message; @@ -3555,37 +3851,87 @@ export class BaileysStartupService extends ChannelStartupService { } } + if ('messageContextInfo' in msg.message && Object.keys(msg.message).length === 1) { + this.logger.verbose('Message contains only messageContextInfo, skipping media processing'); + return null; + } + let mediaMessage: any; let mediaType: string; - for (const type of TypeMediaMessage) { - mediaMessage = msg.message[type]; - if (mediaMessage) { - mediaType = type; - break; + if (msg.message?.templateMessage) { + const template = + msg.message.templateMessage.hydratedTemplate || msg.message.templateMessage.hydratedFourRowTemplate; + + for (const type of TypeMediaMessage) { + if (template[type]) { + mediaMessage = template[type]; + mediaType = type; + msg.message = { [type]: { ...template[type], url: template[type].staticUrl } }; + break; + } + } + + if (!mediaMessage) { + throw 'Template message does not contain a supported media type'; + } + } else { + for (const type of TypeMediaMessage) { + mediaMessage = msg.message[type]; + if (mediaMessage) { + mediaType = type; + break; + } } - } - if (!mediaMessage) { - throw 'The message is not of the media type'; + if (!mediaMessage) { + throw 'The message is not of the media type'; + } } if (typeof mediaMessage['mediaKey'] === 'object') { - msg.message = JSON.parse(JSON.stringify(msg.message)); + msg.message[mediaType].mediaKey = Uint8Array.from(Object.values(mediaMessage['mediaKey'])); } - const buffer = await downloadMediaMessage( - { key: msg?.key, message: msg?.message }, - 'buffer', - {}, - { - logger: P({ level: 'error' }) as any, - reuploadRequest: this.client.updateMediaMessage, - }, - ); + let buffer: Buffer; + + try { + buffer = await downloadMediaMessage( + { key: msg?.key, message: msg?.message }, + 'buffer', + {}, + { logger: P({ level: 'error' }) as any, reuploadRequest: this.client.updateMediaMessage }, + ); + } catch { + this.logger.error('Download Media failed, trying to retry in 5 seconds...'); + await new Promise((resolve) => setTimeout(resolve, 5000)); + const mediaType = Object.keys(msg.message).find((key) => key.endsWith('Message')); + if (!mediaType) throw new Error('Could not determine mediaType for fallback'); + + try { + const media = await downloadContentFromMessage( + { + mediaKey: msg.message?.[mediaType]?.mediaKey, + directPath: msg.message?.[mediaType]?.directPath, + url: `https://mmg.whatsapp.net${msg?.message?.[mediaType]?.directPath}`, + }, + await this.mapMediaType(mediaType), + {}, + ); + const chunks = []; + for await (const chunk of media) { + chunks.push(chunk); + } + buffer = Buffer.concat(chunks); + this.logger.info('Download Media with downloadContentFromMessage was successful!'); + } catch (fallbackErr) { + this.logger.error('Download Media with downloadContentFromMessage also failed!'); + throw fallbackErr; + } + } const typeMessage = getContentType(msg.message); - const ext = mime.getExtension(mediaMessage?.['mimetype']); + const ext = mimeTypes.extension(mediaMessage?.['mimetype']); const fileName = mediaMessage?.['fileName'] || `${msg.key.id}.${ext}` || `${v4()}.${ext}`; if (convertToMp4 && typeMessage === 'audioMessage') { @@ -3620,11 +3966,7 @@ export class BaileysStartupService extends ChannelStartupService { mediaType, fileName, caption: mediaMessage['caption'], - size: { - fileLength: mediaMessage['fileLength'], - height: mediaMessage['height'], - width: mediaMessage['width'], - }, + size: { fileLength: mediaMessage['fileLength'], height: mediaMessage['height'], width: mediaMessage['width'] }, mimetype: mediaMessage['mimetype'], base64: buffer.toString('base64'), buffer: getBuffer ? buffer : null, @@ -3678,24 +4020,17 @@ export class BaileysStartupService extends ChannelStartupService { public async fetchBusinessProfile(number: string): Promise { try { - const jid = number ? this.createJid(number) : this.instance.wuid; + const jid = number ? createJid(number) : this.instance.wuid; const profile = await this.client.getBusinessProfile(jid); if (!profile) { const info = await this.whatsappNumber({ numbers: [jid] }); - return { - isBusiness: false, - message: 'Not is business profile', - ...info?.shift(), - }; + return { isBusiness: false, message: 'Not is business profile', ...info?.shift() }; } - return { - isBusiness: true, - ...profile, - }; + return { isBusiness: true, ...profile }; } catch (error) { throw new InternalServerErrorException('Error updating profile name', error.toString()); } @@ -3726,11 +4061,11 @@ export class BaileysStartupService extends ChannelStartupService { let pic: WAMediaUpload; if (isURL(picture)) { const timestamp = new Date().getTime(); - const url = `${picture}?timestamp=${timestamp}`; + const parsedURL = new URL(picture); + parsedURL.searchParams.set('timestamp', timestamp.toString()); + const url = parsedURL.toString(); - let config: any = { - responseType: 'arraybuffer', - }; + let config: any = { responseType: 'arraybuffer' }; if (this.localProxy?.enabled) { config = { @@ -3796,26 +4131,22 @@ export class BaileysStartupService extends ChannelStartupService { private async formatUpdateMessage(data: UpdateMessageDto) { try { + if (!this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + return data; + } + const msg: any = await this.getMessage(data.key, true); if (msg?.messageType === 'conversation' || msg?.messageType === 'extendedTextMessage') { - return { - text: data.text, - }; + return { text: data.text }; } if (msg?.messageType === 'imageMessage') { - return { - image: msg?.message?.imageMessage, - caption: data.text, - }; + return { image: msg?.message?.imageMessage, caption: data.text }; } if (msg?.messageType === 'videoMessage') { - return { - video: msg?.message?.videoMessage, - caption: data.text, - }; + return { video: msg?.message?.videoMessage, caption: data.text }; } return null; @@ -3826,7 +4157,7 @@ export class BaileysStartupService extends ChannelStartupService { } public async updateMessage(data: UpdateMessageDto) { - const jid = this.createJid(data.number); + const jid = createJid(data.number); const options = await this.formatUpdateMessage(data); @@ -3836,22 +4167,85 @@ export class BaileysStartupService extends ChannelStartupService { } try { - return await this.client.sendMessage(jid, { - ...(options as any), - edit: data.key, - }); + const oldMessage: any = await this.getMessage(data.key, true); + if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + if (!oldMessage) throw new NotFoundException('Message not found'); + if (oldMessage?.key?.remoteJid !== jid) { + throw new BadRequestException('RemoteJid does not match'); + } + if (oldMessage?.messageTimestamp > Date.now() + 900000) { + // 15 minutes in milliseconds + throw new BadRequestException('Message is older than 15 minutes'); + } + } + + const messageSent = await this.client.sendMessage(jid, { ...(options as any), edit: data.key }); + if (messageSent) { + const editedMessage = + messageSent?.message?.protocolMessage || messageSent?.message?.editedMessage?.message?.protocolMessage; + + if (editedMessage) { + this.sendDataWebhook(Events.SEND_MESSAGE_UPDATE, editedMessage); + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) + this.chatwootService.eventWhatsapp( + 'send.message.update', + { instanceName: this.instance.name, instanceId: this.instance.id }, + editedMessage, + ); + + const messageId = messageSent.message?.protocolMessage?.key?.id; + if (messageId && this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { + let message = await this.prismaRepository.message.findFirst({ + where: { key: { path: ['id'], equals: messageId } }, + }); + if (!message) throw new NotFoundException('Message not found'); + + if (!(message.key.valueOf() as any).fromMe) { + new BadRequestException('You cannot edit others messages'); + } + if ((message.key.valueOf() as any)?.deleted) { + new BadRequestException('You cannot edit deleted messages'); + } + + if (oldMessage.messageType === 'conversation' || oldMessage.messageType === 'extendedTextMessage') { + oldMessage.message.conversation = data.text; + } else { + oldMessage.message[oldMessage.messageType].caption = data.text; + } + message = await this.prismaRepository.message.update({ + where: { id: message.id }, + data: { + message: oldMessage.message, + status: 'EDITED', + messageTimestamp: Math.floor(Date.now() / 1000), // Convert to int32 by dividing by 1000 to get seconds + }, + }); + + if (this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) { + const messageUpdate: any = { + messageId: message.id, + keyId: messageId, + remoteJid: messageSent.key.remoteJid, + fromMe: messageSent.key.fromMe, + participant: messageSent.key?.participant, + status: 'EDITED', + instanceId: this.instanceId, + }; + await this.prismaRepository.messageUpdate.create({ data: messageUpdate }); + } + } + } + } + + return messageSent; } catch (error) { this.logger.error(error); - throw new BadRequestException(error.toString()); + throw error; } } public async fetchLabels(): Promise { - const labels = await this.prismaRepository.label.findMany({ - where: { - instanceId: this.instanceId, - }, - }); + const labels = await this.prismaRepository.label.findMany({ where: { instanceId: this.instanceId } }); return labels.map((label) => ({ color: label.color, @@ -3874,11 +4268,13 @@ export class BaileysStartupService extends ChannelStartupService { try { if (data.action === 'add') { await this.client.addChatLabel(contact.jid, data.labelId); + await this.addLabel(data.labelId, this.instanceId, contact.jid); return { numberJid: contact.jid, labelId: data.labelId, add: true }; } if (data.action === 'remove') { await this.client.removeChatLabel(contact.jid, data.labelId); + await this.removeLabel(data.labelId, this.instanceId, contact.jid); return { numberJid: contact.jid, labelId: data.labelId, remove: true }; } @@ -3896,10 +4292,7 @@ export class BaileysStartupService extends ChannelStartupService { if ((cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') || cacheConf?.LOCAL?.ENABLED) { this.logger.verbose(`Updating cache for group: ${groupJid}`); - await groupMetadataCache.set(groupJid, { - timestamp: Date.now(), - data: meta, - }); + await groupMetadataCache.set(groupJid, { timestamp: Date.now(), data: meta }); } return meta; @@ -3945,11 +4338,7 @@ export class BaileysStartupService extends ChannelStartupService { } if (create?.promoteParticipants) { - await this.updateGParticipant({ - groupJid: id, - action: 'promote', - participants: participants, - }); + await this.updateGParticipant({ groupJid: id, action: 'promote', participants: participants }); } const group = await this.client.groupMetadata(id); @@ -3966,11 +4355,11 @@ export class BaileysStartupService extends ChannelStartupService { let pic: WAMediaUpload; if (isURL(picture.image)) { const timestamp = new Date().getTime(); - const url = `${picture.image}?timestamp=${timestamp}`; + const parsedURL = new URL(picture.image); + parsedURL.searchParams.set('timestamp', timestamp.toString()); + const url = parsedURL.toString(); - let config: any = { - responseType: 'arraybuffer', - }; + let config: any = { responseType: 'arraybuffer' }; if (this.localProxy?.enabled) { config = { @@ -4103,7 +4492,7 @@ export class BaileysStartupService extends ChannelStartupService { public async inviteInfo(id: GroupInvite) { try { return await this.client.groupGetInviteInfo(id.inviteCode); - } catch (error) { + } catch { throw new NotFoundException('No invite info', id.inviteCode); } } @@ -4114,21 +4503,19 @@ export class BaileysStartupService extends ChannelStartupService { const inviteUrl = inviteCode.inviteUrl; - const numbers = id.numbers.map((number) => this.createJid(number)); + const numbers = id.numbers.map((number) => createJid(number)); const description = id.description ?? ''; const msg = `${description}\n\n${inviteUrl}`; - const message = { - conversation: msg, - }; + const message = { conversation: msg }; for await (const number of numbers) { await this.sendMessageWithTyping(number, message); } return { send: true, inviteUrl }; - } catch (error) { + } catch { throw new NotFoundException('No send invite'); } } @@ -4155,12 +4542,7 @@ export class BaileysStartupService extends ChannelStartupService { try { const participants = (await this.client.groupMetadata(id.groupJid)).participants; const contacts = await this.prismaRepository.contact.findMany({ - where: { - instanceId: this.instanceId, - remoteJid: { - in: participants.map((p) => p.id), - }, - }, + where: { instanceId: this.instanceId, remoteJid: { in: participants.map((p) => p.id) } }, }); const parsedParticipants = participants.map((participant) => { const contact = contacts.find((c) => c.remoteJid === participant.id); @@ -4185,7 +4567,7 @@ export class BaileysStartupService extends ChannelStartupService { public async updateGParticipant(update: GroupUpdateParticipantDto) { try { - const participants = update.participants.map((p) => this.createJid(p)); + const participants = update.participants.map((p) => createJid(p)); const updateParticipants = await this.client.groupParticipantsUpdate( update.groupJid, participants, @@ -4223,22 +4605,68 @@ export class BaileysStartupService extends ChannelStartupService { throw new BadRequestException('Unable to leave the group', error.toString()); } } + public async templateMessage() { throw new Error('Method not available in the Baileys service'); } + private deserializeMessageBuffers(obj: any): any { + if (obj === null || obj === undefined) { + return obj; + } + + if (typeof obj === 'object' && !Array.isArray(obj) && !Buffer.isBuffer(obj)) { + const keys = Object.keys(obj); + const isIndexedObject = keys.every((key) => !isNaN(Number(key))); + + if (isIndexedObject && keys.length > 0) { + const values = keys.sort((a, b) => Number(a) - Number(b)).map((key) => obj[key]); + return new Uint8Array(values); + } + } + + // Is Buffer?, converter to Uint8Array + if (Buffer.isBuffer(obj)) { + return new Uint8Array(obj); + } + + // Process arrays recursively + if (Array.isArray(obj)) { + return obj.map((item) => this.deserializeMessageBuffers(item)); + } + + // Process objects recursively + if (typeof obj === 'object') { + const converted: any = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + converted[key] = this.deserializeMessageBuffers(obj[key]); + } + } + return converted; + } + + return obj; + } + private prepareMessage(message: proto.IWebMessageInfo): any { const contentType = getContentType(message.message); const contentMsg = message?.message[contentType] as any; const messageRaw = { - key: message.key, - pushName: message.pushName, + key: message.key, // Save key exactly as it comes from Baileys + pushName: + message.pushName || + (message.key.fromMe + ? 'Você' + : message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)), status: status[message.status], - message: { ...message.message }, - contextInfo: contentMsg?.contextInfo, + message: this.deserializeMessageBuffers({ ...message.message }), + contextInfo: this.deserializeMessageBuffers(contentMsg?.contextInfo), messageType: contentType || 'unknown', - messageTimestamp: message.messageTimestamp as number, + messageTimestamp: Long.isLong(message.messageTimestamp) + ? message.messageTimestamp.toNumber() + : (message.messageTimestamp as number), instanceId: this.instanceId, source: getDevice(message.key.id), }; @@ -4259,6 +4687,19 @@ export class BaileysStartupService extends ChannelStartupService { delete messageRaw.message.documentWithCaptionMessage; } + const quotedMessage = messageRaw?.contextInfo?.quotedMessage; + if (quotedMessage) { + if (quotedMessage.extendedTextMessage) { + quotedMessage.conversation = quotedMessage.extendedTextMessage.text; + delete quotedMessage.extendedTextMessage; + } + + if (quotedMessage.documentWithCaptionMessage) { + quotedMessage.documentMessage = quotedMessage.documentWithCaptionMessage.message.documentMessage; + delete quotedMessage.documentWithCaptionMessage; + } + } + return messageRaw; } @@ -4268,7 +4709,22 @@ export class BaileysStartupService extends ChannelStartupService { const prepare = (message: any) => this.prepareMessage(message); this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare); + // Generate ID for this cron task and store in cache + const cronId = cuid(); + const cronKey = `chatwoot:syncLostMessages`; + await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId); + const task = cron.schedule('0,30 * * * *', async () => { + // Check ID before executing (only if cache is available) + const cache = this.chatwootService.getCache(); + if (cache) { + const storedId = await cache.hGet(cronKey, this.instance.name); + if (storedId && storedId !== cronId) { + this.logger.info(`Stopping syncChatwootLostMessages cron - ID mismatch: ${cronId} vs ${storedId}`); + task.stop(); + return; + } + } this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare); }); task.start(); @@ -4278,26 +4734,23 @@ export class BaileysStartupService extends ChannelStartupService { private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise { if (timestamp === undefined || timestamp === null) return 0; - const result = await this.prismaRepository.message.updateMany({ - where: { - AND: [ - { key: { path: ['remoteJid'], equals: remoteJid } }, - { key: { path: ['fromMe'], equals: false } }, - { messageTimestamp: { lte: timestamp } }, - { - OR: [{ status: null }, { status: status[3] }], - }, - ], - }, - data: { status: status[4] }, - }); + // Use raw SQL to avoid JSON path issues + const result = await this.prismaRepository.$executeRaw` + UPDATE "Message" + SET "status" = ${status[4]} + WHERE "instanceId" = ${this.instanceId} + AND "key"->>'remoteJid' = ${remoteJid} + AND ("key"->>'fromMe')::boolean = false + AND "messageTimestamp" <= ${timestamp} + AND ("status" IS NULL OR "status" = ${status[3]}) + `; if (result) { - if (result.count > 0) { + if (result > 0) { this.updateChatUnreadMessages(remoteJid); } - return result.count; + return result; } return 0; @@ -4306,24 +4759,364 @@ export class BaileysStartupService extends ChannelStartupService { private async updateChatUnreadMessages(remoteJid: string): Promise { const [chat, unreadMessages] = await Promise.all([ this.prismaRepository.chat.findFirst({ where: { remoteJid } }), - this.prismaRepository.message.count({ - where: { - AND: [ - { key: { path: ['remoteJid'], equals: remoteJid } }, - { key: { path: ['fromMe'], equals: false } }, - { status: { equals: status[3] } }, - ], - }, - }), + // Use raw SQL to avoid JSON path issues + this.prismaRepository.$queryRaw` + SELECT COUNT(*)::int as count FROM "Message" + WHERE "instanceId" = ${this.instanceId} + AND "key"->>'remoteJid' = ${remoteJid} + AND ("key"->>'fromMe')::boolean = false + AND "status" = ${status[3]} + `.then((result: any[]) => result[0]?.count || 0), ]); if (chat && chat.unreadMessages !== unreadMessages) { - await this.prismaRepository.chat.update({ - where: { id: chat.id }, - data: { unreadMessages }, - }); + await this.prismaRepository.chat.update({ where: { id: chat.id }, data: { unreadMessages } }); } return unreadMessages; } + + private async addLabel(labelId: string, instanceId: string, chatId: string) { + const id = cuid(); + + await this.prismaRepository.$executeRawUnsafe( + `INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt") + VALUES ($4, $2, $3, to_jsonb(ARRAY[$1]::text[]), NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid") + DO + UPDATE + SET "labels" = ( + SELECT to_jsonb(array_agg(DISTINCT elem)) + FROM ( + SELECT jsonb_array_elements_text("Chat"."labels") AS elem + UNION + SELECT $1::text AS elem + ) sub + ), + "updatedAt" = NOW();`, + labelId, + instanceId, + chatId, + id, + ); + } + + private async removeLabel(labelId: string, instanceId: string, chatId: string) { + const id = cuid(); + + await this.prismaRepository.$executeRawUnsafe( + `INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt") + VALUES ($4, $2, $3, '[]'::jsonb, NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid") + DO + UPDATE + SET "labels" = COALESCE ( + ( + SELECT jsonb_agg(elem) + FROM jsonb_array_elements_text("Chat"."labels") AS elem + WHERE elem <> $1 + ), + '[]'::jsonb + ), + "updatedAt" = NOW();`, + labelId, + instanceId, + chatId, + id, + ); + } + + public async baileysOnWhatsapp(jid: string) { + const response = await this.client.onWhatsApp(jid); + + return response; + } + + public async baileysProfilePictureUrl(jid: string, type: 'image' | 'preview', timeoutMs: number) { + const response = await this.client.profilePictureUrl(jid, type, timeoutMs); + + return response; + } + + public async baileysAssertSessions(jids: string[]) { + const response = await this.client.assertSessions(jids); + + return response; + } + + public async baileysCreateParticipantNodes(jids: string[], message: proto.IMessage, extraAttrs: any) { + const response = await this.client.createParticipantNodes(jids, message, extraAttrs); + + const convertedResponse = { + ...response, + nodes: response.nodes.map((node: any) => ({ + ...node, + content: node.content?.map((c: any) => ({ + ...c, + content: c.content instanceof Uint8Array ? Buffer.from(c.content).toString('base64') : c.content, + })), + })), + }; + + return convertedResponse; + } + + public async baileysSendNode(stanza: any) { + console.log('stanza', JSON.stringify(stanza)); + const response = await this.client.sendNode(stanza); + + return response; + } + + public async baileysGetUSyncDevices(jids: string[], useCache: boolean, ignoreZeroDevices: boolean) { + const response = await this.client.getUSyncDevices(jids, useCache, ignoreZeroDevices); + + return response; + } + + public async baileysGenerateMessageTag() { + const response = await this.client.generateMessageTag(); + + return response; + } + + public async baileysSignalRepositoryDecryptMessage(jid: string, type: 'pkmsg' | 'msg', ciphertext: string) { + try { + const ciphertextBuffer = Buffer.from(ciphertext, 'base64'); + + const response = await this.client.signalRepository.decryptMessage({ jid, type, ciphertext: ciphertextBuffer }); + + return response instanceof Uint8Array ? Buffer.from(response).toString('base64') : response; + } catch (error) { + this.logger.error('Error decrypting message:'); + this.logger.error(error); + throw error; + } + } + + public async baileysGetAuthState() { + const response = { me: this.client.authState.creds.me, account: this.client.authState.creds.account }; + + return response; + } + + //Business Controller + public async fetchCatalog(instanceName: string, data: getCollectionsDto) { + const jid = data.number ? createJid(data.number) : this.client?.user?.id; + const limit = data.limit || 10; + const cursor = null; + + const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + + if (!onWhatsapp.exists) { + throw new BadRequestException(onWhatsapp); + } + + try { + const info = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + const business = await this.fetchBusinessProfile(info?.jid); + + let catalog = await this.getCatalog({ jid: info?.jid, limit, cursor }); + let nextPageCursor = catalog.nextPageCursor; + let nextPageCursorJson = nextPageCursor ? JSON.parse(atob(nextPageCursor)) : null; + let pagination = nextPageCursorJson?.pagination_cursor + ? JSON.parse(atob(nextPageCursorJson.pagination_cursor)) + : null; + let fetcherHasMore = pagination?.fetcher_has_more === true ? true : false; + + let productsCatalog = catalog.products || []; + let countLoops = 0; + while (fetcherHasMore && countLoops < 4) { + catalog = await this.getCatalog({ jid: info?.jid, limit, cursor: nextPageCursor }); + nextPageCursor = catalog.nextPageCursor; + nextPageCursorJson = nextPageCursor ? JSON.parse(atob(nextPageCursor)) : null; + pagination = nextPageCursorJson?.pagination_cursor + ? JSON.parse(atob(nextPageCursorJson.pagination_cursor)) + : null; + fetcherHasMore = pagination?.fetcher_has_more === true ? true : false; + productsCatalog = [...productsCatalog, ...catalog.products]; + countLoops++; + } + + return { + wuid: info?.jid || jid, + numberExists: info?.exists, + isBusiness: business.isBusiness, + catalogLength: productsCatalog.length, + catalog: productsCatalog, + }; + } catch (error) { + console.log(error); + return { wuid: jid, name: null, isBusiness: false }; + } + } + + public async getCatalog({ + jid, + limit, + cursor, + }: GetCatalogOptions): Promise<{ products: Product[]; nextPageCursor: string | undefined }> { + try { + jid = jid ? createJid(jid) : this.instance.wuid; + + const catalog = await this.client.getCatalog({ jid, limit: limit, cursor: cursor }); + + if (!catalog) { + return { products: undefined, nextPageCursor: undefined }; + } + + return catalog; + } catch (error) { + throw new InternalServerErrorException('Error getCatalog', error.toString()); + } + } + + public async fetchCollections(instanceName: string, data: getCollectionsDto) { + const jid = data.number ? createJid(data.number) : this.client?.user?.id; + const limit = data.limit <= 20 ? data.limit : 20; //(tem esse limite, não sei porque) + + const onWhatsapp = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + + if (!onWhatsapp.exists) { + throw new BadRequestException(onWhatsapp); + } + + try { + const info = (await this.whatsappNumber({ numbers: [jid] }))?.shift(); + const business = await this.fetchBusinessProfile(info?.jid); + const collections = await this.getCollections(info?.jid, limit); + + return { + wuid: info?.jid || jid, + name: info?.name, + numberExists: info?.exists, + isBusiness: business.isBusiness, + collectionsLength: collections?.length, + collections: collections, + }; + } catch { + return { wuid: jid, name: null, isBusiness: false }; + } + } + + public async getCollections(jid?: string | undefined, limit?: number): Promise { + try { + jid = jid ? createJid(jid) : this.instance.wuid; + + const result = await this.client.getCollections(jid, limit); + + if (!result) { + return [{ id: undefined, name: undefined, products: [], status: undefined }]; + } + + return result.collections; + } catch (error) { + throw new InternalServerErrorException('Error getCatalog', error.toString()); + } + } + + public async fetchMessages(query: Query) { + const keyFilters = query?.where?.key as ExtendedIMessageKey; + + const timestampFilter = {}; + if (query?.where?.messageTimestamp) { + if (query.where.messageTimestamp['gte'] && query.where.messageTimestamp['lte']) { + timestampFilter['messageTimestamp'] = { + gte: Math.floor(new Date(query.where.messageTimestamp['gte']).getTime() / 1000), + lte: Math.floor(new Date(query.where.messageTimestamp['lte']).getTime() / 1000), + }; + } + } + + const count = await this.prismaRepository.message.count({ + where: { + instanceId: this.instanceId, + id: query?.where?.id, + source: query?.where?.source, + messageType: query?.where?.messageType, + ...timestampFilter, + AND: [ + keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, + keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, + keyFilters?.participant ? { key: { path: ['participant'], equals: keyFilters?.participant } } : {}, + { + OR: [ + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, + keyFilters?.remoteJidAlt ? { key: { path: ['remoteJidAlt'], equals: keyFilters?.remoteJidAlt } } : {}, + ], + }, + ], + }, + }); + + if (!query?.offset) { + query.offset = 50; + } + + if (!query?.page) { + query.page = 1; + } + + const messages = await this.prismaRepository.message.findMany({ + where: { + instanceId: this.instanceId, + id: query?.where?.id, + source: query?.where?.source, + messageType: query?.where?.messageType, + ...timestampFilter, + AND: [ + keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, + keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, + keyFilters?.participant ? { key: { path: ['participant'], equals: keyFilters?.participant } } : {}, + { + OR: [ + keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {}, + keyFilters?.remoteJidAlt ? { key: { path: ['remoteJidAlt'], equals: keyFilters?.remoteJidAlt } } : {}, + ], + }, + ], + }, + orderBy: { messageTimestamp: 'desc' }, + skip: query.offset * (query?.page === 1 ? 0 : (query?.page as number) - 1), + take: query.offset, + select: { + id: true, + key: true, + pushName: true, + messageType: true, + message: true, + messageTimestamp: true, + instanceId: true, + source: true, + contextInfo: true, + MessageUpdate: { select: { status: true } }, + }, + }); + + const formattedMessages = messages.map((message) => { + const messageKey = message.key as { fromMe: boolean; remoteJid: string; id: string; participant?: string }; + + if (!message.pushName) { + if (messageKey.fromMe) { + message.pushName = 'Você'; + } else if (message.contextInfo) { + const contextInfo = message.contextInfo as { participant?: string }; + if (contextInfo.participant) { + message.pushName = contextInfo.participant.split('@')[0]; + } else if (messageKey.participant) { + message.pushName = messageKey.participant.split('@')[0]; + } + } + } + + return message; + }); + + return { + messages: { + total: count, + pages: Math.ceil(count / query.offset), + currentPage: query.page, + records: formattedMessages, + }, + }; + } } diff --git a/src/api/integrations/chatbot/base-chatbot.controller.ts b/src/api/integrations/chatbot/base-chatbot.controller.ts new file mode 100644 index 000000000..a5b83e257 --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.controller.ts @@ -0,0 +1,950 @@ +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Events } from '@api/types/wa.types'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { TriggerOperator, TriggerType } from '@prisma/client'; +import { getConversationMessage } from '@utils/getConversationMessage'; + +import { BaseChatbotDto } from './base-chatbot.dto'; +import { ChatbotController, ChatbotControllerInterface, EmitData } from './chatbot.controller'; + +// Common settings interface for all chatbot integrations +export interface ChatbotSettings { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + debounceTime: number; + ignoreJids: string[]; + splitMessages: boolean; + timePerChar: number; + [key: string]: any; +} + +// Common bot properties for all chatbot integrations +export interface BaseBotData { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: string | TriggerType; + triggerOperator?: string | TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; + [key: string]: any; +} + +export abstract class BaseChatbotController + extends ChatbotController + implements ChatbotControllerInterface +{ + public readonly logger: Logger; + + integrationEnabled: boolean; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + // Name of the integration, to be set by the derived class + protected abstract readonly integrationName: string; + + // Method to process bot-specific logic + protected abstract processBot( + waInstance: any, + remoteJid: string, + bot: BotType, + session: any, + settings: ChatbotSettings, + content: string, + pushName?: string, + msg?: any, + ): Promise; + + // Method to get the fallback bot ID from settings + protected abstract getFallbackBotId(settings: any): string | undefined; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor); + + this.sessionRepository = this.prismaRepository.integrationSession; + } + + // Base create bot implementation + public async createBot(instance: InstanceDto, data: BotData) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // Set default settings if not provided + if ( + !data.expire || + !data.keywordFinish || + !data.delayMessage || + !data.unknownMessage || + !data.listeningFromMe || + !data.stopBotFromMe || + !data.keepOpen || + !data.debounceTime || + !data.ignoreJids || + !data.splitMessages || + !data.timePerChar + ) { + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck?.expire; + if (data.keywordFinish === undefined || data.keywordFinish === null) + data.keywordFinish = defaultSettingCheck?.keywordFinish; + if (data.delayMessage === undefined || data.delayMessage === null) + data.delayMessage = defaultSettingCheck?.delayMessage; + if (data.unknownMessage === undefined || data.unknownMessage === null) + data.unknownMessage = defaultSettingCheck?.unknownMessage; + if (data.listeningFromMe === undefined || data.listeningFromMe === null) + data.listeningFromMe = defaultSettingCheck?.listeningFromMe; + if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) + data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe; + if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck?.keepOpen; + if (data.debounceTime === undefined || data.debounceTime === null) + data.debounceTime = defaultSettingCheck?.debounceTime; + if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck?.ignoreJids; + if (data.splitMessages === undefined || data.splitMessages === null) + data.splitMessages = defaultSettingCheck?.splitMessages ?? false; + if (data.timePerChar === undefined || data.timePerChar === null) + data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; + + if (!defaultSettingCheck) { + await this.settings(instance, { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + }); + } + } + + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + instanceId: instanceId, + }, + }); + + if (checkTriggerAll && data.triggerType === 'all') { + throw new Error( + `You already have a ${this.integrationName} with an "All" trigger, you cannot have more bots while it is active`, + ); + } + + // Check for trigger keyword duplicates + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Check for trigger advanced duplicates + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Derived classes should implement the specific duplicate checking before calling this method + // and add bot-specific fields to the data object + + try { + const botData = { + enabled: data?.enabled, + description: data.description, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + ...this.getAdditionalBotData(data), + }; + + const bot = await this.botRepository.create({ + data: botData, + }); + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error creating ${this.integrationName}`); + } + } + + // Additional fields needed for specific bot types + protected abstract getAdditionalBotData(data: BotData): Record; + + // Common implementation for findBot + public async findBot(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + try { + const bots = await this.botRepository.findMany({ + where: { + instanceId: instanceId, + }, + }); + + return bots; + } catch (error) { + this.logger.error(error); + throw new Error(`Error finding ${this.integrationName}`); + } + } + + // Common implementation for fetchBot + public async fetchBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const bot = await this.botRepository.findUnique({ + where: { + id: botId, + }, + }); + + if (!bot) { + return null; + } + + return bot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error fetching ${this.integrationName}`); + } + } + + // Common implementation for settings + public async settings(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const existingSettings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + // Get the name of the fallback field for this integration type + const fallbackFieldName = this.getFallbackFieldName(); + + const settingsData = { + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + [fallbackFieldName]: data.fallbackId, // Use the correct field name dynamically + }; + + if (existingSettings) { + const settings = await this.settingsRepository.update({ + where: { + id: existingSettings.id, + }, + data: settingsData, + }); + + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings[fallbackFieldName], + }; + } else { + const settings = await this.settingsRepository.create({ + data: { + ...settingsData, + Instance: { + connect: { + id: instanceId, + }, + }, + }, + }); + + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings[fallbackFieldName], + }; + } + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Abstract method to get the field name for the fallback ID + protected abstract getFallbackFieldName(): string; + + // Abstract method to get the integration type (dify, n8n, evoai, etc.) + protected abstract getIntegrationType(): string; + + // Common implementation for fetchSettings + public async fetchSettings(instance: InstanceDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + include: { + Fallback: true, + }, + }); + + // Get the name of the fallback field for this integration type + const fallbackFieldName = this.getFallbackFieldName(); + + if (!settings) { + return { + expire: 300, + keywordFinish: 'bye', + delayMessage: 1000, + unknownMessage: 'Sorry, I dont understand', + listeningFromMe: true, + stopBotFromMe: true, + keepOpen: false, + debounceTime: 1, + ignoreJids: [], + splitMessages: false, + timePerChar: 0, + fallbackId: '', + fallback: null, + }; + } + + // Return with standardized fallbackId field + return { + ...settings, + fallbackId: settings[fallbackFieldName], + fallback: settings.Fallback, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching settings'); + } + } + + // Common implementation for changeStatus + public async changeStatus(instance: InstanceDto, data: any) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const defaultSettingCheck = await this.settingsRepository.findFirst({ + where: { + instanceId, + }, + }); + + const remoteJid = data.remoteJid; + const status = data.status; + const session = await this.getSession(remoteJid, instance); + + if (this.integrationName === 'Typebot') { + const typebotData = { + remoteJid: remoteJid, + status: status, + session, + }; + this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + } + + if (status === 'delete') { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + + return { bot: { remoteJid: remoteJid, status: status } }; + } + + if (status === 'closed') { + if (defaultSettingCheck?.keepOpen) { + await this.sessionRepository.updateMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.sessionRepository.deleteMany({ + where: { + remoteJid: remoteJid, + botId: { not: null }, + }, + }); + } + + return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; + } else { + const session = await this.sessionRepository.updateMany({ + where: { + instanceId: instanceId, + remoteJid: remoteJid, + botId: { not: null }, + }, + data: { + status: status, + }, + }); + + const botData = { + remoteJid: remoteJid, + status: status, + session, + }; + + return { bot: { ...instance, bot: botData } }; + } + } catch (error) { + this.logger.error(error); + throw new Error(`Error changing ${this.integrationName} status`); + } + } + + // Common implementation for fetchSessions + public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (bot && bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + // Get the integration type (dify, n8n, evoai, etc.) + const integrationType = this.getIntegrationType(); + + return await this.sessionRepository.findMany({ + where: { + instanceId: instanceId, + remoteJid, + botId: bot ? botId : { not: null }, + type: integrationType, + }, + }); + } catch (error) { + this.logger.error(error); + throw new Error('Error fetching sessions'); + } + } + + // Common implementation for ignoreJid + public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); + + if (!settings) { + throw new Error('Settings not found'); + } + + let ignoreJids: any = settings?.ignoreJids || []; + + if (data.action === 'add') { + if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; + + ignoreJids.push(data.remoteJid); + } else { + ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); + } + + const updateSettings = await this.settingsRepository.update({ + where: { + id: settings.id, + }, + data: { + ignoreJids: ignoreJids, + }, + }); + + return { + ignoreJids: updateSettings.ignoreJids, + }; + } catch (error) { + this.logger.error(error); + throw new Error('Error setting default settings'); + } + } + + // Base implementation for updateBot + public async updateBot(instance: InstanceDto, botId: string, data: BotData) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error(`${this.integrationName} not found`); + } + + if (bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + // Check for "all" trigger type conflicts + if (data.triggerType === 'all') { + const checkTriggerAll = await this.botRepository.findFirst({ + where: { + enabled: true, + triggerType: 'all', + id: { + not: botId, + }, + instanceId: instanceId, + }, + }); + + if (checkTriggerAll) { + throw new Error( + `You already have a ${this.integrationName} with an "All" trigger, you cannot have more bots while it is active`, + ); + } + } + + // Let subclasses check for integration-specific duplicates + await this.validateNoDuplicatesOnUpdate(botId, instanceId, data); + + // Check for keyword trigger duplicates + if (data.triggerType === 'keyword') { + if (!data.triggerOperator || !data.triggerValue) { + throw new Error('Trigger operator and value are required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Check for advanced trigger duplicates + if (data.triggerType === 'advanced') { + if (!data.triggerValue) { + throw new Error('Trigger value is required'); + } + + const checkDuplicate = await this.botRepository.findFirst({ + where: { + triggerValue: data.triggerValue, + id: { not: botId }, + instanceId: instanceId, + }, + }); + + if (checkDuplicate) { + throw new Error('Trigger already exists'); + } + } + + // Combine common fields with bot-specific fields + const updateData = { + enabled: data?.enabled, + description: data.description, + expire: data.expire, + keywordFinish: data.keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + instanceId: instanceId, + triggerType: data.triggerType, + triggerOperator: data.triggerOperator, + triggerValue: data.triggerValue, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + ...this.getAdditionalUpdateFields(data), + }; + + const updatedBot = await this.botRepository.update({ + where: { + id: botId, + }, + data: updateData, + }); + + return updatedBot; + } catch (error) { + this.logger.error(error); + throw new Error(`Error updating ${this.integrationName}`); + } + } + + // Abstract method for validating bot-specific duplicates on update + protected abstract validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: BotData): Promise; + + // Abstract method for getting additional fields for update + protected abstract getAdditionalUpdateFields(data: BotData): Record; + + // Base implementation for deleteBot + public async deleteBot(instance: InstanceDto, botId: string) { + if (!this.integrationEnabled) throw new BadRequestException(`${this.integrationName} is disabled`); + + try { + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + const bot = await this.botRepository.findFirst({ + where: { + id: botId, + }, + }); + + if (!bot) { + throw new Error(`${this.integrationName} not found`); + } + + if (bot.instanceId !== instanceId) { + throw new Error(`${this.integrationName} not found`); + } + + await this.prismaRepository.integrationSession.deleteMany({ + where: { + botId: botId, + }, + }); + + await this.botRepository.delete({ + where: { + id: botId, + }, + }); + + return { bot: { id: botId } }; + } catch (error) { + this.logger.error(error); + throw new Error(`Error deleting ${this.integrationName} bot`); + } + } + + // Base implementation for emit + public async emit({ instance, remoteJid, msg }: EmitData) { + if (!this.integrationEnabled) return; + + try { + const settings = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; + + const session = await this.getSession(remoteJid, instance); + + const content = getConversationMessage(msg); + + // Get integration type + // const integrationType = this.getIntegrationType(); + + // Find a bot for this message + let findBot: any = await this.findBotTrigger(this.botRepository, content, instance, session); + + // If no bot is found, try to use fallback + if (!findBot) { + const fallback = await this.settingsRepository.findFirst({ + where: { + instanceId: instance.instanceId, + }, + }); + + // Get the fallback ID for this integration type + const fallbackId = this.getFallbackBotId(fallback); + + if (fallbackId) { + const findFallback = await this.botRepository.findFirst({ + where: { + id: fallbackId, + }, + }); + + findBot = findFallback; + } else { + return; + } + } + + // If we still don't have a bot, return + if (!findBot) { + return; + } + + // Collect settings with fallbacks to default settings + let expire = findBot.expire; + let keywordFinish = findBot.keywordFinish; + let delayMessage = findBot.delayMessage; + let unknownMessage = findBot.unknownMessage; + let listeningFromMe = findBot.listeningFromMe; + let stopBotFromMe = findBot.stopBotFromMe; + let keepOpen = findBot.keepOpen; + let debounceTime = findBot.debounceTime; + let ignoreJids = findBot.ignoreJids; + let splitMessages = findBot.splitMessages; + let timePerChar = findBot.timePerChar; + + if (expire === undefined || expire === null) expire = settings.expire; + if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; + if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; + if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; + if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; + if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; + if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; + if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; + if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; + if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; + if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; + + const key = msg.key as { + id: string; + remoteJid: string; + fromMe: boolean; + participant: string; + }; + + // Handle stopping the bot if message is from me + if (stopBotFromMe && key.fromMe && session) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'paused', + }, + }); + + if (this.integrationName === 'Typebot') { + const typebotData = { + remoteJid: remoteJid, + status: 'paused', + session, + }; + this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + } + + return; + } + + // Skip if not listening to messages from me + if (!listeningFromMe && key.fromMe) { + return; + } + + // Skip if session exists but not awaiting user input + if (session && session.status === 'closed') { + return; + } + + // Merged settings + const mergedSettings = { + ...settings, + expire, + keywordFinish, + delayMessage, + unknownMessage, + listeningFromMe, + stopBotFromMe, + keepOpen, + debounceTime, + ignoreJids, + splitMessages, + timePerChar, + }; + + // Process with debounce if needed + if (debounceTime && debounceTime > 0) { + this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { + await this.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + mergedSettings, + debouncedContent, + msg?.pushName, + msg, + ); + }); + } else { + await this.processBot( + this.waMonitor.waInstances[instance.instanceName], + remoteJid, + findBot, + session, + mergedSettings, + content, + msg?.pushName, + msg, + ); + } + } catch (error) { + this.logger.error(error); + } + } +} diff --git a/src/api/integrations/chatbot/base-chatbot.dto.ts b/src/api/integrations/chatbot/base-chatbot.dto.ts new file mode 100644 index 000000000..7bc2e56a0 --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.dto.ts @@ -0,0 +1,42 @@ +import { TriggerOperator, TriggerType } from '@prisma/client'; + +/** + * Base DTO for all chatbot integrations + * Contains common properties shared by all chatbot types + */ +export class BaseChatbotDto { + enabled?: boolean; + description: string; + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + triggerType: TriggerType; + triggerOperator?: TriggerOperator; + triggerValue?: string; + ignoreJids?: string[]; + splitMessages?: boolean; + timePerChar?: number; +} + +/** + * Base settings DTO for all chatbot integrations + */ +export class BaseChatbotSettingDto { + expire?: number; + keywordFinish?: string; + delayMessage?: number; + unknownMessage?: string; + listeningFromMe?: boolean; + stopBotFromMe?: boolean; + keepOpen?: boolean; + debounceTime?: number; + ignoreJids?: any; + splitMessages?: boolean; + timePerChar?: number; + fallbackId?: string; // Unified fallback ID field for all integrations +} diff --git a/src/api/integrations/chatbot/base-chatbot.service.ts b/src/api/integrations/chatbot/base-chatbot.service.ts new file mode 100644 index 000000000..c3581c9b6 --- /dev/null +++ b/src/api/integrations/chatbot/base-chatbot.service.ts @@ -0,0 +1,419 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { IntegrationSession } from '@prisma/client'; + +/** + * Base class for all chatbot service implementations + * Contains common methods shared across different chatbot integrations + */ +export abstract class BaseChatbotService { + protected readonly logger: Logger; + protected readonly waMonitor: WAMonitoringService; + protected readonly prismaRepository: PrismaRepository; + protected readonly configService?: ConfigService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + loggerName: string, + configService?: ConfigService, + ) { + this.waMonitor = waMonitor; + this.prismaRepository = prismaRepository; + this.logger = new Logger(loggerName); + this.configService = configService; + } + + /** + * Check if a message contains an image + */ + protected isImageMessage(content: string): boolean { + return content.includes('imageMessage'); + } + + /** + * Check if a message contains audio + */ + protected isAudioMessage(content: string): boolean { + return content.includes('audioMessage'); + } + + /** + * Check if a string is valid JSON + */ + protected isJSON(str: string): boolean { + try { + JSON.parse(str); + return true; + } catch { + return false; + } + } + + /** + * Determine the media type from a URL based on its extension + */ + protected getMediaType(url: string): string | null { + const extension = url.split('.').pop()?.toLowerCase(); + const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; + const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; + const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; + const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; + + if (imageExtensions.includes(extension || '')) return 'image'; + if (audioExtensions.includes(extension || '')) return 'audio'; + if (videoExtensions.includes(extension || '')) return 'video'; + if (documentExtensions.includes(extension || '')) return 'document'; + return null; + } + + /** + * Create a new chatbot session + */ + public async createNewSession(instance: InstanceDto | any, data: any, type: string) { + try { + // Extract pushName safely - if data.pushName is an object with a pushName property, use that + const pushNameValue = + typeof data.pushName === 'object' && data.pushName?.pushName + ? data.pushName.pushName + : typeof data.pushName === 'string' + ? data.pushName + : null; + + // Extract remoteJid safely + const remoteJidValue = + typeof data.remoteJid === 'object' && data.remoteJid?.remoteJid ? data.remoteJid.remoteJid : data.remoteJid; + + const session = await this.prismaRepository.integrationSession.create({ + data: { + remoteJid: remoteJidValue, + pushName: pushNameValue, + sessionId: remoteJidValue, + status: 'opened', + awaitUser: false, + botId: data.botId, + instanceId: instance.instanceId, + type: type, + }, + }); + + return { session }; + } catch (error) { + this.logger.error(error); + return; + } + } + + /** + * Standard implementation for processing incoming messages + * This handles the common workflow across all chatbot types: + * 1. Check for existing session or create new one + * 2. Handle message based on session state + */ + public async process( + instance: any, + remoteJid: string, + bot: BotType, + session: IntegrationSession, + settings: SettingsType, + content: string, + pushName?: string, + msg?: any, + ): Promise { + try { + // For new sessions or sessions awaiting initialization + if (!session) { + await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName, msg); + return; + } + + // If session is paused, ignore the message + if (session.status === 'paused') { + return; + } + + // For existing sessions, keywords might indicate the conversation should end + const keywordFinish = (settings as any)?.keywordFinish || ''; + const normalizedContent = content.toLowerCase().trim(); + if (keywordFinish.length > 0 && normalizedContent === keywordFinish.toLowerCase()) { + // Update session to closed and return + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + return; + } + + // Forward the message to the chatbot API + await this.sendMessageToBot(instance, session, settings, bot, remoteJid, pushName || '', content, msg); + + // Update session to indicate we're waiting for user response + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(`Error in process: ${error}`); + return; + } + } + + /** + * Standard implementation for sending messages to WhatsApp + * This handles common patterns like markdown links and formatting + */ + protected async sendMessageWhatsApp( + instance: any, + remoteJid: string, + message: string, + settings: SettingsType, + linkPreview: boolean = true, + ): Promise { + if (!message) return; + + const linkRegex = /!?\[(.*?)\]\((.*?)\)/g; + let textBuffer = ''; + let lastIndex = 0; + let match: RegExpExecArray | null; + + const splitMessages = (settings as any)?.splitMessages ?? false; + + while ((match = linkRegex.exec(message)) !== null) { + const [fullMatch, altText, url] = match; + const mediaType = this.getMediaType(url); + const beforeText = message.slice(lastIndex, match.index); + + if (beforeText) { + textBuffer += beforeText; + } + + if (mediaType) { + // Send accumulated text before sending media + if (textBuffer.trim()) { + await this.sendFormattedText(instance, remoteJid, textBuffer.trim(), settings, splitMessages, linkPreview); + textBuffer = ''; + } + + // Handle sending the media + try { + if (mediaType === 'audio') { + await instance.audioWhatsapp({ + number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0], + delay: (settings as any)?.delayMessage || 1000, + audio: url, + caption: altText, + }); + } else { + await instance.mediaMessage( + { + number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0], + delay: (settings as any)?.delayMessage || 1000, + mediatype: mediaType, + media: url, + caption: altText, + fileName: mediaType === 'document' ? altText || 'document' : undefined, + }, + null, + false, + ); + } + } catch (error) { + this.logger.error(`Error sending media: ${error}`); + // If media fails, at least send the alt text and URL + textBuffer += `${altText}: ${url}`; + } + } else { + // It's a regular link, keep it in the text + textBuffer += fullMatch; + } + + lastIndex = linkRegex.lastIndex; + } + + // Add any remaining text after the last match + if (lastIndex < message.length) { + const remainingText = message.slice(lastIndex); + if (remainingText.trim()) { + textBuffer += remainingText; + } + } + + // Send any remaining text + if (textBuffer.trim()) { + await this.sendFormattedText(instance, remoteJid, textBuffer.trim(), settings, splitMessages, linkPreview); + } + } + + /** + * Split message by double line breaks and return array of message parts + */ + private splitMessageByDoubleLineBreaks(message: string): string[] { + return message.split('\n\n').filter((part) => part.trim().length > 0); + } + + /** + * Send a single message with proper typing indicators and delays + */ + private async sendSingleMessage( + instance: any, + remoteJid: string, + message: string, + settings: any, + linkPreview: boolean = true, + ): Promise { + const timePerChar = settings?.timePerChar ?? 0; + const minDelay = 1000; + const maxDelay = 20000; + const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); + + this.logger.debug(`[BaseChatbot] Sending single message with linkPreview: ${linkPreview}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + await new Promise((resolve) => { + setTimeout(async () => { + await instance.textMessage( + { + number: remoteJid.includes('@lid') ? remoteJid : remoteJid.split('@')[0], + delay: settings?.delayMessage || 1000, + text: message, + linkPreview, + }, + false, + ); + resolve(); + }, delay); + }); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); + } + } + + /** + * Helper method to send formatted text with proper typing indicators and delays + */ + private async sendFormattedText( + instance: any, + remoteJid: string, + text: string, + settings: any, + splitMessages: boolean, + linkPreview: boolean = true, + ): Promise { + if (splitMessages) { + const messageParts = this.splitMessageByDoubleLineBreaks(text); + + this.logger.debug(`[BaseChatbot] Splitting message into ${messageParts.length} parts`); + + for (let index = 0; index < messageParts.length; index++) { + const message = messageParts[index]; + + this.logger.debug(`[BaseChatbot] Sending message part ${index + 1}/${messageParts.length}`); + await this.sendSingleMessage(instance, remoteJid, message, settings, linkPreview); + } + + this.logger.debug(`[BaseChatbot] All message parts sent successfully`); + } else { + this.logger.debug(`[BaseChatbot] Sending single message`); + await this.sendSingleMessage(instance, remoteJid, text, settings, linkPreview); + } + } + + /** + * Standard implementation for initializing a new session + * This method should be overridden if a subclass needs specific initialization + */ + protected async initNewSession( + instance: any, + remoteJid: string, + bot: BotType, + settings: SettingsType, + session: IntegrationSession, + content: string, + pushName?: string | any, + msg?: any, + ): Promise { + // Create a session if none exists + if (!session) { + // Extract pushName properly - if it's an object with pushName property, use that + const pushNameValue = + typeof pushName === 'object' && pushName?.pushName + ? pushName.pushName + : typeof pushName === 'string' + ? pushName + : null; + + const sessionResult = await this.createNewSession( + { + instanceName: instance.instanceName, + instanceId: instance.instanceId, + }, + { + remoteJid, + pushName: pushNameValue, + botId: (bot as any).id, + }, + this.getBotType(), + ); + + if (!sessionResult || !sessionResult.session) { + this.logger.error('Failed to create new session'); + return; + } + + session = sessionResult.session; + } + + // Update session status to opened + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: false, + }, + }); + + // Forward the message to the chatbot + await this.sendMessageToBot(instance, session, settings, bot, remoteJid, pushName || '', content, msg); + } + + /** + * Get the bot type identifier (e.g., 'dify', 'n8n', 'evoai') + * This should match the type field used in the IntegrationSession + */ + protected abstract getBotType(): string; + + /** + * Send a message to the chatbot API + * This is specific to each chatbot integration + */ + protected abstract sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: SettingsType, + bot: BotType, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise; +} diff --git a/src/api/integrations/chatbot/chatbot.controller.ts b/src/api/integrations/chatbot/chatbot.controller.ts index 2db9a654e..74f1427a9 100644 --- a/src/api/integrations/chatbot/chatbot.controller.ts +++ b/src/api/integrations/chatbot/chatbot.controller.ts @@ -2,8 +2,10 @@ import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { difyController, + evoaiController, evolutionBotController, flowiseController, + n8nController, openaiController, typebotController, } from '@api/server.module'; @@ -89,15 +91,19 @@ export class ChatbotController { pushName, isIntegration, }; - await evolutionBotController.emit(emitData); + evolutionBotController.emit(emitData); - await typebotController.emit(emitData); + typebotController.emit(emitData); - await openaiController.emit(emitData); + openaiController.emit(emitData); - await difyController.emit(emitData); + difyController.emit(emitData); - await flowiseController.emit(emitData); + n8nController.emit(emitData); + + evoaiController.emit(emitData); + + flowiseController.emit(emitData); } public processDebounce( @@ -173,7 +179,7 @@ export class ChatbotController { if (session) { if (session.status !== 'closed' && !session.botId) { this.logger.warn('Session is already opened in another integration'); - return; + return null; } else if (!session.botId) { session = null; } @@ -184,18 +190,17 @@ export class ChatbotController { public async findBotTrigger( botRepository: any, - settingsRepository: any, content: string, instance: InstanceDto, session?: IntegrationSession, ) { - let findBot: null; + let findBot: any = null; if (!session) { - findBot = await findBotByTrigger(botRepository, settingsRepository, content, instance.instanceId); + findBot = await findBotByTrigger(botRepository, content, instance.instanceId); if (!findBot) { - return; + return null; } } else { findBot = await botRepository.findFirst({ diff --git a/src/api/integrations/chatbot/chatbot.router.ts b/src/api/integrations/chatbot/chatbot.router.ts index 19fc74b7c..10a52083e 100644 --- a/src/api/integrations/chatbot/chatbot.router.ts +++ b/src/api/integrations/chatbot/chatbot.router.ts @@ -4,8 +4,10 @@ import { OpenaiRouter } from '@api/integrations/chatbot/openai/routes/openai.rou import { TypebotRouter } from '@api/integrations/chatbot/typebot/routes/typebot.router'; import { Router } from 'express'; +import { EvoaiRouter } from './evoai/routes/evoai.router'; import { EvolutionBotRouter } from './evolutionBot/routes/evolutionBot.router'; import { FlowiseRouter } from './flowise/routes/flowise.router'; +import { N8nRouter } from './n8n/routes/n8n.router'; export class ChatbotRouter { public readonly router: Router; @@ -19,5 +21,7 @@ export class ChatbotRouter { this.router.use('/openai', new OpenaiRouter(...guards).router); this.router.use('/dify', new DifyRouter(...guards).router); this.router.use('/flowise', new FlowiseRouter(...guards).router); + this.router.use('/n8n', new N8nRouter(...guards).router); + this.router.use('/evoai', new EvoaiRouter(...guards).router); } } diff --git a/src/api/integrations/chatbot/chatbot.schema.ts b/src/api/integrations/chatbot/chatbot.schema.ts index efc2388f7..4712a70de 100644 --- a/src/api/integrations/chatbot/chatbot.schema.ts +++ b/src/api/integrations/chatbot/chatbot.schema.ts @@ -1,6 +1,8 @@ export * from '@api/integrations/chatbot/chatwoot/validate/chatwoot.schema'; export * from '@api/integrations/chatbot/dify/validate/dify.schema'; +export * from '@api/integrations/chatbot/evoai/validate/evoai.schema'; export * from '@api/integrations/chatbot/evolutionBot/validate/evolutionBot.schema'; export * from '@api/integrations/chatbot/flowise/validate/flowise.schema'; +export * from '@api/integrations/chatbot/n8n/validate/n8n.schema'; export * from '@api/integrations/chatbot/openai/validate/openai.schema'; export * from '@api/integrations/chatbot/typebot/validate/typebot.schema'; diff --git a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts index 17cdce01d..a55c134a4 100644 --- a/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts +++ b/src/api/integrations/chatbot/chatwoot/controllers/chatwoot.controller.ts @@ -1,10 +1,6 @@ import { InstanceDto } from '@api/dto/instance.dto'; import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto'; import { ChatwootService } from '@api/integrations/chatbot/chatwoot/services/chatwoot.service'; -import { PrismaRepository } from '@api/repository/repository.service'; -import { waMonitor } from '@api/server.module'; -import { CacheService } from '@api/services/cache.service'; -import { CacheEngine } from '@cache/cacheengine'; import { Chatwoot, ConfigService, HttpServer } from '@config/env.config'; import { BadRequestException } from '@exceptions'; import { isURL } from 'class-validator'; @@ -13,7 +9,6 @@ export class ChatwootController { constructor( private readonly chatwootService: ChatwootService, private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, ) {} public async createChatwoot(instance: InstanceDto, data: ChatwootDto) { @@ -84,9 +79,6 @@ export class ChatwootController { public async receiveWebhook(instance: InstanceDto, data: any) { if (!this.configService.get('CHATWOOT').ENABLED) throw new BadRequestException('Chatwoot is disabled'); - const chatwootCache = new CacheService(new CacheEngine(this.configService, ChatwootService.name).getEngine()); - const chatwootService = new ChatwootService(waMonitor, this.configService, this.prismaRepository, chatwootCache); - - return chatwootService.receiveWebhook(instance, data); + return this.chatwootService.receiveWebhook(instance, data); } } diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index 503a5cc90..906fff188 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -23,12 +23,13 @@ import { Chatwoot as ChatwootModel, Contact as ContactModel, Message as MessageM import i18next from '@utils/i18n'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; -import { proto } from 'baileys'; +import { WAMessageContent, WAMessageKey } from 'baileys'; import dayjs from 'dayjs'; import FormData from 'form-data'; -import Jimp from 'jimp'; +import { Jimp, JimpMime } from 'jimp'; +import { parsePhoneNumberFromString } from 'libphonenumber-js'; import Long from 'long'; -import mime from 'mime'; +import mimeTypes from 'mime-types'; import path from 'path'; import { Readable } from 'stream'; @@ -43,6 +44,9 @@ interface ChatwootMessage { export class ChatwootService { private readonly logger = new Logger('ChatwootService'); + // Lock polling delay + private readonly LOCK_POLLING_DELAY_MS = 300; // Delay between lock status checks + private provider: any; constructor( @@ -129,7 +133,7 @@ export class ChatwootService { public async find(instance: InstanceDto): Promise { try { return await this.waMonitor.waInstances[instance.instanceName].findChatwoot(); - } catch (error) { + } catch { this.logger.error('chatwoot not found'); return { enabled: null, url: '' }; } @@ -295,51 +299,67 @@ export class ChatwootService { avatar_url?: string, jid?: string, ) { - const client = await this.clientCw(instance); + try { + const client = await this.clientCw(instance); - if (!client) { - this.logger.warn('client not found'); - return null; - } + if (!client) { + this.logger.warn('client not found'); + return null; + } - let data: any = {}; - if (!isGroup) { - data = { - inbox_id: inboxId, - name: name || phoneNumber, - identifier: jid, - avatar_url: avatar_url, - }; + let data: any = {}; + if (!isGroup) { + data = { + inbox_id: inboxId, + name: name || phoneNumber, + identifier: jid, + avatar_url: avatar_url, + }; - if ((jid && jid.includes('@')) || !jid) { - data['phone_number'] = `+${phoneNumber}`; + if ((jid && jid.includes('@')) || !jid) { + data['phone_number'] = `+${phoneNumber}`; + } + } else { + data = { + inbox_id: inboxId, + name: name || phoneNumber, + identifier: phoneNumber, + avatar_url: avatar_url, + }; } - } else { - data = { - inbox_id: inboxId, - name: name || phoneNumber, - identifier: phoneNumber, - avatar_url: avatar_url, - }; - } - const contact = await client.contacts.create({ - accountId: this.provider.accountId, - data, - }); + const contact = await client.contacts.create({ + accountId: this.provider.accountId, + data, + }); - if (!contact) { - this.logger.warn('contact not found'); - return null; - } + if (!contact) { + this.logger.warn('contact not found'); + return null; + } - const findContact = await this.findContact(instance, phoneNumber); + const findContact = await this.findContact(instance, phoneNumber); - const contactId = findContact?.id; + const contactId = findContact?.id; - await this.addLabelToContact(this.provider.nameInbox, contactId); + await this.addLabelToContact(this.provider.nameInbox, contactId); - return contact; + return contact; + } catch (error) { + if ((error.status === 422 || error.response?.status === 422) && jid) { + this.logger.warn(`Contact with identifier ${jid} creation failed (422). Checking if it already exists...`); + const existingContact = await this.findContactByIdentifier(instance, jid); + if (existingContact) { + const contactId = existingContact.id; + await this.addLabelToContact(this.provider.nameInbox, contactId); + return existingContact; + } + } + + this.logger.error('Error creating contact'); + console.log(error); + return null; + } } public async updateContact(instance: InstanceDto, id: number, data: any) { @@ -363,7 +383,7 @@ export class ChatwootService { }); return contact; - } catch (error) { + } catch { return null; } } @@ -400,11 +420,60 @@ export class ChatwootService { } return true; - } catch (error) { + } catch { return false; } } + public async findContactByIdentifier(instance: InstanceDto, identifier: string) { + const client = await this.clientCw(instance); + + if (!client) { + this.logger.warn('client not found'); + return null; + } + + // Direct search by query (q) - most common way to search by identifier/email/phone + const contact = (await (client as any).get('contacts/search', { + params: { + q: identifier, + sort: 'name', + }, + })) as any; + + if (contact && contact.data && contact.data.payload && contact.data.payload.length > 0) { + return contact.data.payload[0]; + } + + // Fallback for older API versions or different response structures + if (contact && contact.payload && contact.payload.length > 0) { + return contact.payload[0]; + } + + // Try search by attribute + const contactByAttr = (await (client as any).post('contacts/filter', { + payload: [ + { + attribute_key: 'identifier', + filter_operator: 'equal_to', + values: [identifier], + query_operator: null, + }, + ], + })) as any; + + if (contactByAttr && contactByAttr.payload && contactByAttr.payload.length > 0) { + return contactByAttr.payload[0]; + } + + // Check inside data property if using axios interceptors wrapper + if (contactByAttr && contactByAttr.data && contactByAttr.data.payload && contactByAttr.data.payload.length > 0) { + return contactByAttr.data.payload[0]; + } + + return null; + } + public async findContact(instance: InstanceDto, phoneNumber: string) { const client = await this.clientCw(instance); @@ -451,6 +520,24 @@ export class ChatwootService { } } + private async mergeContacts(baseId: number, mergeId: number) { + try { + const contact = await chatwootRequest(this.getClientCwConfig(), { + method: 'POST', + url: `/api/v1/accounts/${this.provider.accountId}/actions/contact_merge`, + body: { + base_contact_id: baseId, + mergee_contact_id: mergeId, + }, + }); + + return contact; + } catch { + this.logger.error('Error merging contacts'); + return null; + } + } + private async mergeBrazilianContacts(contacts: any[]) { try { const contact = await chatwootRequest(this.getClientCwConfig(), { @@ -543,31 +630,56 @@ export class ChatwootService { } public async createConversation(instance: InstanceDto, body: any) { - try { - this.logger.verbose('--- Start createConversation ---'); - this.logger.verbose(`Instance: ${JSON.stringify(instance)}`); + const isLid = body.key.addressingMode === 'lid'; + const isGroup = body.key.remoteJid.endsWith('@g.us'); + const phoneNumber = isLid && !isGroup ? body.key.remoteJidAlt : body.key.remoteJid; + const { remoteJid } = body.key; + const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`; + const lockKey = `${instance.instanceName}:lock:createConversation-${remoteJid}`; + const maxWaitTime = 5000; // 5 seconds + const client = await this.clientCw(instance); + if (!client) return null; - const client = await this.clientCw(instance); + try { + // Processa atualização de contatos já criados @lid + if (phoneNumber && remoteJid && !isGroup) { + const contact = await this.findContact(instance, phoneNumber.split('@')[0]); + if (contact && contact.identifier !== remoteJid) { + this.logger.verbose( + `Identifier needs update: (contact.identifier: ${contact.identifier}, phoneNumber: ${phoneNumber}, body.key.remoteJidAlt: ${remoteJid}`, + ); + const updateContact = await this.updateContact(instance, contact.id, { + identifier: phoneNumber, + phone_number: `+${phoneNumber.split('@')[0]}`, + }); - if (!client) { - this.logger.warn(`Client not found for instance: ${JSON.stringify(instance)}`); - return null; + if (updateContact === null) { + const baseContact = await this.findContact(instance, phoneNumber.split('@')[0]); + if (baseContact) { + await this.mergeContacts(baseContact.id, contact.id); + this.logger.verbose( + `Merge contacts: (${baseContact.id}) ${baseContact.phone_number} and (${contact.id}) ${contact.phone_number}`, + ); + } + } + } } + this.logger.verbose(`--- Start createConversation ---`); + this.logger.verbose(`Instance: ${JSON.stringify(instance)}`); - const cacheKey = `${instance.instanceName}:createConversation-${body.key.remoteJid}`; - this.logger.verbose(`Cache key: ${cacheKey}`); - + // If it already exists in the cache, return conversationId if (await this.cache.has(cacheKey)) { - this.logger.verbose(`Cache hit for key: ${cacheKey}`); const conversationId = (await this.cache.get(cacheKey)) as number; - this.logger.verbose(`Cached conversation ID: ${conversationId}`); - let conversationExists: conversation | boolean; + this.logger.verbose(`Found conversation to: ${phoneNumber}, conversation ID: ${conversationId}`); + let conversationExists: any; try { conversationExists = await client.conversations.get({ accountId: this.provider.accountId, conversationId: conversationId, }); - this.logger.verbose(`Conversation exists: ${JSON.stringify(conversationExists)}`); + this.logger.verbose( + `Conversation exists: ID: ${conversationExists.id} - Name: ${conversationExists.meta.sender.name} - Identifier: ${conversationExists.meta.sender.identifier}`, + ); } catch (error) { this.logger.error(`Error getting conversation: ${error}`); conversationExists = false; @@ -577,182 +689,198 @@ export class ChatwootService { this.cache.delete(cacheKey); return await this.createConversation(instance, body); } - return conversationId; } - const isGroup = body.key.remoteJid.includes('@g.us'); - this.logger.verbose(`Is group: ${isGroup}`); + // If lock already exists, wait until release or timeout + if (await this.cache.has(lockKey)) { + this.logger.verbose(`Operação de criação já em andamento para ${remoteJid}, aguardando resultado...`); + const start = Date.now(); + while (await this.cache.has(lockKey)) { + if (Date.now() - start > maxWaitTime) { + this.logger.warn(`Timeout aguardando lock para ${remoteJid}`); + break; + } + await new Promise((res) => setTimeout(res, this.LOCK_POLLING_DELAY_MS)); + if (await this.cache.has(cacheKey)) { + const conversationId = (await this.cache.get(cacheKey)) as number; + this.logger.verbose(`Resolves creation of: ${remoteJid}, conversation ID: ${conversationId}`); + return conversationId; + } + } + } - const chatId = isGroup ? body.key.remoteJid : body.key.remoteJid.split('@')[0]; - this.logger.verbose(`Chat ID: ${chatId}`); + // Adquire lock + await this.cache.set(lockKey, true, 30); + this.logger.verbose(`Bloqueio adquirido para: ${lockKey}`); + + try { + /* + Double check after lock + Utilizei uma nova verificação para evitar que outra thread execute entre o terminio do while e o set lock + */ + if (await this.cache.has(cacheKey)) { + return (await this.cache.get(cacheKey)) as number; + } - let nameContact: string; + const chatId = isGroup ? remoteJid : phoneNumber.split('@')[0].split(':')[0]; + let nameContact = !body.key.fromMe ? body.pushName : chatId; + const filterInbox = await this.getInbox(instance); + if (!filterInbox) return null; - nameContact = !body.key.fromMe ? body.pushName : chatId; - this.logger.verbose(`Name contact: ${nameContact}`); + if (isGroup) { + this.logger.verbose(`Processing group conversation`); + const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId); + this.logger.verbose(`Group metadata: JID:${group.JID} - Subject:${group?.subject || group?.Name}`); - const filterInbox = await this.getInbox(instance); + const participantJid = isLid && !body.key.fromMe ? body.key.participantAlt : body.key.participant; + nameContact = `${group.subject} (GROUP)`; - if (!filterInbox) { - this.logger.warn(`Inbox not found for instance: ${JSON.stringify(instance)}`); - return null; - } + const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture( + participantJid.split('@')[0], + ); + this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`); - if (isGroup) { - this.logger.verbose('Processing group conversation'); - const group = await this.waMonitor.waInstances[instance.instanceName].client.groupMetadata(chatId); - this.logger.verbose(`Group metadata: ${JSON.stringify(group)}`); + const findParticipant = await this.findContact(instance, participantJid.split('@')[0]); - nameContact = `${group.subject} (GROUP)`; + if (findParticipant) { + this.logger.verbose( + `Found participant: ID:${findParticipant.id} - Name: ${findParticipant.name} - identifier: ${findParticipant.identifier}`, + ); + if (!findParticipant.name || findParticipant.name === chatId) { + await this.updateContact(instance, findParticipant.id, { + name: body.pushName, + avatar_url: picture_url.profilePictureUrl || null, + }); + } + } else { + await this.createContact( + instance, + participantJid.split('@')[0].split(':')[0], + filterInbox.id, + false, + body.pushName, + picture_url.profilePictureUrl || null, + participantJid, + ); + } + } - const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture( - body.key.participant.split('@')[0], - ); - this.logger.verbose(`Participant profile picture URL: ${JSON.stringify(picture_url)}`); + const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId); + this.logger.verbose(`Contact profile picture URL: ${JSON.stringify(picture_url)}`); - const findParticipant = await this.findContact(instance, body.key.participant.split('@')[0]); - this.logger.verbose(`Found participant: ${JSON.stringify(findParticipant)}`); + this.logger.verbose(`Searching contact for: ${chatId}`); + let contact = await this.findContact(instance, chatId); - if (findParticipant) { - if (!findParticipant.name || findParticipant.name === chatId) { - await this.updateContact(instance, findParticipant.id, { - name: body.pushName, - avatar_url: picture_url.profilePictureUrl || null, - }); + if (contact) { + this.logger.verbose(`Found contact: ID:${contact.id} - Name:${contact.name}`); + if (!body.key.fromMe) { + const waProfilePictureFile = + picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || ''; + const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || ''; + const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile; + const nameNeedsUpdate = !contact.name || contact.name === chatId; + this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`); + this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`); + if (pictureNeedsUpdate || nameNeedsUpdate) { + contact = await this.updateContact(instance, contact.id, { + ...(nameNeedsUpdate && { name: nameContact }), + ...(waProfilePictureFile === '' && { avatar: null }), + ...(pictureNeedsUpdate && { avatar_url: picture_url?.profilePictureUrl }), + }); + } } } else { - await this.createContact( + contact = await this.createContact( instance, - body.key.participant.split('@')[0], + chatId, filterInbox.id, - false, - body.pushName, + isGroup, + nameContact, picture_url.profilePictureUrl || null, - body.key.participant, + phoneNumber, ); } - } - const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId); - this.logger.verbose(`Contact profile picture URL: ${JSON.stringify(picture_url)}`); - - let contact = await this.findContact(instance, chatId); - this.logger.verbose(`Found contact: ${JSON.stringify(contact)}`); - - if (contact) { - if (!body.key.fromMe) { - const waProfilePictureFile = - picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || ''; - const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || ''; - const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile; - const nameNeedsUpdate = - !contact.name || - contact.name === chatId || - (`+${chatId}`.startsWith('+55') - ? this.getNumbers(`+${chatId}`).some( - (v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1), - ) - : false); - - this.logger.verbose(`Picture needs update: ${pictureNeedsUpdate}`); - this.logger.verbose(`Name needs update: ${nameNeedsUpdate}`); - - if (pictureNeedsUpdate || nameNeedsUpdate) { - contact = await this.updateContact(instance, contact.id, { - ...(nameNeedsUpdate && { name: nameContact }), - ...(waProfilePictureFile === '' && { avatar: null }), - ...(pictureNeedsUpdate && { avatar_url: picture_url?.profilePictureUrl }), - }); - } + if (!contact) { + this.logger.warn(`Contact not created or found`); + return null; } - } else { - const jid = body.key.remoteJid; - contact = await this.createContact( - instance, - chatId, - filterInbox.id, - isGroup, - nameContact, - picture_url.profilePictureUrl || null, - jid, - ); - } - if (!contact) { - this.logger.warn('Contact not created or found'); - return null; - } - - const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id; - this.logger.verbose(`Contact ID: ${contactId}`); + const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id; + this.logger.verbose(`Contact ID: ${contactId}`); - const contactConversations = (await client.contacts.listConversations({ - accountId: this.provider.accountId, - id: contactId, - })) as any; - this.logger.verbose(`Contact conversations: ${JSON.stringify(contactConversations)}`); + const contactConversations = (await client.contacts.listConversations({ + accountId: this.provider.accountId, + id: contactId, + })) as any; - if (!contactConversations || !contactConversations.payload) { - this.logger.error('No conversations found or payload is undefined'); - return null; - } - - if (contactConversations.payload.length) { - let conversation: any; - if (this.provider.reopenConversation) { - conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id); - this.logger.verbose(`Found conversation in reopenConversation mode: ${JSON.stringify(conversation)}`); + if (!contactConversations || !contactConversations.payload) { + this.logger.error(`No conversations found or payload is undefined`); + return null; + } - if (this.provider.conversationPending) { - if (conversation) { + let inboxConversation = contactConversations.payload.find( + (conversation) => conversation.inbox_id == filterInbox.id, + ); + if (inboxConversation) { + if (this.provider.reopenConversation) { + this.logger.verbose( + `Found conversation in reopenConversation mode: ID: ${inboxConversation.id} - Name: ${inboxConversation.meta.sender.name} - Identifier: ${inboxConversation.meta.sender.identifier}`, + ); + if (inboxConversation && this.provider.conversationPending && inboxConversation.status !== 'open') { await client.conversations.toggleStatus({ accountId: this.provider.accountId, - conversationId: conversation.id, + conversationId: inboxConversation.id, data: { status: 'pending', }, }); } + } else { + inboxConversation = contactConversations.payload.find( + (conversation) => + conversation && conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id, + ); + this.logger.verbose(`Found conversation: ${JSON.stringify(inboxConversation)}`); } - } else { - conversation = contactConversations.payload.find( - (conversation) => conversation.status !== 'resolved' && conversation.inbox_id == filterInbox.id, - ); - this.logger.verbose(`Found conversation: ${JSON.stringify(conversation)}`); - } - if (conversation) { - this.logger.verbose(`Returning existing conversation ID: ${conversation.id}`); - this.cache.set(cacheKey, conversation.id); - return conversation.id; + if (inboxConversation) { + this.logger.verbose(`Returning existing conversation ID: ${inboxConversation.id}`); + this.cache.set(cacheKey, inboxConversation.id, 1800); + return inboxConversation.id; + } } - } - const data = { - contact_id: contactId.toString(), - inbox_id: filterInbox.id.toString(), - }; + const data = { + contact_id: contactId.toString(), + inbox_id: filterInbox.id.toString(), + }; - if (this.provider.conversationPending) { - data['status'] = 'pending'; - } + if (this.provider.conversationPending) { + data['status'] = 'pending'; + } - const conversation = await client.conversations.create({ - accountId: this.provider.accountId, - data, - }); + const conversation = await client.conversations.create({ + accountId: this.provider.accountId, + data, + }); - if (!conversation) { - this.logger.warn('Conversation not created or found'); - return null; - } + if (!conversation) { + this.logger.warn(`Conversation not created or found`); + return null; + } - this.logger.verbose(`New conversation created with ID: ${conversation.id}`); - this.cache.set(cacheKey, conversation.id); - return conversation.id; + this.logger.verbose(`New conversation created of ${remoteJid} with ID: ${conversation.id}`); + this.cache.set(cacheKey, conversation.id, 1800); + return conversation.id; + } finally { + await this.cache.delete(lockKey); + this.logger.verbose(`Block released for: ${lockKey}`); + } } catch (error) { this.logger.error(`Error in createConversation: ${error}`); + return null; } } @@ -931,7 +1059,7 @@ export class ChatwootService { quotedMsg?: MessageModel, ) { if (sourceId && this.isImportHistoryAvailable()) { - const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); if (messageAlreadySaved) { if (messageAlreadySaved.size > 0) { this.logger.warn('Message already saved on chatwoot'); @@ -1066,7 +1194,7 @@ export class ChatwootService { public async sendAttachment(waInstance: any, number: string, media: any, caption?: string, options?: Options) { try { const parsedMedia = path.parse(decodeURIComponent(media)); - let mimeType = mime.getType(parsedMedia?.ext) || ''; + let mimeType = mimeTypes.lookup(parsedMedia?.ext) || ''; let fileName = parsedMedia?.name + parsedMedia?.ext; if (!mimeType) { @@ -1100,18 +1228,19 @@ export class ChatwootService { const data: SendAudioDto = { number: number, audio: media, - delay: 1200, + delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500, quoted: options?.quoted, }; sendTelemetry('/message/sendWhatsAppAudio'); - const messageSent = await waInstance?.audioWhatsapp(data, true); + const messageSent = await waInstance?.audioWhatsapp(data, null, true); return messageSent; } - if (type === 'image' && parsedMedia && parsedMedia?.ext === '.gif') { + const documentExtensions = ['.gif', '.svg', '.tiff', '.tif', '.dxf', '.dwg']; + if (type === 'image' && parsedMedia && documentExtensions.includes(parsedMedia?.ext)) { type = 'document'; } @@ -1135,6 +1264,7 @@ export class ChatwootService { return messageSent; } catch (error) { this.logger.error(error); + throw error; // Re-throw para que o erro seja tratado pelo caller } } @@ -1216,6 +1346,7 @@ export class ChatwootService { const senderName = body?.conversation?.messages[0]?.sender?.available_name || body?.sender?.name; const waInstance = this.waMonitor.waInstances[instance.instanceName]; + instance.instanceId = waInstance.instanceId; if (body.event === 'message_updated' && body.content_attributes?.deleted) { const message = await this.prismaRepository.message.findFirst({ @@ -1226,12 +1357,7 @@ export class ChatwootService { }); if (message) { - const key = message.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; + const key = message.key as WAMessageKey; await waInstance?.client.sendMessage(key.remoteJid, { delete: key }); @@ -1363,7 +1489,6 @@ export class ChatwootService { await this.updateChatwootMessageId( { ...messageSent, - owner: instance.instanceName, }, { messageId: body.id, @@ -1378,7 +1503,7 @@ export class ChatwootService { const data: SendTextDto = { number: chatId, text: formatText, - delay: 1200, + delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500, quoted: await this.getQuotedMessage(body, instance), }; @@ -1398,7 +1523,6 @@ export class ChatwootService { await this.updateChatwootMessageId( { ...messageSent, - instanceId: instance.instanceId, }, { messageId: body.id, @@ -1429,12 +1553,7 @@ export class ChatwootService { }, }); if (lastMessage && !lastMessage.chatwootIsRead) { - const key = lastMessage.key as { - id: string; - fromMe: boolean; - remoteJid: string; - participant?: string; - }; + const key = lastMessage.key as WAMessageKey; waInstance?.markMessageAsRead({ readMessages: [ @@ -1471,7 +1590,7 @@ export class ChatwootService { const data: SendTextDto = { number: chatId, text: body.content.replace(/\\\r\n|\\\n|\n/g, '\n'), - delay: 1200, + delay: Math.floor(Math.random() * (2000 - 500 + 1)) + 500, }; sendTelemetry('/message/sendText'); @@ -1492,51 +1611,46 @@ export class ChatwootService { chatwootMessageIds: ChatwootMessage, instance: InstanceDto, ) { - const key = message.key as { - id: string; - fromMe: boolean; - remoteJid: string; - participant?: string; - }; + const key = message.key as WAMessageKey; if (!chatwootMessageIds.messageId || !key?.id) { return; } - await this.prismaRepository.message.updateMany({ - where: { - key: { - path: ['id'], - equals: key.id, - }, - instanceId: instance.instanceId, - }, - data: { - chatwootMessageId: chatwootMessageIds.messageId, - chatwootConversationId: chatwootMessageIds.conversationId, - chatwootInboxId: chatwootMessageIds.inboxId, - chatwootContactInboxSourceId: chatwootMessageIds.contactInboxSourceId, - chatwootIsRead: chatwootMessageIds.isRead, - }, - }); + // Use raw SQL to avoid JSON path issues + const result = await this.prismaRepository.$executeRaw` + UPDATE "Message" + SET + "chatwootMessageId" = ${chatwootMessageIds.messageId}, + "chatwootConversationId" = ${chatwootMessageIds.conversationId}, + "chatwootInboxId" = ${chatwootMessageIds.inboxId}, + "chatwootContactInboxSourceId" = ${chatwootMessageIds.contactInboxSourceId}, + "chatwootIsRead" = ${chatwootMessageIds.isRead || false} + WHERE "instanceId" = ${instance.instanceId} + AND "key"->>'id' = ${key.id} + `; + + this.logger.verbose(`Update result: ${result} rows affected`); if (this.isImportHistoryAvailable()) { - chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id); + try { + await chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id); + } catch (error) { + this.logger.error(`Error updating Chatwoot message source ID: ${error}`); + } } } private async getMessageByKeyId(instance: InstanceDto, keyId: string): Promise { - const messages = await this.prismaRepository.message.findFirst({ - where: { - key: { - path: ['id'], - equals: keyId, - }, - instanceId: instance.instanceId, - }, - }); - - return messages || null; + // Use raw SQL query to avoid JSON path issues with Prisma + const messages = await this.prismaRepository.$queryRaw` + SELECT * FROM "Message" + WHERE "instanceId" = ${instance.instanceId} + AND "key"->>'id' = ${keyId} + LIMIT 1 + `; + + return (messages as MessageModel[])[0] || null; } private async getReplyToIds( @@ -1571,17 +1685,13 @@ export class ChatwootService { }, }); - const key = message?.key as { - id: string; - fromMe: boolean; - remoteJid: string; - participant?: string; - }; + const key = message?.key as WAMessageKey; + const messageContent = message?.message as WAMessageContent; - if (message && key?.id) { + if (messageContent && key?.id) { return { - key: message.key as proto.IMessageKey, - message: message.message as proto.IMessage, + key: key, + message: messageContent, }; } } @@ -1607,6 +1717,10 @@ export class ChatwootService { return result; } + private isInteractiveButtonMessage(messageType: string, message: any) { + return messageType === 'interactiveMessage' && message.interactiveMessage?.nativeFlowMessage?.buttons?.length > 0; + } + private getAdsMessage(msg: any) { interface AdsMessage { title: string; @@ -1653,7 +1767,7 @@ export class ChatwootService { stickerMessage: undefined, documentMessage: msg.documentMessage?.caption, documentWithCaptionMessage: msg.documentWithCaptionMessage?.message?.documentMessage?.caption, - audioMessage: msg.audioMessage?.caption, + audioMessage: msg.audioMessage ? (msg.audioMessage.caption ?? '') : undefined, contactMessage: msg.contactMessage?.vcard, contactsArrayMessage: msg.contactsArrayMessage, locationMessage: msg.locationMessage, @@ -1880,6 +1994,7 @@ export class ChatwootService { } if (event === 'messages.upsert' || event === 'send.message') { + this.logger.info(`[${event}] New message received - Instance: ${JSON.stringify(body, null, 2)}`); if (body.key.remoteJid === 'status@broadcast') { return; } @@ -1898,7 +2013,7 @@ export class ChatwootService { .replaceAll(/~((?!\s)([^\n~]+?)(? { + switch (pixSettings.key_type) { + case 'EVP': + return 'Chave Aleatória'; + case 'EMAIL': + return 'E-mail'; + case 'PHONE': + return 'Telefone'; + default: + return pixSettings.key_type; + } + })(); + const pixKey = pixSettings.key_type === 'PHONE' ? pixSettings.key.replace('+55', '') : pixSettings.key; + const content = `*${pixSettings.merchant_name}*\nChave PIX: ${pixKey} (${pixKeyType})`; + + const send = await this.createMessage( + instance, + getConversation, + content, + messageType, + false, + [], + body, + 'WAID:' + body.key.id, + quotedMsg, + ); + if (!send) this.logger.warn('message not sent'); + } else { + this.logger.warn('Interactive Button Message not mapped'); + } + } + return; + } + const isAdsMessage = (adsMessage && adsMessage.title) || adsMessage.body || adsMessage.thumbnailUrl; if (isAdsMessage) { const imgBuffer = await axios.get(adsMessage.thumbnailUrl, { responseType: 'arraybuffer' }); - const extension = mime.getExtension(imgBuffer.headers['content-type']); - const mimeType = extension && mime.getType(extension); + const extension = mimeTypes.extension(imgBuffer.headers['content-type']); + const mimeType = extension && mimeTypes.lookup(extension); if (!mimeType) { this.logger.warn('mimetype of Ads message not found'); @@ -2056,13 +2223,15 @@ export class ChatwootService { } const random = Math.random().toString(36).substring(7); - const nameFile = `${random}.${mime.getExtension(mimeType)}`; + const nameFile = `${random}.${mimeTypes.extension(mimeType)}`; const fileData = Buffer.from(imgBuffer.data, 'binary'); const img = await Jimp.read(fileData); - await img.cover(320, 180); - - const processedBuffer = await img.getBufferAsync(Jimp.MIME_PNG); + await img.cover({ + w: 320, + h: 180, + }); + const processedBuffer = await img.getBuffer(JimpMime.png); const fileStream = new Readable(); fileStream._read = () => {}; // _read is required but you can noop it @@ -2099,11 +2268,16 @@ export class ChatwootService { if (body.key.remoteJid.includes('@g.us')) { const participantName = body.pushName; + const rawPhoneNumber = + body.key.addressingMode === 'lid' && !body.key.fromMe && body.key.participantAlt + ? body.key.participantAlt.split('@')[0].split(':')[0] + : body.key.participant.split('@')[0].split(':')[0]; + const formattedPhoneNumber = parsePhoneNumberFromString(`+${rawPhoneNumber}`).formatInternational(); let content: string; if (!body.key.fromMe) { - content = `**${participantName}**\n\n${bodyMessage}`; + content = `**${formattedPhoneNumber} - ${participantName}:**\n\n${bodyMessage}`; } else { content = `${bodyMessage}`; } @@ -2179,21 +2353,37 @@ export class ChatwootService { } } - if (event === 'messages.edit') { - const editedText = `${ - body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text - }\n\n_\`${i18next.t('cw.message.edited')}.\`_`; + if (event === 'messages.edit' || event === 'send.message.update') { + const editedMessageContentRaw = + body?.editedMessage?.conversation ?? + body?.editedMessage?.extendedTextMessage?.text ?? + body?.editedMessage?.imageMessage?.caption ?? + body?.editedMessage?.videoMessage?.caption ?? + body?.editedMessage?.documentMessage?.caption ?? + (typeof body?.text === 'string' ? body.text : undefined); + + const editedMessageContent = (editedMessageContentRaw ?? '').trim(); + + if (!editedMessageContent) { + this.logger.info('[CW.EDIT] Conteúdo vazio — ignorando (DELETE tratará se for revoke).'); + return; + } + const message = await this.getMessageByKeyId(instance, body?.key?.id); - const key = message.key as { - id: string; - fromMe: boolean; - remoteJid: string; - participant?: string; - }; + + if (!message) { + this.logger.warn('Message not found for edit event'); + return; + } + + const key = message.key as WAMessageKey; const messageType = key?.fromMe ? 'outgoing' : 'incoming'; - if (message && message.chatwootConversationId) { + if (message && message.chatwootConversationId && message.chatwootMessageId) { + // Criar nova mensagem com formato: "Mensagem editada:\n\nteste1" + const editedText = `\n\n\`${i18next.t('cw.message.edited')}:\`\n\n${editedMessageContent}`; + const send = await this.createMessage( instance, message.chatwootConversationId, @@ -2245,7 +2435,7 @@ export class ChatwootService { const url = `/public/api/v1/inboxes/${inbox.inbox_identifier}/contacts/${sourceId}` + `/conversations/${conversationId}/update_last_seen`; - chatwootRequest(this.getClientCwConfig(), { + await chatwootRequest(this.getClientCwConfig(), { method: 'POST', url: url, }); @@ -2271,15 +2461,30 @@ export class ChatwootService { await this.createBotMessage(instance, msgStatus, 'incoming'); } - if (event === 'connection.update') { - if (body.status === 'open') { - // if we have qrcode count then we understand that a new connection was established - if (this.waMonitor.waInstances[instance.instanceName].qrCode.count > 0) { - const msgConnection = i18next.t('cw.inbox.connected'); - await this.createBotMessage(instance, msgConnection, 'incoming'); - this.waMonitor.waInstances[instance.instanceName].qrCode.count = 0; - chatwootImport.clearAll(instance); - } + if (event === 'connection.update' && body.status === 'open') { + const waInstance = this.waMonitor.waInstances[instance.instanceName]; + if (!waInstance) return; + + const now = Date.now(); + const timeSinceLastNotification = now - (waInstance.lastConnectionNotification || 0); + + // Se a conexão foi estabelecida via QR code, notifica imediatamente. + if (waInstance.qrCode && waInstance.qrCode.count > 0) { + const msgConnection = i18next.t('cw.inbox.connected'); + await this.createBotMessage(instance, msgConnection, 'incoming'); + waInstance.qrCode.count = 0; + waInstance.lastConnectionNotification = now; + chatwootImport.clearAll(instance); + } + // Se não foi via QR code, verifica o throttling. + else if (timeSinceLastNotification >= 30000) { + const msgConnection = i18next.t('cw.inbox.connected'); + await this.createBotMessage(instance, msgConnection, 'incoming'); + waInstance.lastConnectionNotification = now; + } else { + this.logger.warn( + `Connection notification skipped for ${instance.instanceName} - too frequent (${timeSinceLastNotification}ms since last)`, + ); } } @@ -2322,7 +2527,13 @@ export class ChatwootService { } } - public getNumberFromRemoteJid(remoteJid: string) { + public normalizeJidIdentifier(remoteJid: string) { + if (!remoteJid) { + return ''; + } + if (remoteJid.includes('@lid')) { + return remoteJid; + } return remoteJid.replace(/:\d+/, '').split('@')[0]; } @@ -2467,7 +2678,7 @@ export class ChatwootService { const savedMessages = await this.prismaRepository.message.findMany({ where: { Instance: { name: instance.instanceName }, - messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() }, + messageTimestamp: { gte: Number(dayjs().subtract(6, 'hours').unix()) }, AND: ids.map((id) => ({ key: { path: ['id'], not: id } })), }, }); @@ -2496,7 +2707,7 @@ export class ChatwootService { await chatwootImport.importHistoryMessages(instance, this, inbox, this.provider); const waInstance = this.waMonitor.waInstances[instance.instanceName]; waInstance.clearCacheChatwoot(); - } catch (error) { + } catch { return; } } diff --git a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts index 52453f59c..7d55da416 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -112,12 +112,19 @@ class ChatwootImport { const bindInsert = [provider.accountId]; for (const contact of contactsChunk) { - bindInsert.push(contact.pushName); - const bindName = `$${bindInsert.length}`; + const isGroup = this.isIgnorePhoneNumber(contact.remoteJid); - bindInsert.push(`+${contact.remoteJid.split('@')[0]}`); - const bindPhoneNumber = `$${bindInsert.length}`; + const contactName = isGroup ? `${contact.pushName} (GROUP)` : contact.pushName; + bindInsert.push(contactName); + const bindName = `$${bindInsert.length}`; + let bindPhoneNumber: string; + if (!isGroup) { + bindInsert.push(`+${contact.remoteJid.split('@')[0]}`); + bindPhoneNumber = `$${bindInsert.length}`; + } else { + bindPhoneNumber = 'NULL'; + } bindInsert.push(contact.remoteJid); const bindIdentifier = `$${bindInsert.length}`; @@ -130,7 +137,7 @@ class ChatwootImport { DO UPDATE SET name = EXCLUDED.name, phone_number = EXCLUDED.phone_number, - identifier = EXCLUDED.identifier`; + updated_at = NOW()`; totalContactsImported += (await pgClient.query(sqlInsert, bindInsert))?.rowCount ?? 0; @@ -169,7 +176,7 @@ class ChatwootImport { } } - public async getExistingSourceIds(sourceIds: string[]): Promise> { + public async getExistingSourceIds(sourceIds: string[], conversationId?: number): Promise> { try { const existingSourceIdsSet = new Set(); @@ -177,18 +184,25 @@ class ChatwootImport { return existingSourceIdsSet; } - const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); // Make sure the sourceId is always formatted as WAID:1234567890 - const query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; + // Ensure all sourceIds are consistently prefixed with 'WAID:' as required by downstream systems and database queries. + const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); const pgClient = postgresClient.getChatwootConnection(); - const result = await pgClient.query(query, [formattedSourceIds]); + const params = conversationId ? [formattedSourceIds, conversationId] : [formattedSourceIds]; + + const query = conversationId + ? 'SELECT source_id FROM messages WHERE source_id = ANY($1) AND conversation_id = $2' + : 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; + + const result = await pgClient.query(query, params); for (const row of result.rows) { existingSourceIdsSet.add(row.source_id); } return existingSourceIdsSet; } catch (error) { - return null; + this.logger.error(`Error on getExistingSourceIds: ${error.toString()}`); + return new Set(); } } @@ -499,25 +513,30 @@ class ChatwootImport { stickerMessage: msg.message.stickerMessage, templateMessage: msg.message.templateMessage?.hydratedTemplate?.hydratedContentText, }; - const typeKey = Object.keys(types).find((key) => types[key] !== undefined); + const typeKey = Object.keys(types).find((key) => types[key] !== undefined && types[key] !== null); switch (typeKey) { - case 'documentMessage': - return `__`; - - case 'documentWithCaptionMessage': - return `__`; - - case 'templateMessage': - return msg.message.templateMessage.hydratedTemplate.hydratedTitleText - ? `*${msg.message.templateMessage.hydratedTemplate.hydratedTitleText}*\\n` - : '' + msg.message.templateMessage.hydratedTemplate.hydratedContentText; + case 'documentMessage': { + const doc = msg.message.documentMessage; + const fileName = doc?.fileName || 'document'; + const caption = doc?.caption ? ` ${doc.caption}` : ''; + return `__`; + } + + case 'documentWithCaptionMessage': { + const doc = msg.message.documentWithCaptionMessage?.message?.documentMessage; + const fileName = doc?.fileName || 'document'; + const caption = doc?.caption ? ` ${doc.caption}` : ''; + return `__`; + } + + case 'templateMessage': { + const template = msg.message.templateMessage?.hydratedTemplate; + return ( + (template?.hydratedTitleText ? `*${template.hydratedTitleText}*\n` : '') + + (template?.hydratedContentText || '') + ); + } case 'imageMessage': return '__'; diff --git a/src/api/integrations/chatbot/dify/controllers/dify.controller.ts b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts index 96c44a7e1..ebbf2b0d1 100644 --- a/src/api/integrations/chatbot/dify/controllers/dify.controller.ts +++ b/src/api/integrations/chatbot/dify/controllers/dify.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { DifyDto } from '@api/integrations/chatbot/dify/dto/dify.dto'; import { DifyService } from '@api/integrations/chatbot/dify/services/dify.service'; @@ -7,12 +6,11 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { configService, Dify } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { Dify as DifyModel } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { Dify as DifyModel, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class DifyController extends ChatbotController implements ChatbotControllerInterface { +export class DifyController extends BaseChatbotController { constructor( private readonly difyService: DifyService, prismaRepository: PrismaRepository, @@ -26,6 +24,7 @@ export class DifyController extends ChatbotController implements ChatbotControll } public readonly logger = new Logger('DifyController'); + protected readonly integrationName = 'Dify'; integrationEnabled = configService.get('DIFY').ENABLED; botRepository: any; @@ -33,88 +32,42 @@ export class DifyController extends ChatbotController implements ChatbotControll sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: DifyDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); + protected getFallbackBotId(settings: any): string | undefined { + return settings?.fallbackId; + } - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; + protected getFallbackFieldName(): string { + return 'difyIdFallback'; + } - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } + protected getIntegrationType(): string { + return 'dify'; + } - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); + protected getAdditionalBotData(data: DifyDto): Record { + return { + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: DifyDto): Record { + return { + botType: data.botType, + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: DifyDto): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { + id: { + not: botId, + }, instanceId: instanceId, botType: data.botType, apiUrl: data.apiUrl, @@ -125,128 +78,10 @@ export class DifyController extends ChatbotController implements ChatbotControll if (checkDuplicate) { throw new Error('Dify already exists'); } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating dify'); - } } - public async findBot(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; - } - - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Dify not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return bot; - } - - public async updateBot(instance: InstanceDto, botId: string, data: DifyDto) { + // Override createBot to add Dify-specific validation + public async createBot(instance: InstanceDto, data: DifyDto) { if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); const instanceId = await this.prismaRepository.instance @@ -257,42 +92,9 @@ export class DifyController extends ChatbotController implements ChatbotControll }) .then((instance) => instance.id); - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Dify not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - } - + // Dify-specific duplicate check const checkDuplicate = await this.botRepository.findFirst({ where: { - id: { - not: botId, - }, instanceId: instanceId, botType: data.botType, apiUrl: data.apiUrl, @@ -304,591 +106,21 @@ export class DifyController extends ChatbotController implements ChatbotControll throw new Error('Dify already exists'); } - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - botType: data.botType, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating dify'); - } - } - - public async deleteBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Dify not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting dify bot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - difyIdFallback: updateSettings.difyIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - difyIdFallback: data.difyIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - difyIdFallback: newSetttings.difyIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - difyIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - difyIdFallback: settings.difyIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } + // Let the base class handle the rest + return super.createBot(instance, data); } - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'dify', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Dify is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - if (!this.integrationEnabled) return; - - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger( - this.botRepository, - this.settingsRepository, - content, - instance, - session, - )) as DifyModel; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.difyIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.difyIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.difyService.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.difyService.processDify( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Process Dify-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: DifyModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.difyService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } } diff --git a/src/api/integrations/chatbot/dify/dto/dify.dto.ts b/src/api/integrations/chatbot/dify/dto/dify.dto.ts index ff9bba059..9e4367057 100644 --- a/src/api/integrations/chatbot/dify/dto/dify.dto.ts +++ b/src/api/integrations/chatbot/dify/dto/dify.dto.ts @@ -1,38 +1,13 @@ -import { $Enums, TriggerOperator, TriggerType } from '@prisma/client'; +import { $Enums } from '@prisma/client'; -export class DifyDto { - enabled?: boolean; - description?: string; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class DifyDto extends BaseChatbotDto { botType?: $Enums.DifyBotType; apiUrl?: string; apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class DifySettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class DifySettingDto extends BaseChatbotSettingDto { difyIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/dify/services/dify.service.ts b/src/api/integrations/chatbot/dify/services/dify.service.ts index 9f7b61272..a00594ec3 100644 --- a/src/api/integrations/chatbot/dify/services/dify.service.ts +++ b/src/api/integrations/chatbot/dify/services/dify.service.ts @@ -1,60 +1,35 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; +import { ConfigService, HttpServer } from '@config/env.config'; import { Dify, DifySetting, IntegrationSession } from '@prisma/client'; -import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; -import { Readable } from 'stream'; +import { isURL } from 'class-validator'; -export class DifyService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private readonly logger = new Logger('DifyService'); +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'dify', - }, - }); - - return { session }; - } catch (error) { - this.logger.error(error); - return; - } - } +export class DifyService extends BaseChatbotService { + private openaiService: OpenaiService; - private isImageMessage(content: string) { - return content.includes('imageMessage'); + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'DifyService', configService); + this.openaiService = openaiService; } - private isJSON(str: string): boolean { - try { - JSON.parse(str); - return true; - } catch (e) { - return false; - } + /** + * Return the bot type for Dify + */ + protected getBotType(): string { + return 'dify'; } - private async sendMessageToBot( + protected async sendMessageToBot( instance: any, session: IntegrationSession, settings: DifySetting, @@ -62,10 +37,30 @@ export class DifyService { remoteJid: string, pushName: string, content: string, - ) { + msg?: any, + ): Promise { try { let endpoint: string = dify.apiUrl; + if (!endpoint) { + this.logger.error('No Dify endpoint defined'); + return; + } + + // Handle audio messages - transcribe using OpenAI Whisper + let processedContent = content; + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[Dify] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + processedContent = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[Dify] Failed to transcribe audio: ${err}`); + } + } + if (dify.botType === 'chatBot') { endpoint += '/chat-messages'; const payload: any = { @@ -74,25 +69,45 @@ export class DifyService { pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, - query: content, + query: processedContent, response_mode: 'blocking', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - transfer_method: 'remote_url', - url: contentSplit[1].split('?')[0], - }, - ]; - payload.query = contentSplit[2] || content; + const media = content.split('|'); + + if (msg.message.mediaUrl || msg.message.base64) { + let mediaBase64 = msg.message.base64 || null; + + if (msg.message.mediaUrl && isURL(msg.message.mediaUrl)) { + const result = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }); + mediaBase64 = Buffer.from(result.data).toString('base64'); + } + + if (mediaBase64) { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: mediaBase64, + }, + ]; + } + } else { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: media[1].split('?')[0], + }, + ]; + } + payload.query = media[2] || content; } if (instance.integration === Integration.WHATSAPP_BAILEYS) { @@ -112,7 +127,9 @@ export class DifyService { const message = response?.data?.answer; const conversationId = response?.data?.conversation_id; - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); + } await this.prismaRepository.integrationSession.update({ where: { @@ -130,29 +147,49 @@ export class DifyService { endpoint += '/completion-messages'; const payload: any = { inputs: { - query: content, + query: processedContent, pushName: pushName, remoteJid: remoteJid, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, response_mode: 'blocking', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - transfer_method: 'remote_url', - url: contentSplit[1].split('?')[0], - }, - ]; - payload.inputs.query = contentSplit[2] || content; + const media = content.split('|'); + + if (msg.message.mediaUrl || msg.message.base64) { + let mediaBase64 = msg.message.base64 || null; + + if (msg.message.mediaUrl && isURL(msg.message.mediaUrl)) { + const result = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }); + mediaBase64 = Buffer.from(result.data).toString('base64'); + } + + if (mediaBase64) { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: mediaBase64, + }, + ]; + } + } else { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: media[1].split('?')[0], + }, + ]; + payload.inputs.query = media[2] || content; + } } if (instance.integration === Integration.WHATSAPP_BAILEYS) { @@ -172,7 +209,9 @@ export class DifyService { const message = response?.data?.answer; const conversationId = response?.data?.conversation_id; - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); + } await this.prismaRepository.integrationSession.update({ where: { @@ -194,25 +233,36 @@ export class DifyService { pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, - query: content, + query: processedContent, response_mode: 'streaming', conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, user: remoteJid, }; + // Handle image messages if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - transfer_method: 'remote_url', - url: contentSplit[1].split('?')[0], - }, - ]; - payload.query = contentSplit[2] || content; + const media = content.split('|'); + + if (msg.message.mediaUrl || msg.message.base64) { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: msg.message.mediaUrl || msg.message.base64, + }, + ]; + } else { + payload.files = [ + { + type: 'image', + transfer_method: 'remote_url', + url: media[1].split('?')[0], + }, + ]; + payload.query = media[2] || content; + } } if (instance.integration === Integration.WHATSAPP_BAILEYS) { @@ -224,113 +274,32 @@ export class DifyService { headers: { Authorization: `Bearer ${dify.apiKey}`, }, - responseType: 'stream', }); let conversationId; let answer = ''; - const stream = response.data; - const reader = new Readable().wrap(stream); - - reader.on('data', (chunk) => { - const data = chunk.toString().replace(/data:\s*/g, ''); - - if (data.trim() === '' || !data.startsWith('{')) { - return; - } - - try { - const events = data.split('\n').filter((line) => line.trim() !== ''); + const data = response.data.replaceAll('data: ', ''); + const events = data.split('\n').filter((line) => line.trim() !== ''); - for (const eventString of events) { - if (eventString.trim().startsWith('{')) { - const event = JSON.parse(eventString); + for (const eventString of events) { + if (eventString.trim().startsWith('{')) { + const event = JSON.parse(eventString); - if (event?.event === 'agent_message') { - console.log('event:', event); - conversationId = conversationId ?? event?.conversation_id; - answer += event?.answer; - } - } + if (event?.event === 'agent_message') { + console.log('event:', event); + conversationId = conversationId ?? event?.conversation_id; + answer += event?.answer; } - } catch (error) { - console.error('Error parsing stream data:', error); } - }); - - reader.on('end', async () => { - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = answer; - - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - sessionId: conversationId, - }, - }); - }); - - reader.on('error', (error) => { - console.error('Error reading stream:', error); - }); - - return; - } - - if (dify.botType === 'workflow') { - endpoint += '/workflows/run'; - const payload: any = { - inputs: { - query: content, - remoteJid: remoteJid, - pushName: pushName, - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - response_mode: 'blocking', - user: remoteJid, - }; - - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - transfer_method: 'remote_url', - url: contentSplit[1].split('?')[0], - }, - ]; - payload.inputs.query = contentSplit[2] || content; - } - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); } - const response = await axios.post(endpoint, payload, { - headers: { - Authorization: `Bearer ${dify.apiKey}`, - }, - }); - if (instance.integration === Integration.WHATSAPP_BAILEYS) await instance.client.sendPresenceUpdate('paused', remoteJid); - const message = response?.data?.data.outputs.text; - - await this.sendMessageWhatsApp(instance, remoteJid, message, settings); + if (answer) { + await this.sendMessageWhatsApp(instance, remoteJid, answer, settings, true); + } await this.prismaRepository.integrationSession.update({ where: { @@ -339,309 +308,13 @@ export class DifyService { data: { status: 'opened', awaitUser: true, + sessionId: session.sessionId === remoteJid ? conversationId : session.sessionId, }, }); - - return; } } catch (error) { this.logger.error(error.response?.data || error); return; } } - - private async sendMessageWhatsApp(instance: any, remoteJid: string, message: string, settings: DifySetting) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; - } - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - } - } - - sendTelemetry('/message/sendText'); - } - - private async initNewSession( - instance: any, - remoteJid: string, - dify: Dify, - settings: DifySetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: dify.id, - }); - - if (data.session) { - session = data.session; - } - - await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); - - return; - } - - public async processDify( - instance: any, - remoteJid: string, - dify: Dify, - session: IntegrationSession, - settings: DifySetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: dify.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); - return; - } - } - - if (!session) { - await this.initNewSession(instance, remoteJid, dify, settings, session, content, pushName); - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: dify.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - await this.sendMessageToBot(instance, session, settings, dify, remoteJid, pushName, content); - - return; - } } diff --git a/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts b/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts new file mode 100644 index 000000000..38ce433d4 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts @@ -0,0 +1,122 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { EvoaiDto } from '@api/integrations/chatbot/evoai/dto/evoai.dto'; +import { EvoaiService } from '@api/integrations/chatbot/evoai/services/evoai.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Evoai } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { Evoai as EvoaiModel, IntegrationSession } from '@prisma/client'; + +import { BaseChatbotController } from '../../base-chatbot.controller'; + +export class EvoaiController extends BaseChatbotController { + constructor( + private readonly evoaiService: EvoaiService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.evoai; + this.settingsRepository = this.prismaRepository.evoaiSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('EvoaiController'); + protected readonly integrationName = 'Evoai'; + + integrationEnabled = configService.get('EVOAI').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + protected getFallbackBotId(settings: any): string | undefined { + return settings?.evoaiIdFallback; + } + + protected getFallbackFieldName(): string { + return 'evoaiIdFallback'; + } + + protected getIntegrationType(): string { + return 'evoai'; + } + + protected getAdditionalBotData(data: EvoaiDto): Record { + return { + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }; + } + + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: EvoaiDto): Record { + return { + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }; + } + + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: EvoaiDto): Promise { + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Evoai already exists'); + } + } + + // Override createBot to add EvoAI-specific validation + public async createBot(instance: InstanceDto, data: EvoaiDto) { + if (!this.integrationEnabled) throw new BadRequestException('Evoai is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // EvoAI-specific duplicate check + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + agentUrl: data.agentUrl, + apiKey: data.apiKey, + }, + }); + + if (checkDuplicate) { + throw new Error('Evoai already exists'); + } + + // Let the base class handle the rest + return super.createBot(instance, data); + } + + // Process Evoai-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: EvoaiModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.evoaiService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } +} diff --git a/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts b/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts new file mode 100644 index 000000000..6043e7658 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/dto/evoai.dto.ts @@ -0,0 +1,10 @@ +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class EvoaiDto extends BaseChatbotDto { + agentUrl?: string; + apiKey?: string; +} + +export class EvoaiSettingDto extends BaseChatbotSettingDto { + evoaiIdFallback?: string; +} diff --git a/src/api/integrations/chatbot/evoai/routes/evoai.router.ts b/src/api/integrations/chatbot/evoai/routes/evoai.router.ts new file mode 100644 index 000000000..aadca01d6 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/routes/evoai.router.ts @@ -0,0 +1,124 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { evoaiController } from '@api/server.module'; +import { + evoaiIgnoreJidSchema, + evoaiSchema, + evoaiSettingSchema, + evoaiStatusSchema, + instanceSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { EvoaiDto, EvoaiSettingDto } from '../dto/evoai.dto'; + +export class EvoaiRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSchema, + ClassRef: EvoaiDto, + execute: (instance, data) => evoaiController.createBot(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.findBot(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchBot(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSchema, + ClassRef: EvoaiDto, + execute: (instance, data) => evoaiController.updateBot(instance, req.params.evoaiId, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.deleteBot(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiSettingSchema, + ClassRef: EvoaiSettingDto, + execute: (instance, data) => evoaiController.settings(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchSettings(instance), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => evoaiController.changeStatus(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:evoaiId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => evoaiController.fetchSessions(instance, req.params.evoaiId), + }); + + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: evoaiIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => evoaiController.ignoreJid(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/evoai/services/evoai.service.ts b/src/api/integrations/chatbot/evoai/services/evoai.service.ts new file mode 100644 index 000000000..c6ce5badc --- /dev/null +++ b/src/api/integrations/chatbot/evoai/services/evoai.service.ts @@ -0,0 +1,207 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { Integration } from '@api/types/wa.types'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { Evoai, EvoaiSetting, IntegrationSession } from '@prisma/client'; +import axios from 'axios'; +import { downloadMediaMessage } from 'baileys'; +import { isURL } from 'class-validator'; +import { v4 as uuidv4 } from 'uuid'; + +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class EvoaiService extends BaseChatbotService { + private openaiService: OpenaiService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'EvoaiService', configService); + this.openaiService = openaiService; + } + + /** + * Return the bot type for EvoAI + */ + protected getBotType(): string { + return 'evoai'; + } + + /** + * Implement the abstract method to send message to EvoAI API + * Handles audio transcription, image processing, and complex JSON-RPC payload + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: EvoaiSetting, + evoai: Evoai, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { + try { + this.logger.debug(`[EvoAI] Sending message to bot with content: ${content}`); + + let processedContent = content; + + // Handle audio messages - transcribe using OpenAI Whisper + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[EvoAI] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + processedContent = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[EvoAI] Failed to transcribe audio: ${err}`); + } + } + + const endpoint: string = evoai.agentUrl; + + if (!endpoint) { + this.logger.error('No EvoAI endpoint defined'); + return; + } + + const callId = `req-${uuidv4().substring(0, 8)}`; + const messageId = remoteJid.split('@')[0] || uuidv4(); // Use phone number as messageId + + // Prepare message parts + const parts = [ + { + type: 'text', + text: processedContent, + }, + ]; + + // Handle image message if present + if (this.isImageMessage(content) && msg) { + const media = content.split('|'); + parts[0].text = media[2] || content; + + try { + if (msg.message.mediaUrl || msg.message.base64) { + let mediaBase64 = msg.message.base64 || null; + + if (msg.message.mediaUrl && isURL(msg.message.mediaUrl)) { + const result = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }); + mediaBase64 = Buffer.from(result.data).toString('base64'); + } + + if (mediaBase64) { + parts.push({ + type: 'file', + file: { + name: msg.key.id + '.jpeg', + mimeType: 'image/jpeg', + bytes: mediaBase64, + }, + } as any); + } + } else { + // Download the image + const mediaBuffer = await downloadMediaMessage(msg, 'buffer', {}); + const fileContent = Buffer.from(mediaBuffer).toString('base64'); + const fileName = media[2] || `${msg.key?.id || 'image'}.jpg`; + + parts.push({ + type: 'file', + file: { + name: fileName, + mimeType: 'image/jpeg', + bytes: fileContent, + }, + } as any); + } + } catch (fileErr) { + this.logger.error(`[EvoAI] Failed to process image: ${fileErr}`); + } + } + + const payload = { + jsonrpc: '2.0', + id: callId, + method: 'message/send', + params: { + contextId: session.sessionId, + message: { + role: 'user', + parts, + messageId: messageId, + metadata: { + messageKey: msg?.key, + }, + }, + metadata: { + remoteJid: remoteJid, + pushName: pushName, + fromMe: msg?.key?.fromMe, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, + }, + }, + }; + + this.logger.debug(`[EvoAI] Sending request to: ${endpoint}`); + // Redact base64 file bytes from payload log + const redactedPayload = JSON.parse(JSON.stringify(payload)); + if (redactedPayload?.params?.message?.parts) { + redactedPayload.params.message.parts = redactedPayload.params.message.parts.map((part) => { + if (part.type === 'file' && part.file && part.file.bytes) { + return { ...part, file: { ...part.file, bytes: '[base64 omitted]' } }; + } + return part; + }); + } + this.logger.debug(`[EvoAI] Payload: ${JSON.stringify(redactedPayload)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); + } + + const response = await axios.post(endpoint, payload, { + headers: { + 'x-api-key': evoai.apiKey, + 'Content-Type': 'application/json', + }, + }); + + this.logger.debug(`[EvoAI] Response: ${JSON.stringify(response.data)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) + await instance.client.sendPresenceUpdate('paused', remoteJid); + + let message = undefined; + const result = response?.data?.result; + + // Extract message from artifacts array + if (result?.artifacts && Array.isArray(result.artifacts) && result.artifacts.length > 0) { + const artifact = result.artifacts[0]; + if (artifact?.parts && Array.isArray(artifact.parts)) { + const textPart = artifact.parts.find((p) => p.type === 'text' && p.text); + if (textPart) message = textPart.text; + } + } + + this.logger.debug(`[EvoAI] Extracted message to send: ${message}`); + + if (message) { + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); + } + } catch (error) { + this.logger.error( + `[EvoAI] Error sending message: ${error?.response?.data ? JSON.stringify(error.response.data) : error}`, + ); + return; + } + } +} diff --git a/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts b/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts new file mode 100644 index 000000000..59a070387 --- /dev/null +++ b/src/api/integrations/chatbot/evoai/validate/evoai.schema.ts @@ -0,0 +1,115 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const evoaiSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + agentUrl: { type: 'string' }, + apiKey: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: ['enabled', 'agentUrl', 'triggerType'], + ...isNotEmpty('enabled', 'agentUrl', 'triggerType'), +}; + +export const evoaiStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const evoaiSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ), +}; + +export const evoaiIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts index 329c18a9c..13ec5330d 100644 --- a/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts +++ b/src/api/integrations/chatbot/evolutionBot/controllers/evolutionBot.controller.ts @@ -1,16 +1,13 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Logger } from '@config/logger.config'; -import { EvolutionBot } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { EvolutionBot, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; import { EvolutionBotDto } from '../dto/evolutionBot.dto'; import { EvolutionBotService } from '../services/evolutionBot.service'; -export class EvolutionBotController extends ChatbotController implements ChatbotControllerInterface { +export class EvolutionBotController extends BaseChatbotController { constructor( private readonly evolutionBotService: EvolutionBotService, prismaRepository: PrismaRepository, @@ -24,258 +21,49 @@ export class EvolutionBotController extends ChatbotController implements Chatbot } public readonly logger = new Logger('EvolutionBotController'); + protected readonly integrationName = 'EvolutionBot'; - integrationEnabled: boolean; + integrationEnabled = true; // Set to true by default or use config value if available botRepository: any; settingsRepository: any; sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: EvolutionBotDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); + // Implementation of abstract methods required by BaseChatbotController - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a dify with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - instanceId: instanceId, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - }, - }); - - if (checkDuplicate) { - throw new Error('Dify already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating bot'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.botIdFallback; } - public async findBot(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + protected getFallbackFieldName(): string { + return 'botIdFallback'; } - public async fetchBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - return bot; + protected getIntegrationType(): string { + return 'evolution'; } - public async updateBot(instance: InstanceDto, botId: string, data: EvolutionBotDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); + protected getAdditionalBotData(data: EvolutionBotDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } - if (checkTriggerAll) { - throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); - } - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: EvolutionBotDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate( + botId: string, + instanceId: string, + data: EvolutionBotDto, + ): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { id: { @@ -288,579 +76,21 @@ export class EvolutionBotController extends ChatbotController implements Chatbot }); if (checkDuplicate) { - throw new Error('Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating bot'); + throw new Error('Evolution Bot already exists'); } } - public async deleteBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting bot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - botIdFallback: data.botIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - botIdFallback: updateSettings.botIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - botIdFallback: data.botIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - botIdFallback: newSetttings.botIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - botIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - botIdFallback: settings.botIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'evolution', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger( - this.botRepository, - this.settingsRepository, - content, - instance, - session, - )) as EvolutionBot; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.botIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.botIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.evolutionBotService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.evolutionBotService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Process bot-specific logic + protected async processBot( + instance: any, + remoteJid: string, + bot: EvolutionBot, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.evolutionBotService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } } diff --git a/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts index de2d952cd..dad8e559d 100644 --- a/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts +++ b/src/api/integrations/chatbot/evolutionBot/dto/evolutionBot.dto.ts @@ -1,37 +1,10 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; -export class EvolutionBotDto { - enabled?: boolean; - description?: string; - apiUrl?: string; - apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; +export class EvolutionBotDto extends BaseChatbotDto { + apiUrl: string; + apiKey: string; } -export class EvolutionBotSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class EvolutionBotSettingDto extends BaseChatbotSettingDto { botIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts index 3b8a8a4a8..13f3e9aaf 100644 --- a/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts +++ b/src/api/integrations/chatbot/evolutionBot/services/evolutionBot.service.ts @@ -1,428 +1,164 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; +import { ConfigService, HttpServer } from '@config/env.config'; import { EvolutionBot, EvolutionBotSetting, IntegrationSession } from '@prisma/client'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; +import { isURL } from 'class-validator'; -export class EvolutionBotService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} - - private readonly logger = new Logger('EvolutionBotService'); +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'evolution', - }, - }); +export class EvolutionBotService extends BaseChatbotService { + private openaiService: OpenaiService; - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'EvolutionBotService', configService); + this.openaiService = openaiService; } - private isImageMessage(content: string) { - return content.includes('imageMessage'); + /** + * Get the bot type identifier + */ + protected getBotType(): string { + return 'evolution'; } - private async sendMessageToBot( + /** + * Send a message to the Evolution Bot API + */ + protected async sendMessageToBot( instance: any, session: IntegrationSession, + settings: EvolutionBotSetting, bot: EvolutionBot, remoteJid: string, pushName: string, content: string, - ) { - const payload: any = { - inputs: { - sessionId: session.id, - remoteJid: remoteJid, - pushName: pushName, - instanceName: instance.instanceName, - serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, - }, - query: content, - conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, - user: remoteJid, - }; - - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); - - payload.files = [ - { - type: 'image', - url: contentSplit[1].split('?')[0], + msg?: any, + ): Promise { + try { + const payload: any = { + inputs: { + sessionId: session.id, + remoteJid: remoteJid, + pushName: pushName, + fromMe: msg?.key?.fromMe, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, }, - ]; - payload.query = contentSplit[2] || content; - } - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - let headers: any = { - 'Content-Type': 'application/json', - }; - - if (bot.apiKey) { - headers = { - ...headers, - Authorization: `Bearer ${bot.apiKey}`, + query: content, + conversation_id: session.sessionId === remoteJid ? undefined : session.sessionId, + user: remoteJid, }; - } - - const response = await axios.post(bot.apiUrl, payload, { - headers, - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); - const message = response?.data?.message; - - return message; - } - - private async sendMessageWhatsApp( - instance: any, - remoteJid: string, - session: IntegrationSession, - settings: EvolutionBotSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[EvolutionBot] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.query = `[audio] ${transcription}`; } + } catch (err) { + this.logger.error(`[EvolutionBot] Failed to transcribe audio: ${err}`); } + } + + if (this.isImageMessage(content) && msg) { + const media = content.split('|'); - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); + if (msg.message.mediaUrl || msg.message.base64) { + payload.files = [ + { + type: 'image', + url: msg.message.base64 || msg.message.mediaUrl, + }, + ]; } else { - await instance.mediaMessage( + payload.files = [ { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, + type: 'image', + url: media[1].split('?')[0], }, - null, - false, - ); + ]; } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; + payload.query = media[2] || content; } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); } - } - - sendTelemetry('/message/sendText'); - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - } - - private async initNewSession( - instance: any, - remoteJid: string, - bot: EvolutionBot, - settings: EvolutionBotSetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: bot.id, - }); - - if (data.session) { - session = data.session; - } - const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); - - if (!message) return; - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; - } + const endpoint = bot.apiUrl; - public async processBot( - instance: any, - remoteJid: string, - bot: EvolutionBot, - session: IntegrationSession, - settings: EvolutionBotSetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); + if (!endpoint) { + this.logger.error('No Evolution Bot endpoint defined'); + return; + } - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + let headers: any = { + 'Content-Type': 'application/json', + }; - const diff = now - sessionUpdatedAt; + if (bot.apiKey) { + headers = { + ...headers, + Authorization: `Bearer ${bot.apiKey}`, + }; + } - const diffInMinutes = Math.floor(diff / 1000 / 60); + // Sanitize payload for logging (remove sensitive data) + const sanitizedPayload = { + ...payload, + inputs: { + ...payload.inputs, + apiKey: payload.inputs.apiKey ? '[REDACTED]' : undefined, + }, + }; - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } + const response = await axios.post(endpoint, payload, { + headers, + }); - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); } - } - if (!session) { - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } + let message = response?.data?.message; + const rawLinkPreview = response?.data?.linkPreview; - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); + // Validate linkPreview is boolean and default to true for backward compatibility + const linkPreview = typeof rawLinkPreview === 'boolean' ? rawLinkPreview : true; - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); + if (message && typeof message === 'string' && message.startsWith("'") && message.endsWith("'")) { + const innerContent = message.slice(1, -1); + if (!innerContent.includes("'")) { + message = innerContent; + } } - return; - } - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); + if (message) { + // Use the base class method that handles splitMessages functionality + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, linkPreview); } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); + this.logger.warn(`[EvolutionBot] No message content received from bot response`); } + + // Send telemetry + sendTelemetry('/message/sendText'); + } catch (error) { + this.logger.error(`Error in sendMessageToBot: ${error.message || JSON.stringify(error)}`); return; } - - const message = await this.sendMessageToBot(instance, session, bot, remoteJid, pushName, content); - - if (!message) return; - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; } } diff --git a/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts index 67b572f1c..fbd9ea90b 100644 --- a/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts +++ b/src/api/integrations/chatbot/flowise/controllers/flowise.controller.ts @@ -1,16 +1,16 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Flowise } from '@config/env.config'; import { Logger } from '@config/logger.config'; -import { Flowise } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { BadRequestException } from '@exceptions'; +import { Flowise as FlowiseModel, IntegrationSession } from '@prisma/client'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; import { FlowiseDto } from '../dto/flowise.dto'; import { FlowiseService } from '../services/flowise.service'; -export class FlowiseController extends ChatbotController implements ChatbotControllerInterface { +export class FlowiseController extends BaseChatbotController { constructor( private readonly flowiseService: FlowiseService, prismaRepository: PrismaRepository, @@ -24,93 +24,44 @@ export class FlowiseController extends ChatbotController implements ChatbotContr } public readonly logger = new Logger('FlowiseController'); + protected readonly integrationName = 'Flowise'; - integrationEnabled: boolean; + integrationEnabled = configService.get('FLOWISE').ENABLED; botRepository: any; settingsRepository: any; sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: FlowiseDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); + protected getFallbackBotId(settings: any): string | undefined { + return settings?.flowiseIdFallback; + } - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; + protected getFallbackFieldName(): string { + return 'flowiseIdFallback'; + } - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } + protected getIntegrationType(): string { + return 'flowise'; + } - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); + protected getAdditionalBotData(data: FlowiseDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a Flowise with an "All" trigger, you cannot have more bots while it is active'); - } + protected getAdditionalUpdateFields(data: FlowiseDto): Record { + return { + apiUrl: data.apiUrl, + apiKey: data.apiKey, + }; + } + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: FlowiseDto): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { + id: { not: botId }, instanceId: instanceId, apiUrl: data.apiUrl, apiKey: data.apiKey, @@ -120,123 +71,26 @@ export class FlowiseController extends ChatbotController implements ChatbotContr if (checkDuplicate) { throw new Error('Flowise already exists'); } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating bot'); - } } - public async findBot(instance: InstanceDto) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + // Process Flowise-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: FlowiseModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.flowiseService.processBot(instance, remoteJid, bot, session, settings, content, pushName, msg); } - public async fetchBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - return bot; - } + // Override createBot to add module availability check and Flowise-specific validation + public async createBot(instance: InstanceDto, data: FlowiseDto) { + if (!this.integrationEnabled) throw new BadRequestException('Flowise is disabled'); - public async updateBot(instance: InstanceDto, botId: string, data: FlowiseDto) { const instanceId = await this.prismaRepository.instance .findFirst({ where: { @@ -245,42 +99,9 @@ export class FlowiseController extends ChatbotController implements ChatbotContr }) .then((instance) => instance.id); - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error('You already have a bot with an "All" trigger, you cannot have more bots while it is active'); - } - } - + // Flowise-specific duplicate check const checkDuplicate = await this.botRepository.findFirst({ where: { - id: { - not: botId, - }, instanceId: instanceId, apiUrl: data.apiUrl, apiKey: data.apiKey, @@ -288,579 +109,10 @@ export class FlowiseController extends ChatbotController implements ChatbotContr }); if (checkDuplicate) { - throw new Error('Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - apiUrl: data.apiUrl, - apiKey: data.apiKey, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating bot'); - } - } - - public async deleteBot(instance: InstanceDto, botId: string) { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Bot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { bot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting bot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - flowiseIdFallback: data.flowiseIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - flowiseIdFallback: updateSettings.flowiseIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - flowiseIdFallback: data.flowiseIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - flowiseIdFallback: newSetttings.flowiseIdFallback, - ignoreJids: newSetttings.ignoreJids, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - flowiseIdFallback: '', - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - flowiseIdFallback: settings.flowiseIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { bot: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - } - - return { bot: { ...instance, bot: { remoteJid: remoteJid, status: status } } }; - } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const botData = { - remoteJid: remoteJid, - status: status, - session, - }; - - return { bot: { ...instance, bot: botData } }; - } - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (bot && bot.instanceId !== instanceId) { - throw new Error('Dify not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: bot ? botId : { not: null }, - type: 'flowise', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); + throw new Error('Flowise already exists'); } - } - - // Emit - public async emit({ instance, remoteJid, msg }: EmitData) { - try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - let findBot = (await this.findBotTrigger( - this.botRepository, - this.settingsRepository, - content, - instance, - session, - )) as Flowise; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.flowiseIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.flowiseIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.flowiseService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - msg?.pushName, - ); - }); - } else { - await this.flowiseService.processBot( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - content, - msg?.pushName, - ); - } - - return; - } catch (error) { - this.logger.error(error); - return; - } + // Let the base class handle the rest + return super.createBot(instance, data); } } diff --git a/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts index 98e612ad6..4bbe1be38 100644 --- a/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts +++ b/src/api/integrations/chatbot/flowise/dto/flowise.dto.ts @@ -1,37 +1,10 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; -export class FlowiseDto { - enabled?: boolean; - description?: string; - apiUrl?: string; +export class FlowiseDto extends BaseChatbotDto { + apiUrl: string; apiKey?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class FlowiseSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class FlowiseSettingDto extends BaseChatbotSettingDto { flowiseIdFallback?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/flowise/services/flowise.service.ts b/src/api/integrations/chatbot/flowise/services/flowise.service.ts index d1ab4e2f6..8002eaf14 100644 --- a/src/api/integrations/chatbot/flowise/services/flowise.service.ts +++ b/src/api/integrations/chatbot/flowise/services/flowise.service.ts @@ -1,76 +1,110 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { Auth, ConfigService, HttpServer } from '@config/env.config'; -import { Logger } from '@config/logger.config'; -import { Flowise, FlowiseSetting, IntegrationSession } from '@prisma/client'; -import { sendTelemetry } from '@utils/sendTelemetry'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { Flowise as FlowiseModel, IntegrationSession } from '@prisma/client'; import axios from 'axios'; +import { isURL } from 'class-validator'; -export class FlowiseService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; - private readonly logger = new Logger('FlowiseService'); +export class FlowiseService extends BaseChatbotService { + private openaiService: OpenaiService; - public async createNewSession(instance: InstanceDto, data: any) { - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: data.remoteJid, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'flowise', - }, - }); + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'FlowiseService', configService); + this.openaiService = openaiService; + } - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + // Return the bot type for Flowise + protected getBotType(): string { + return 'flowise'; } - private isImageMessage(content: string) { - return content.includes('imageMessage'); + // Process Flowise-specific bot logic + public async processBot( + instance: any, + remoteJid: string, + bot: FlowiseModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.process(instance, remoteJid, bot, session, settings, content, pushName, msg); } - private async sendMessageToBot(instance: any, bot: Flowise, remoteJid: string, pushName: string, content: string) { + // Implement the abstract method to send message to Flowise API + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: any, + bot: FlowiseModel, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { const payload: any = { question: content, overrideConfig: { sessionId: remoteJid, vars: { + messageId: msg?.key?.id, + fromMe: msg?.key?.fromMe, remoteJid: remoteJid, pushName: pushName, instanceName: instance.instanceName, serverUrl: this.configService.get('SERVER').URL, - apiKey: this.configService.get('AUTHENTICATION').API_KEY.KEY, + apiKey: instance.token, }, }, }; + // Handle audio messages + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[Flowise] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.question = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[Flowise] Failed to transcribe audio: ${err}`); + } + } + if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); + const media = content.split('|'); - payload.uploads = [ - { - data: contentSplit[1].split('?')[0], - type: 'url', - name: 'Flowise.png', - mime: 'image/png', - }, - ]; - payload.question = contentSplit[2] || content; + if (msg.message.mediaUrl || msg.message.base64) { + payload.uploads = [ + { + data: msg.message.base64 || msg.message.mediaUrl, + type: 'url', + name: 'Flowise.png', + mime: 'image/png', + }, + ]; + } else { + payload.uploads = [ + { + data: media[1].split('?')[0], + type: 'url', + name: 'Flowise.png', + mime: 'image/png', + }, + ]; + payload.question = media[2] || content; + } } if (instance.integration === Integration.WHATSAPP_BAILEYS) { @@ -91,335 +125,26 @@ export class FlowiseService { const endpoint = bot.apiUrl; - if (!endpoint) return null; + if (!endpoint) { + this.logger.error('No Flowise endpoint defined'); + return; + } const response = await axios.post(endpoint, payload, { headers, }); - if (instance.integration === Integration.WHATSAPP_BAILEYS) + if (instance.integration === Integration.WHATSAPP_BAILEYS) { await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data?.text; - - return message; - } - - private async sendMessageWhatsApp( - instance: any, - remoteJid: string, - session: IntegrationSession, - settings: FlowiseSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; - } - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; - } - - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; - } } - sendTelemetry('/message/sendText'); - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: true, - }, - }); - - return; - } - - private async initNewSession( - instance: any, - remoteJid: string, - bot: Flowise, - settings: FlowiseSetting, - session: IntegrationSession, - content: string, - pushName?: string, - ) { - const data = await this.createNewSession(instance, { - remoteJid, - pushName, - botId: bot.id, - }); + const message = response?.data?.text; - if (data.session) { - session = data.session; + if (message) { + // Use the base class method to send the message to WhatsApp + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); } - - const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; } - public async processBot( - instance: any, - remoteJid: string, - bot: Flowise, - session: IntegrationSession, - settings: FlowiseSetting, - content: string, - pushName?: string, - ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - - const diff = now - sessionUpdatedAt; - - const diffInMinutes = Math.floor(diff / 1000 / 60); - - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } - - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } - } - - if (!session) { - await this.initNewSession(instance, remoteJid, bot, settings, session, content, pushName); - return; - } - - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; - } - - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: bot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } - - const message = await this.sendMessageToBot(instance, bot, remoteJid, pushName, content); - - await this.sendMessageWhatsApp(instance, remoteJid, session, settings, message); - - return; - } + // The service is now complete with just the abstract method implementations } diff --git a/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts index 83f9d1eaa..3283d2470 100644 --- a/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts +++ b/src/api/integrations/chatbot/flowise/validate/flowise.schema.ts @@ -40,6 +40,8 @@ export const flowiseSchema: JSONSchema7 = { keepOpen: { type: 'boolean' }, debounceTime: { type: 'integer' }, ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, }, required: ['enabled', 'apiUrl', 'triggerType'], ...isNotEmpty('enabled', 'apiUrl', 'triggerType'), @@ -69,7 +71,9 @@ export const flowiseSettingSchema: JSONSchema7 = { keepOpen: { type: 'boolean' }, debounceTime: { type: 'integer' }, ignoreJids: { type: 'array', items: { type: 'string' } }, - botIdFallback: { type: 'string' }, + flowiseIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, }, required: [ 'expire', diff --git a/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts b/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts new file mode 100644 index 000000000..0eb7f7a61 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts @@ -0,0 +1,127 @@ +import { InstanceDto } from '@api/dto/instance.dto'; +import { N8nDto } from '@api/integrations/chatbot/n8n/dto/n8n.dto'; +import { N8nService } from '@api/integrations/chatbot/n8n/services/n8n.service'; +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { BadRequestException } from '@exceptions'; +import { IntegrationSession, N8n as N8nModel } from '@prisma/client'; + +import { BaseChatbotController } from '../../base-chatbot.controller'; + +export class N8nController extends BaseChatbotController { + constructor( + private readonly n8nService: N8nService, + prismaRepository: PrismaRepository, + waMonitor: WAMonitoringService, + ) { + super(prismaRepository, waMonitor); + + this.botRepository = this.prismaRepository.n8n; + this.settingsRepository = this.prismaRepository.n8nSetting; + this.sessionRepository = this.prismaRepository.integrationSession; + } + + public readonly logger = new Logger('N8nController'); + protected readonly integrationName = 'N8n'; + + integrationEnabled = configService.get('N8N').ENABLED; + botRepository: any; + settingsRepository: any; + sessionRepository: any; + userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; + + protected getFallbackBotId(settings: any): string | undefined { + return settings?.fallbackId; + } + + protected getFallbackFieldName(): string { + return 'n8nIdFallback'; + } + + protected getIntegrationType(): string { + return 'n8n'; + } + + protected getAdditionalBotData(data: N8nDto): Record { + return { + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }; + } + + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: N8nDto): Record { + return { + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }; + } + + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: N8nDto): Promise { + const checkDuplicate = await this.botRepository.findFirst({ + where: { + id: { + not: botId, + }, + instanceId: instanceId, + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }, + }); + + if (checkDuplicate) { + throw new Error('N8n already exists'); + } + } + + // Bots + public async createBot(instance: InstanceDto, data: N8nDto) { + if (!this.integrationEnabled) throw new BadRequestException('N8n is disabled'); + + const instanceId = await this.prismaRepository.instance + .findFirst({ + where: { + name: instance.instanceName, + }, + }) + .then((instance) => instance.id); + + // Check for N8n-specific duplicate + const checkDuplicate = await this.botRepository.findFirst({ + where: { + instanceId: instanceId, + webhookUrl: data.webhookUrl, + basicAuthUser: data.basicAuthUser, + basicAuthPass: data.basicAuthPass, + }, + }); + + if (checkDuplicate) { + throw new Error('N8n already exists'); + } + + // Let the base class handle the rest of the bot creation process + return super.createBot(instance, data); + } + + // Process N8n-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: N8nModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + // Use the base class pattern instead of calling n8nService.process directly + await this.n8nService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } +} diff --git a/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts b/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts new file mode 100644 index 000000000..c844f76e0 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/dto/n8n.dto.ts @@ -0,0 +1,17 @@ +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; + +export class N8nDto extends BaseChatbotDto { + // N8n specific fields + webhookUrl?: string; + basicAuthUser?: string; + basicAuthPass?: string; +} + +export class N8nSettingDto extends BaseChatbotSettingDto { + // N8n has no specific fields +} + +export class N8nMessageDto { + chatInput: string; + sessionId: string; +} diff --git a/src/api/integrations/chatbot/n8n/routes/n8n.router.ts b/src/api/integrations/chatbot/n8n/routes/n8n.router.ts new file mode 100644 index 000000000..1fbf50d23 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/routes/n8n.router.ts @@ -0,0 +1,114 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { IgnoreJidDto } from '@api/dto/chatbot.dto'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { n8nController } from '@api/server.module'; +import { + instanceSchema, + n8nIgnoreJidSchema, + n8nSchema, + n8nSettingSchema, + n8nStatusSchema, +} from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { N8nDto, N8nSettingDto } from '../dto/n8n.dto'; + +export class N8nRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('create'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSchema, + ClassRef: N8nDto, + execute: (instance, data) => n8nController.createBot(instance, data), + }); + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.findBot(instance), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetch/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchBot(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .put(this.routerPath('update/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSchema, + ClassRef: N8nDto, + execute: (instance, data) => n8nController.updateBot(instance, req.params.n8nId, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .delete(this.routerPath('delete/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.deleteBot(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('settings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nSettingSchema, + ClassRef: N8nSettingDto, + execute: (instance, data) => n8nController.settings(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSettings'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchSettings(instance), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('changeStatus'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nStatusSchema, + ClassRef: InstanceDto, + execute: (instance, data) => n8nController.changeStatus(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }) + .get(this.routerPath('fetchSessions/:n8nId'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => n8nController.fetchSessions(instance, req.params.n8nId), + }); + res.status(HttpStatus.OK).json(response); + }) + .post(this.routerPath('ignoreJid'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: n8nIgnoreJidSchema, + ClassRef: IgnoreJidDto, + execute: (instance, data) => n8nController.ignoreJid(instance, data), + }); + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/chatbot/n8n/services/n8n.service.ts b/src/api/integrations/chatbot/n8n/services/n8n.service.ts new file mode 100644 index 000000000..7da8ac28b --- /dev/null +++ b/src/api/integrations/chatbot/n8n/services/n8n.service.ts @@ -0,0 +1,98 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { ConfigService, HttpServer } from '@config/env.config'; +import { IntegrationSession, N8n, N8nSetting } from '@prisma/client'; +import axios from 'axios'; + +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class N8nService extends BaseChatbotService { + private openaiService: OpenaiService; + + constructor( + waMonitor: WAMonitoringService, + prismaRepository: PrismaRepository, + configService: ConfigService, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'N8nService', configService); + this.openaiService = openaiService; + } + + /** + * Return the bot type for N8n + */ + protected getBotType(): string { + return 'n8n'; + } + + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: N8nSetting, + n8n: N8n, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ) { + try { + if (!session) { + this.logger.error('Session is null in sendMessageToBot'); + return; + } + + const endpoint: string = n8n.webhookUrl; + const payload: any = { + chatInput: content, + sessionId: session.sessionId, + remoteJid: remoteJid, + pushName: pushName, + keyId: msg?.key?.id, + fromMe: msg?.key?.fromMe, + quotedMessage: msg?.contextInfo?.quotedMessage, + instanceName: instance.instanceName, + serverUrl: this.configService.get('SERVER').URL, + apiKey: instance.token, + }; + + // Handle audio messages + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[N8n] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + payload.chatInput = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[N8n] Failed to transcribe audio: ${err}`); + } + } + + const headers: Record = {}; + if (n8n.basicAuthUser && n8n.basicAuthPass) { + const auth = Buffer.from(`${n8n.basicAuthUser}:${n8n.basicAuthPass}`).toString('base64'); + headers['Authorization'] = `Basic ${auth}`; + } + const response = await axios.post(endpoint, payload, { headers }); + const message = response?.data?.output || response?.data?.answer; + + // Use base class method instead of custom implementation + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); + + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(error.response?.data || error); + return; + } + } +} diff --git a/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts b/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts new file mode 100644 index 000000000..b1382ac31 --- /dev/null +++ b/src/api/integrations/chatbot/n8n/validate/n8n.schema.ts @@ -0,0 +1,116 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + }; +}; + +export const n8nSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean' }, + description: { type: 'string' }, + webhookUrl: { type: 'string' }, + basicAuthUser: { type: 'string' }, + basicAuthPassword: { type: 'string' }, + triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] }, + triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] }, + triggerValue: { type: 'string' }, + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: ['enabled', 'webhookUrl', 'triggerType'], + ...isNotEmpty('enabled', 'webhookUrl', 'triggerType'), +}; + +export const n8nStatusSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + status: { type: 'string', enum: ['opened', 'closed', 'paused', 'delete'] }, + }, + required: ['remoteJid', 'status'], + ...isNotEmpty('remoteJid', 'status'), +}; + +export const n8nSettingSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + expire: { type: 'integer' }, + keywordFinish: { type: 'string' }, + delayMessage: { type: 'integer' }, + unknownMessage: { type: 'string' }, + listeningFromMe: { type: 'boolean' }, + stopBotFromMe: { type: 'boolean' }, + keepOpen: { type: 'boolean' }, + debounceTime: { type: 'integer' }, + ignoreJids: { type: 'array', items: { type: 'string' } }, + botIdFallback: { type: 'string' }, + splitMessages: { type: 'boolean' }, + timePerChar: { type: 'integer' }, + }, + required: [ + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ], + ...isNotEmpty( + 'expire', + 'keywordFinish', + 'delayMessage', + 'unknownMessage', + 'listeningFromMe', + 'stopBotFromMe', + 'keepOpen', + 'debounceTime', + 'ignoreJids', + 'splitMessages', + 'timePerChar', + ), +}; + +export const n8nIgnoreJidSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + remoteJid: { type: 'string' }, + action: { type: 'string', enum: ['add', 'remove'] }, + }, + required: ['remoteJid', 'action'], + ...isNotEmpty('remoteJid', 'action'), +}; diff --git a/src/api/integrations/chatbot/openai/controllers/openai.controller.ts b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts index 3d28ff4ac..1d9910d1f 100644 --- a/src/api/integrations/chatbot/openai/controllers/openai.controller.ts +++ b/src/api/integrations/chatbot/openai/controllers/openai.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { OpenaiCredsDto, OpenaiDto } from '@api/integrations/chatbot/openai/dto/openai.dto'; import { OpenaiService } from '@api/integrations/chatbot/openai/services/openai.service'; @@ -7,13 +6,12 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { configService, Openai } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { OpenaiBot } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { IntegrationSession, OpenaiBot } from '@prisma/client'; import OpenAI from 'openai'; -import { ChatbotController, ChatbotControllerInterface, EmitData } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class OpenaiController extends ChatbotController implements ChatbotControllerInterface { +export class OpenaiController extends BaseChatbotController { constructor( private readonly openaiService: OpenaiService, prismaRepository: PrismaRepository, @@ -28,6 +26,7 @@ export class OpenaiController extends ChatbotController implements ChatbotContro } public readonly logger = new Logger('OpenaiController'); + protected readonly integrationName = 'Openai'; integrationEnabled = configService.get('OPENAI').ENABLED; botRepository: any; @@ -37,139 +36,88 @@ export class OpenaiController extends ChatbotController implements ChatbotContro private client: OpenAI; private credsRepository: any; - // Credentials - public async createOpenaiCreds(instance: InstanceDto, data: OpenaiCredsDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if (!data.apiKey) throw new Error('API Key is required'); - if (!data.name) throw new Error('Name is required'); - - try { - const creds = await this.credsRepository.create({ - data: { - name: data.name, - apiKey: data.apiKey, - instanceId: instanceId, - }, - }); - - return creds; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating openai creds'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.openaiIdFallback; } - public async findOpenaiCreds(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const creds = await this.credsRepository.findMany({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiAssistant: true, - }, - }); + protected getFallbackFieldName(): string { + return 'openaiIdFallback'; + } - return creds; + protected getIntegrationType(): string { + return 'openai'; } - public async deleteCreds(instance: InstanceDto, openaiCredsId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + protected getAdditionalBotData(data: OpenaiDto): Record { + return { + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + }; + } - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: OpenaiDto): Record { + return { + openaiCredsId: data.openaiCredsId, + botType: data.botType, + assistantId: data.assistantId, + functionUrl: data.functionUrl, + model: data.model, + systemMessages: data.systemMessages, + assistantMessages: data.assistantMessages, + userMessages: data.userMessages, + maxTokens: data.maxTokens, + }; + } - const creds = await this.credsRepository.findFirst({ - where: { - id: openaiCredsId, + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: OpenaiDto): Promise { + let whereDuplication: any = { + id: { + not: botId, }, - }); - - if (!creds) { - throw new Error('Openai Creds not found'); - } + instanceId: instanceId, + }; - if (creds.instanceId !== instanceId) { - throw new Error('Openai Creds not found'); - } + if (data.botType === 'assistant') { + if (!data.assistantId) throw new Error('Assistant ID is required'); - try { - await this.credsRepository.delete({ - where: { - id: openaiCredsId, - }, - }); + whereDuplication = { + ...whereDuplication, + assistantId: data.assistantId, + botType: data.botType, + }; + } else if (data.botType === 'chatCompletion') { + if (!data.model) throw new Error('Model is required'); + if (!data.maxTokens) throw new Error('Max tokens is required'); - return { openaiCreds: { id: openaiCredsId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting openai creds'); + whereDuplication = { + ...whereDuplication, + model: data.model, + maxTokens: data.maxTokens, + botType: data.botType, + }; + } else { + throw new Error('Bot type is required'); } - } - - // Models - public async getModels(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if (!instanceId) throw new Error('Instance not found'); - - const defaultSettings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - OpenaiCreds: true, - }, + const checkDuplicate = await this.botRepository.findFirst({ + where: whereDuplication, }); - if (!defaultSettings) throw new Error('Settings not found'); - - const { apiKey } = defaultSettings.OpenaiCreds; - - try { - this.client = new OpenAI({ apiKey }); - - const models: any = await this.client.models.list(); - - return models?.body?.data; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching models'); + if (checkDuplicate) { + throw new Error('OpenAI Bot already exists'); } } - // Bots + // Override createBot to handle OpenAI-specific credential logic public async createBot(instance: InstanceDto, data: OpenaiDto) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); @@ -181,80 +129,7 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - if ( - !data.openaiCredsId || - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids || - !data.splitMessages || - !data.timePerChar - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (data.expire === undefined || data.expire === null) data.expire = defaultSettingCheck.expire; - if (data.keywordFinish === undefined || data.keywordFinish === null) - data.keywordFinish = defaultSettingCheck.keywordFinish; - if (data.delayMessage === undefined || data.delayMessage === null) - data.delayMessage = defaultSettingCheck.delayMessage; - if (data.unknownMessage === undefined || data.unknownMessage === null) - data.unknownMessage = defaultSettingCheck.unknownMessage; - if (data.listeningFromMe === undefined || data.listeningFromMe === null) - data.listeningFromMe = defaultSettingCheck.listeningFromMe; - if (data.stopBotFromMe === undefined || data.stopBotFromMe === null) - data.stopBotFromMe = defaultSettingCheck.stopBotFromMe; - if (data.keepOpen === undefined || data.keepOpen === null) data.keepOpen = defaultSettingCheck.keepOpen; - if (data.debounceTime === undefined || data.debounceTime === null) - data.debounceTime = defaultSettingCheck.debounceTime; - if (data.ignoreJids === undefined || data.ignoreJids === null) data.ignoreJids = defaultSettingCheck.ignoreJids; - if (data.splitMessages === undefined || data.splitMessages === null) - data.splitMessages = defaultSettingCheck?.splitMessages ?? false; - if (data.timePerChar === undefined || data.timePerChar === null) - data.timePerChar = defaultSettingCheck?.timePerChar ?? 0; - - if (!data.openaiCredsId) { - throw new Error('Openai Creds Id is required'); - } - - if (!defaultSettingCheck) { - await this.settings(instance, { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a openai with an "All" trigger, you cannot have more bots while it is active'); - } - + // OpenAI specific validation let whereDuplication: any = { instanceId: instanceId, }; @@ -289,81 +164,64 @@ export class OpenaiController extends ChatbotController implements ChatbotContro throw new Error('Openai Bot already exists'); } - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } + // Check if settings exist and create them if not + const existingSettings = await this.settingsRepository.findFirst({ + where: { + instanceId: instanceId, + }, + }); - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, + if (!existingSettings) { + // Create default settings with the OpenAI credentials + await this.settings(instance, { + openaiCredsId: data.openaiCredsId, + expire: data.expire || 300, + keywordFinish: data.keywordFinish || 'bye', + delayMessage: data.delayMessage || 1000, + unknownMessage: data.unknownMessage || 'Sorry, I dont understand', + listeningFromMe: data.listeningFromMe !== undefined ? data.listeningFromMe : true, + stopBotFromMe: data.stopBotFromMe !== undefined ? data.stopBotFromMe : true, + keepOpen: data.keepOpen !== undefined ? data.keepOpen : false, + debounceTime: data.debounceTime || 1, + ignoreJids: data.ignoreJids || [], + speechToText: false, }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ + } else if (!existingSettings.openaiCredsId && data.openaiCredsId) { + // Update settings with OpenAI credentials if they're missing + await this.settingsRepository.update({ where: { - triggerValue: data.triggerValue, - instanceId: instanceId, + id: existingSettings.id, }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ data: { - enabled: data?.enabled, - description: data.description, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - functionUrl: data.functionUrl, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, + OpenaiCreds: { + connect: { + id: data.openaiCredsId, + }, + }, }, }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating openai bot'); } + + // Let the base class handle the rest of the bot creation process + return super.createBot(instance, data); } - public async findBot(instance: InstanceDto) { + // Process OpenAI-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: OpenaiBot, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + await this.openaiService.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } + + // Credentials - OpenAI specific functionality + public async createOpenaiCreds(instance: InstanceDto, data: OpenaiCredsDto) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); const instanceId = await this.prismaRepository.instance @@ -374,48 +232,49 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - const bots = await this.botRepository.findMany({ + if (!data.apiKey) throw new BadRequestException('API Key is required'); + if (!data.name) throw new BadRequestException('Name is required'); + + // Check if API key already exists + const existingApiKey = await this.credsRepository.findFirst({ where: { - instanceId, + apiKey: data.apiKey, }, }); - if (!bots.length) { - return null; + if (existingApiKey) { + throw new BadRequestException('This API key is already registered. Please use a different API key.'); } - return bots; - } - - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ + // Check if name already exists for this instance + const existingName = await this.credsRepository.findFirst({ where: { - id: botId, + name: data.name, + instanceId: instanceId, }, }); - if (!bot) { - throw new Error('Openai Bot not found'); + if (existingName) { + throw new BadRequestException('This credential name is already in use. Please choose a different name.'); } - if (bot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } + try { + const creds = await this.credsRepository.create({ + data: { + name: data.name, + apiKey: data.apiKey, + instanceId: instanceId, + }, + }); - return bot; + return creds; + } catch (error) { + this.logger.error(error); + throw new Error('Error creating openai creds'); + } } - public async updateBot(instance: InstanceDto, botId: string, data: OpenaiDto) { + public async findOpenaiCreds(instance: InstanceDto) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); const instanceId = await this.prismaRepository.instance @@ -426,154 +285,19 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - const bot = await this.botRepository.findFirst({ + const creds = await this.credsRepository.findMany({ where: { - id: botId, + instanceId: instanceId, }, - }); - - if (!bot) { - throw new Error('Openai Bot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkTriggerAll) { - throw new Error( - 'You already have a openai bot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } - - let whereDuplication: any = { - id: { - not: botId, + include: { + OpenaiAssistant: true, }, - instanceId: instanceId, - }; - - if (data.botType === 'assistant') { - if (!data.assistantId) throw new Error('Assistant ID is required'); - - whereDuplication = { - ...whereDuplication, - assistantId: data.assistantId, - }; - } else if (data.botType === 'chatCompletion') { - if (!data.model) throw new Error('Model is required'); - if (!data.maxTokens) throw new Error('Max tokens is required'); - - whereDuplication = { - ...whereDuplication, - model: data.model, - maxTokens: data.maxTokens, - }; - } else { - throw new Error('Bot type is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: whereDuplication, }); - if (checkDuplicate) { - throw new Error('Openai Bot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - openaiCredsId: data.openaiCredsId, - botType: data.botType, - assistantId: data.assistantId, - functionUrl: data.functionUrl, - model: data.model, - systemMessages: data.systemMessages, - assistantMessages: data.assistantMessages, - userMessages: data.userMessages, - maxTokens: data.maxTokens, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating openai bot'); - } + return creds; } - public async deleteBot(instance: InstanceDto, botId: string) { + public async deleteCreds(instance: InstanceDto, openaiCredsId: string) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); const instanceId = await this.prismaRepository.instance @@ -584,40 +308,35 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - const bot = await this.botRepository.findFirst({ + const creds = await this.credsRepository.findFirst({ where: { - id: botId, + id: openaiCredsId, }, }); - if (!bot) { - throw new Error('Openai bot not found'); + if (!creds) { + throw new Error('Openai Creds not found'); } - if (bot.instanceId !== instanceId) { - throw new Error('Openai bot not found'); + if (creds.instanceId !== instanceId) { + throw new Error('Openai Creds not found'); } - try { - await this.sessionRepository.deleteMany({ - where: { - botId: botId, - }, - }); - await this.botRepository.delete({ + try { + await this.credsRepository.delete({ where: { - id: botId, + id: openaiCredsId, }, }); - return { bot: { id: botId } }; + return { openaiCreds: { id: openaiCredsId } }; } catch (error) { this.logger.error(error); - throw new Error('Error deleting openai bot'); + throw new Error('Error deleting openai creds'); } } - // Settings + // Override the settings method to handle the OpenAI credentials public async settings(instance: InstanceDto, data: any) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); @@ -630,503 +349,134 @@ export class OpenaiController extends ChatbotController implements ChatbotContro }) .then((instance) => instance.id); - const settings = await this.settingsRepository.findFirst({ + const existingSettings = await this.settingsRepository.findFirst({ where: { instanceId: instanceId, }, }); - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - speechToText: data.speechToText, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - openaiCredsId: updateSettings.openaiCredsId, - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - speechToText: updateSettings.speechToText, - openaiIdFallback: updateSettings.openaiIdFallback, - ignoreJids: updateSettings.ignoreJids, - splitMessages: updateSettings.splitMessages, - timePerChar: updateSettings.timePerChar, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - openaiCredsId: data.openaiCredsId, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - openaiIdFallback: data.openaiIdFallback, - ignoreJids: data.ignoreJids, - speechToText: data.speechToText, - instanceId: instanceId, - splitMessages: data.splitMessages, - timePerChar: data.timePerChar, - }, - }); - - return { - openaiCredsId: newSetttings.openaiCredsId, - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - openaiIdFallback: newSetttings.openaiIdFallback, - ignoreJids: newSetttings.ignoreJids, - speechToText: newSetttings.speechToText, - splitMessages: newSetttings.splitMessages, - timePerChar: newSetttings.timePerChar, + // Convert keywordFinish to string if it's an array + const keywordFinish = data.keywordFinish; + + // Additional OpenAI-specific fields + const settingsData = { + expire: data.expire, + keywordFinish, + delayMessage: data.delayMessage, + unknownMessage: data.unknownMessage, + listeningFromMe: data.listeningFromMe, + stopBotFromMe: data.stopBotFromMe, + keepOpen: data.keepOpen, + debounceTime: data.debounceTime, + ignoreJids: data.ignoreJids, + splitMessages: data.splitMessages, + timePerChar: data.timePerChar, + openaiIdFallback: data.fallbackId, + OpenaiCreds: data.openaiCredsId + ? { + connect: { + id: data.openaiCredsId, + }, + } + : undefined, + speechToText: data.speechToText, }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - public async fetchSettings(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - try { - const instanceId = ( - await this.prismaRepository.instance.findFirst({ - select: { id: true }, + if (existingSettings) { + const settings = await this.settingsRepository.update({ where: { - name: instance.instanceName, + id: existingSettings.id, }, - }) - )?.id; - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); + data: settingsData, + }); - if (!settings) { + // Map the specific fallback field to a generic 'fallbackId' in the response return { - openaiCredsId: null, - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - splitMessages: false, - timePerChar: 0, - openaiIdFallback: null, - speechToText: false, - fallback: null, + ...settings, + fallbackId: settings.openaiIdFallback, }; - } - - return { - openaiCredsId: settings.openaiCredsId, - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - splitMessages: settings.splitMessages, - timePerChar: settings.timePerChar, - openaiIdFallback: settings.openaiIdFallback, - speechToText: settings.speechToText, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } - } - - // Sessions - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - const remoteJid = data.remoteJid; - const status = data.status; - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - }, - }); - - return { openai: { remoteJid: remoteJid, status: status } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - remoteJid: remoteJid, - botId: { not: null }, - status: { not: 'closed' }, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - }, - }); - } - - return { openai: { ...instance, openai: { remoteJid: remoteJid, status: status } } }; } else { - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, + const settings = await this.settingsRepository.create({ data: { - status: status, + ...settingsData, + Instance: { + connect: { + id: instanceId, + }, + }, }, }); - const openaiData = { - remoteJid: remoteJid, - status: status, - session, + // Map the specific fallback field to a generic 'fallbackId' in the response + return { + ...settings, + fallbackId: settings.openaiIdFallback, }; - - return { openai: { ...instance, openai: openaiData } }; } } catch (error) { this.logger.error(error); - throw new Error('Error changing status'); + throw new Error('Error setting default settings'); } } - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { + // Models - OpenAI specific functionality + public async getModels(instance: InstanceDto, openaiCredsId?: string) { if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const openaiBot = await this.botRepository.findFirst({ + const instanceId = await this.prismaRepository.instance + .findFirst({ where: { - id: botId, + name: instance.instanceName, }, - }); + }) + .then((instance) => instance.id); - if (openaiBot && openaiBot.instanceId !== instanceId) { - throw new Error('Openai Bot not found'); - } + if (!instanceId) throw new Error('Instance not found'); + + let apiKey: string; - return await this.sessionRepository.findMany({ + if (openaiCredsId) { + // Use specific credential ID if provided + const creds = await this.credsRepository.findFirst({ where: { - instanceId: instanceId, - remoteJid, - botId: openaiBot ? botId : { not: null }, - type: 'openai', + id: openaiCredsId, + instanceId: instanceId, // Ensure the credential belongs to this instance }, }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled'); + if (!creds) throw new Error('OpenAI credentials not found for the provided ID'); - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ + apiKey = creds.apiKey; + } else { + // Use default credentials from settings if no ID provided + const defaultSettings = await this.settingsRepository.findFirst({ where: { instanceId: instanceId, }, + include: { + OpenaiCreds: true, + }, }); - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; + if (!defaultSettings) throw new Error('Settings not found'); - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); + if (!defaultSettings.OpenaiCreds) + throw new Error( + 'OpenAI credentials not found. Please create credentials and associate them with the settings.', + ); - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); + apiKey = defaultSettings.OpenaiCreds.apiKey; } - } - - // Emit - public async emit({ instance, remoteJid, msg, pushName }: EmitData) { - if (!this.integrationEnabled) return; try { - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (this.checkIgnoreJids(settings?.ignoreJids, remoteJid)) return; - - let session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger( - this.botRepository, - this.settingsRepository, - content, - instance, - session, - )) as OpenaiBot; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.openaiIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.openaiIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - let splitMessages = findBot?.splitMessages; - let timePerChar = findBot?.timePerChar; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - if (splitMessages === undefined || splitMessages === null) splitMessages = settings?.splitMessages ?? false; - if (timePerChar === undefined || timePerChar === null) timePerChar = settings?.timePerChar ?? 0; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - session = await this.sessionRepository.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } + this.client = new OpenAI({ apiKey }); - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - if (findBot.botType === 'assistant') { - await this.openaiService.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - key.fromMe, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - ); - } - - if (findBot.botType === 'chatCompletion') { - await this.openaiService.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - findBot, - session, - { - ...settings, - expire, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debounceTime, - ignoreJids, - splitMessages, - timePerChar, - }, - debouncedContent, - ); - } - }); - } else { - if (findBot.botType === 'assistant') { - await this.openaiService.processOpenaiAssistant( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - key.fromMe, - findBot, - session, - settings, - content, - ); - } - - if (findBot.botType === 'chatCompletion') { - await this.openaiService.processOpenaiChatCompletion( - this.waMonitor.waInstances[instance.instanceName], - remoteJid, - pushName, - findBot, - session, - settings, - content, - ); - } - } + const models: any = await this.client.models.list(); - return; + return models?.body?.data; } catch (error) { this.logger.error(error); - return; + throw new Error('Error fetching models'); } } } diff --git a/src/api/integrations/chatbot/openai/dto/openai.dto.ts b/src/api/integrations/chatbot/openai/dto/openai.dto.ts index a8ac2e4df..9cea4ce55 100644 --- a/src/api/integrations/chatbot/openai/dto/openai.dto.ts +++ b/src/api/integrations/chatbot/openai/dto/openai.dto.ts @@ -1,15 +1,13 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; export class OpenaiCredsDto { name: string; apiKey: string; } -export class OpenaiDto { - enabled?: boolean; - description?: string; +export class OpenaiDto extends BaseChatbotDto { openaiCredsId: string; - botType?: string; + botType: string; assistantId?: string; functionUrl?: string; model?: string; @@ -17,35 +15,10 @@ export class OpenaiDto { assistantMessages?: string[]; userMessages?: string[]; maxTokens?: number; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; - splitMessages?: boolean; - timePerChar?: number; } -export class OpenaiSettingDto { +export class OpenaiSettingDto extends BaseChatbotSettingDto { openaiCredsId?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; openaiIdFallback?: string; - ignoreJids?: any; speechToText?: boolean; - splitMessages?: boolean; - timePerChar?: number; } diff --git a/src/api/integrations/chatbot/openai/routes/openai.router.ts b/src/api/integrations/chatbot/openai/routes/openai.router.ts index ed55a4e76..262815d41 100644 --- a/src/api/integrations/chatbot/openai/routes/openai.router.ts +++ b/src/api/integrations/chatbot/openai/routes/openai.router.ts @@ -153,7 +153,7 @@ export class OpenaiRouter extends RouterBroker { request: req, schema: instanceSchema, ClassRef: InstanceDto, - execute: (instance) => openaiController.getModels(instance), + execute: (instance) => openaiController.getModels(instance, req.query.openaiCredsId as string), }); res.status(HttpStatus.OK).json(response); diff --git a/src/api/integrations/chatbot/openai/services/openai.service.ts b/src/api/integrations/chatbot/openai/services/openai.service.ts index 440e39414..4f0cbd396 100644 --- a/src/api/integrations/chatbot/openai/services/openai.service.ts +++ b/src/api/integrations/chatbot/openai/services/openai.service.ts @@ -1,136 +1,346 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { InstanceDto } from '@api/dto/instance.dto'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; import { Integration } from '@api/types/wa.types'; -import { ConfigService, Language } from '@config/env.config'; -import { Logger } from '@config/logger.config'; -import { IntegrationSession, OpenaiBot, OpenaiCreds, OpenaiSetting } from '@prisma/client'; +import { ConfigService, Language, Openai as OpenaiConfig } from '@config/env.config'; +import { IntegrationSession, OpenaiBot, OpenaiSetting } from '@prisma/client'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; import { downloadMediaMessage } from 'baileys'; +import { isURL } from 'class-validator'; import FormData from 'form-data'; import OpenAI from 'openai'; import P from 'pino'; -export class OpenaiService { - constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} +import { BaseChatbotService } from '../../base-chatbot.service'; - private client: OpenAI; +/** + * OpenAI service that extends the common BaseChatbotService + * Handles both Assistant API and ChatCompletion API + */ +export class OpenaiService extends BaseChatbotService { + protected client: OpenAI; - private readonly logger = new Logger('OpenaiService'); + constructor(waMonitor: WAMonitoringService, prismaRepository: PrismaRepository, configService: ConfigService) { + super(waMonitor, prismaRepository, 'OpenaiService', configService); + } - private async sendMessageToBot(instance: any, openaiBot: OpenaiBot, remoteJid: string, content: string) { - const systemMessages: any = openaiBot.systemMessages; + /** + * Return the bot type for OpenAI + */ + protected getBotType(): string { + return 'openai'; + } - const messagesSystem: any[] = systemMessages.map((message) => { - return { - role: 'system', - content: message, - }; - }); + /** + * Initialize the OpenAI client with the provided API key + */ + protected initClient(apiKey: string) { + this.client = new OpenAI({ apiKey }); + return this.client; + } - const assistantMessages: any = openaiBot.assistantMessages; + /** + * Process a message based on the bot type (assistant or chat completion) + */ + public async process( + instance: any, + remoteJid: string, + openaiBot: OpenaiBot, + session: IntegrationSession, + settings: OpenaiSetting, + content: string, + pushName?: string, + msg?: any, + ): Promise { + try { + this.logger.log(`Starting process for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`); - const messagesAssistant: any[] = assistantMessages.map((message) => { - return { - role: 'assistant', - content: message, - }; - }); + // Handle audio message transcription + if (content.startsWith('audioMessage|') && msg) { + this.logger.log('Detected audio message, attempting to transcribe'); - const userMessages: any = openaiBot.userMessages; + // Get OpenAI credentials for transcription + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); - const messagesUser: any[] = userMessages.map((message) => { - return { - role: 'user', - content: message, - }; - }); + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return; + } - const messageData: any = { - role: 'user', - content: [{ type: 'text', text: content }], - }; + // Initialize OpenAI client for transcription + this.initClient(creds.apiKey); - if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); + // Transcribe the audio + const transcription = await this.speechToText(msg, instance); - const url = contentSplit[1].split('?')[0]; + if (transcription) { + this.logger.log(`Audio transcribed: ${transcription}`); + // Replace the audio message identifier with the transcription + content = transcription; + } else { + this.logger.error('Failed to transcribe audio'); + await this.sendMessageWhatsApp( + instance, + remoteJid, + "Sorry, I couldn't transcribe your audio message. Could you please type your message instead?", + settings, + true, + ); + return; + } + } else { + // Get the OpenAI credentials + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); - messageData.content = [ - { type: 'text', text: contentSplit[2] || content }, - { - type: 'image_url', - image_url: { - url: url, + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return; + } + + // Initialize OpenAI client + this.initClient(creds.apiKey); + } + + // Handle keyword finish + const keywordFinish = settings?.keywordFinish || ''; + const normalizedContent = content.toLowerCase().trim(); + if (keywordFinish.length > 0 && normalizedContent === keywordFinish.toLowerCase()) { + if (settings?.keepOpen) { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'closed', + }, + }); + } else { + await this.prismaRepository.integrationSession.delete({ + where: { + id: session.id, + }, + }); + } + + await sendTelemetry('/openai/session/finish'); + return; + } + + // If session is new or doesn't exist + if (!session) { + const data = { + remoteJid, + pushName, + botId: openaiBot.id, + }; + + const createSession = await this.createNewSession( + { instanceName: instance.instanceName, instanceId: instance.instanceId }, + data, + this.getBotType(), + ); + + await this.initNewSession( + instance, + remoteJid, + openaiBot, + settings, + createSession.session, + content, + pushName, + msg, + ); + + await sendTelemetry('/openai/session/start'); + return; + } + + // If session exists but is paused + if (session.status === 'paused') { + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, }, - }, - ]; + data: { + status: 'opened', + awaitUser: true, + }, + }); + + return; + } + + // Process with the appropriate API based on bot type + await this.sendMessageToBot(instance, session, settings, openaiBot, remoteJid, pushName || '', content, msg); + } catch (error) { + this.logger.error(`Error in process: ${error.message || JSON.stringify(error)}`); + return; } + } - const messages: any[] = [...messagesSystem, ...messagesAssistant, ...messagesUser, messageData]; + /** + * Send message to OpenAI - this handles both Assistant API and ChatCompletion API + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: OpenaiSetting, + openaiBot: OpenaiBot, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { + this.logger.log(`Sending message to bot for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`); + + if (!this.client) { + this.logger.log('Client not initialized, initializing now'); + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); + if (!creds) { + this.logger.error(`OpenAI credentials not found in sendMessageToBot. CredsId: ${openaiBot.openaiCredsId}`); + return; + } + + this.initClient(creds.apiKey); } - const completions = await this.client.chat.completions.create({ - model: openaiBot.model, - messages: messages, - max_tokens: openaiBot.maxTokens, - }); + try { + let message: string; - if (instance.integration === Integration.WHATSAPP_BAILEYS) - await instance.client.sendPresenceUpdate('paused', remoteJid); + // Handle different bot types + if (openaiBot.botType === 'assistant') { + this.logger.log('Processing with Assistant API'); + message = await this.processAssistantMessage( + instance, + session, + openaiBot, + remoteJid, + pushName, + false, // Not fromMe + content, + msg, + ); + } else { + this.logger.log('Processing with ChatCompletion API'); + message = await this.processChatCompletionMessage(instance, openaiBot, remoteJid, content, msg); + } - const message = completions.choices[0].message.content; + this.logger.log(`Got response from OpenAI: ${message?.substring(0, 50)}${message?.length > 50 ? '...' : ''}`); - return message; + // Send the response + if (message) { + this.logger.log('Sending message to WhatsApp'); + await this.sendMessageWhatsApp(instance, remoteJid, message, settings, true); + } else { + this.logger.error('No message to send to WhatsApp'); + } + + // Update session status + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + status: 'opened', + awaitUser: true, + }, + }); + } catch (error) { + this.logger.error(`Error in sendMessageToBot: ${error.message || JSON.stringify(error)}`); + if (error.response) { + this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`); + } + return; + } } - private async sendMessageToAssistant( + /** + * Process message using the OpenAI Assistant API + */ + private async processAssistantMessage( instance: any, + session: IntegrationSession, openaiBot: OpenaiBot, remoteJid: string, pushName: string, fromMe: boolean, content: string, - threadId: string, - ) { + msg?: any, + ): Promise { const messageData: any = { role: fromMe ? 'assistant' : 'user', content: [{ type: 'text', text: content }], }; + // Handle image messages if (this.isImageMessage(content)) { - const contentSplit = content.split('|'); + const media = content.split('|'); - const url = contentSplit[1].split('?')[0]; + if (msg.message.mediaUrl || msg.message.base64) { + let mediaBase64 = msg.message.base64 || null; - messageData.content = [ - { type: 'text', text: contentSplit[2] || content }, - { - type: 'image_url', - image_url: { - url: url, + if (msg.message.mediaUrl && isURL(msg.message.mediaUrl)) { + const result = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }); + mediaBase64 = Buffer.from(result.data).toString('base64'); + } + + if (mediaBase64) { + messageData.content = [ + { type: 'text', text: media[2] || content }, + { type: 'image_url', image_url: { url: mediaBase64 } }, + ]; + } + } else { + const url = media[1].split('?')[0]; + + messageData.content = [ + { type: 'text', text: media[2] || content }, + { + type: 'image_url', + image_url: { + url: url, + }, }, + ]; + } + } + + // Get thread ID from session or create new thread + let threadId = session.sessionId; + + // Create a new thread if one doesn't exist or invalid format + if (!threadId || threadId === remoteJid) { + const newThread = await this.client.beta.threads.create(); + threadId = newThread.id; + + // Save the new thread ID to the session + await this.prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + sessionId: threadId, }, - ]; + }); + this.logger.log(`Created new thread ID: ${threadId} for session: ${session.id}`); } + // Add message to thread await this.client.beta.threads.messages.create(threadId, messageData); if (fromMe) { sendTelemetry('/message/sendText'); - return; + return ''; } + // Run the assistant const runAssistant = await this.client.beta.threads.runs.create(threadId, { assistant_id: openaiBot.assistantId, }); @@ -140,190 +350,31 @@ export class OpenaiService { await instance.client.sendPresenceUpdate('composing', remoteJid); } + // Wait for the assistant to complete const response = await this.getAIResponse(threadId, runAssistant.id, openaiBot.functionUrl, remoteJid, pushName); - if (instance.integration === Integration.WHATSAPP_BAILEYS) + if (instance.integration === Integration.WHATSAPP_BAILEYS) { await instance.client.sendPresenceUpdate('paused', remoteJid); - - const message = response?.data[0].content[0].text.value; - - return message; - } - - private async sendMessageWhatsapp( - instance: any, - session: IntegrationSession, - remoteJid: string, - settings: OpenaiSetting, - message: string, - ) { - const linkRegex = /(!?)\[(.*?)\]\((.*?)\)/g; - - let textBuffer = ''; - let lastIndex = 0; - - let match: RegExpExecArray | null; - - const getMediaType = (url: string): string | null => { - const extension = url.split('.').pop()?.toLowerCase(); - const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; - const audioExtensions = ['mp3', 'wav', 'aac', 'ogg']; - const videoExtensions = ['mp4', 'avi', 'mkv', 'mov']; - const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']; - - if (imageExtensions.includes(extension || '')) return 'image'; - if (audioExtensions.includes(extension || '')) return 'audio'; - if (videoExtensions.includes(extension || '')) return 'video'; - if (documentExtensions.includes(extension || '')) return 'document'; - return null; - }; - - while ((match = linkRegex.exec(message)) !== null) { - const [fullMatch, exclMark, altText, url] = match; - const mediaType = getMediaType(url); - - const beforeText = message.slice(lastIndex, match.index); - if (beforeText) { - textBuffer += beforeText; - } - - if (mediaType) { - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); - } - } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; - } - } - - if (mediaType === 'audio') { - await instance.audioWhatsapp({ - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - audio: url, - caption: altText, - }); - } else { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: mediaType, - media: url, - caption: altText, - }, - null, - false, - ); - } - } else { - textBuffer += `[${altText}](${url})`; - } - - lastIndex = linkRegex.lastIndex; } - if (lastIndex < message.length) { - const remainingText = message.slice(lastIndex); - if (remainingText.trim()) { - textBuffer += remainingText; - } - } - - const splitMessages = settings.splitMessages ?? false; - const timePerChar = settings.timePerChar ?? 0; - const minDelay = 1000; - const maxDelay = 20000; - - if (textBuffer.trim()) { - if (splitMessages) { - const multipleMessages = textBuffer.trim().split('\n\n'); - - for (let index = 0; index < multipleMessages.length; index++) { - const message = multipleMessages[index]; - - const delay = Math.min(Math.max(message.length * timePerChar, minDelay), maxDelay); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.presenceSubscribe(remoteJid); - await instance.client.sendPresenceUpdate('composing', remoteJid); - } - - await new Promise((resolve) => { - setTimeout(async () => { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: message, - }, - false, - ); - resolve(); - }, delay); - }); - - if (instance.integration === Integration.WHATSAPP_BAILEYS) { - await instance.client.sendPresenceUpdate('paused', remoteJid); + // Extract the response text safely with type checking + let responseText = "I couldn't generate a proper response. Please try again."; + try { + const messages = response?.data || []; + if (messages.length > 0) { + const messageContent = messages[0]?.content || []; + if (messageContent.length > 0) { + const textContent = messageContent[0]; + if (textContent && 'text' in textContent && textContent.text && 'value' in textContent.text) { + responseText = textContent.text.value; } } - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: textBuffer.trim(), - }, - false, - ); - textBuffer = ''; } + } catch (error) { + this.logger.error(`Error extracting response text: ${error}`); } - sendTelemetry('/message/sendText'); - + // Update session with the thread ID to ensure continuity await this.prismaRepository.integrationSession.update({ where: { id: session.id, @@ -331,504 +382,331 @@ export class OpenaiService { data: { status: 'opened', awaitUser: true, + sessionId: threadId, // Ensure thread ID is saved consistently }, }); - } - - public async createAssistantNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - try { - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - const threadId = (await this.client.beta.threads.create({})).id; - - let session = null; - if (threadId) { - session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: threadId, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'openai', - }, - }); - } - return { session }; - } catch (error) { - this.logger.error(error); - return; - } + // Return fallback message if unable to extract text + return responseText; } - private async initAssistantNewSession( + /** + * Process message using the OpenAI ChatCompletion API + */ + private async processChatCompletionMessage( instance: any, - remoteJid: string, - pushName: string, - fromMe: boolean, openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: IntegrationSession, + remoteJid: string, content: string, - ) { - const data = await this.createAssistantNewSession(instance, { - remoteJid, - pushName, - openaiCredsId: openaiBot.openaiCredsId, - botId: openaiBot.id, - }); - - if (data.session) { - session = data.session; - } - - const message = await this.sendMessageToAssistant( - instance, - openaiBot, - remoteJid, - pushName, - fromMe, - content, - session.sessionId, - ); + msg?: any, + ): Promise { + this.logger.log('Starting processChatCompletionMessage'); + + // Check if client is initialized + if (!this.client) { + this.logger.log('Client not initialized in processChatCompletionMessage, initializing now'); + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: openaiBot.openaiCredsId }, + }); - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`); + return 'Error: OpenAI credentials not found'; + } - return; - } + this.initClient(creds.apiKey); + } - private isJSON(str: string): boolean { - try { - JSON.parse(str); - return true; - } catch (e) { - return false; + // Check if model is defined + if (!openaiBot.model) { + this.logger.error('OpenAI model not defined'); + return 'Error: OpenAI model not configured'; } - } - private async getAIResponse( - threadId: string, - runId: string, - functionUrl: string, - remoteJid: string, - pushName: string, - ) { - const getRun = await this.client.beta.threads.runs.retrieve(threadId, runId); - let toolCalls; - switch (getRun.status) { - case 'requires_action': - toolCalls = getRun?.required_action?.submit_tool_outputs?.tool_calls; - - if (toolCalls) { - for (const toolCall of toolCalls) { - const id = toolCall.id; - const functionName = toolCall?.function?.name; - const functionArgument = this.isJSON(toolCall?.function?.arguments) - ? JSON.parse(toolCall?.function?.arguments) - : toolCall?.function?.arguments; - - let output = null; + this.logger.log(`Using model: ${openaiBot.model}, max tokens: ${openaiBot.maxTokens || 500}`); - try { - const { data } = await axios.post(functionUrl, { - name: functionName, - arguments: { ...functionArgument, remoteJid, pushName }, - }); + // Get existing conversation history from the session + const session = await this.prismaRepository.integrationSession.findFirst({ + where: { + remoteJid, + botId: openaiBot.id, + status: 'opened', + }, + }); - output = JSON.stringify(data) - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t'); - } catch (error) { - output = JSON.stringify(error) - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\t/g, '\\t'); - } + let conversationHistory = []; - await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, { - tool_outputs: [ - { - tool_call_id: id, - output, - }, - ], - }); - } - } + if (session && session.context) { + try { + const sessionData = + typeof session.context === 'string' ? JSON.parse(session.context as string) : session.context; - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'queued': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'in_progress': - await new Promise((resolve) => setTimeout(resolve, 1000)); - return this.getAIResponse(threadId, runId, functionUrl, remoteJid, pushName); - case 'completed': - return await this.client.beta.threads.messages.list(threadId, { - run_id: runId, - limit: 1, - }); + conversationHistory = sessionData.history || []; + this.logger.log(`Retrieved conversation history from session, ${conversationHistory.length} messages`); + } catch (error) { + this.logger.error(`Error parsing session context: ${error.message}`); + // Continue with empty history if we can't parse the session data + conversationHistory = []; + } } - } - private isImageMessage(content: string) { - return content.includes('imageMessage'); - } + // Log bot data + this.logger.log(`Bot data - systemMessages: ${JSON.stringify(openaiBot.systemMessages || [])}`); + this.logger.log(`Bot data - assistantMessages: ${JSON.stringify(openaiBot.assistantMessages || [])}`); + this.logger.log(`Bot data - userMessages: ${JSON.stringify(openaiBot.userMessages || [])}`); - public async processOpenaiAssistant( - instance: any, - remoteJid: string, - pushName: string, - fromMe: boolean, - openaiBot: OpenaiBot, - session: IntegrationSession, - settings: OpenaiSetting, - content: string, - ) { - if (session && session.status === 'closed') { - return; - } + // Prepare system messages + const systemMessages: any = openaiBot.systemMessages || []; + const messagesSystem: any[] = systemMessages.map((message) => { + return { + role: 'system', + content: message, + }; + }); - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); + // Prepare assistant messages + const assistantMessages: any = openaiBot.assistantMessages || []; + const messagesAssistant: any[] = assistantMessages.map((message) => { + return { + role: 'assistant', + content: message, + }; + }); - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + // Prepare user messages + const userMessages: any = openaiBot.userMessages || []; + const messagesUser: any[] = userMessages.map((message) => { + return { + role: 'user', + content: message, + }; + }); - const diff = now - sessionUpdatedAt; + // Prepare current message + const messageData: any = { + role: 'user', + content: [{ type: 'text', text: content }], + }; - const diffInMinutes = Math.floor(diff / 1000 / 60); + // Handle image messages + if (this.isImageMessage(content)) { + this.logger.log('Found image message'); + const media = content.split('|'); + + if (msg.message.mediaUrl || msg.message.base64) { + messageData.content = [ + { type: 'text', text: media[2] || content }, + { type: 'image_url', image_url: { url: msg.message.base64 || msg.message.mediaUrl } }, + ]; + } else { + const url = media[1].split('?')[0]; - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, + messageData.content = [ + { type: 'text', text: media[2] || content }, + { + type: 'image_url', + image_url: { + url: url, }, - }); - } - - await this.initAssistantNewSession( - instance, - remoteJid, - pushName, - fromMe, - openaiBot, - settings, - session, - content, - ); - return; + }, + ]; } } - if (!session) { - await this.initAssistantNewSession(instance, remoteJid, pushName, fromMe, openaiBot, settings, session, content); - return; + // Combine all messages: system messages, pre-defined messages, conversation history, and current message + const messages: any[] = [ + ...messagesSystem, + ...messagesAssistant, + ...messagesUser, + ...conversationHistory, + messageData, + ]; + + this.logger.log(`Final messages payload: ${JSON.stringify(messages)}`); + + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + this.logger.log('Setting typing indicator'); + await instance.client.presenceSubscribe(remoteJid); + await instance.client.sendPresenceUpdate('composing', remoteJid); } - if (session.status !== 'paused') - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, + // Send the request to OpenAI + try { + this.logger.log('Sending request to OpenAI API'); + const completions = await this.client.chat.completions.create({ + model: openaiBot.model, + messages: messages, + max_tokens: openaiBot.maxTokens || 500, // Add default if maxTokens is missing }); - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); + if (instance.integration === Integration.WHATSAPP_BAILEYS) { + await instance.client.sendPresenceUpdate('paused', remoteJid); + } + + const responseContent = completions.choices[0].message.content; + this.logger.log(`Received response from OpenAI: ${JSON.stringify(completions.choices[0])}`); + + // Add the current exchange to the conversation history and update the session + conversationHistory.push(messageData); + conversationHistory.push({ + role: 'assistant', + content: responseContent, + }); - sendTelemetry('/message/sendText'); + // Limit history length to avoid token limits (keep last 10 messages) + if (conversationHistory.length > 10) { + conversationHistory = conversationHistory.slice(conversationHistory.length - 10); } - return; - } - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { + // Save the updated conversation history to the session + if (session) { await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, + where: { id: session.id }, data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, + context: JSON.stringify({ + history: conversationHistory, + }), }, }); + this.logger.log(`Updated session with conversation history, now ${conversationHistory.length} messages`); } - return; - } - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: openaiBot.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const threadId = session.sessionId; - - const message = await this.sendMessageToAssistant( - instance, - openaiBot, - remoteJid, - pushName, - fromMe, - content, - threadId, - ); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } - - public async createChatCompletionNewSession(instance: InstanceDto, data: any) { - if (data.remoteJid === 'status@broadcast') return; - - const id = Math.floor(Math.random() * 10000000000).toString(); - - const creds = await this.prismaRepository.openaiCreds.findFirst({ - where: { - id: data.openaiCredsId, - }, - }); - - if (!creds) throw new Error('Openai Creds not found'); - try { - const session = await this.prismaRepository.integrationSession.create({ - data: { - remoteJid: data.remoteJid, - pushName: data.pushName, - sessionId: id, - status: 'opened', - awaitUser: false, - botId: data.botId, - instanceId: instance.instanceId, - type: 'openai', - }, - }); - - return { session, creds }; + return responseContent; } catch (error) { - this.logger.error(error); - return; + this.logger.error(`Error calling OpenAI: ${error.message || JSON.stringify(error)}`); + if (error.response) { + this.logger.error(`API Response status: ${error.response.status}`); + this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`); + } + return `Sorry, there was an error: ${error.message || 'Unknown error'}`; } } - private async initChatCompletionNewSession( - instance: any, - remoteJid: string, - pushName: string, - openaiBot: OpenaiBot, - settings: OpenaiSetting, - session: IntegrationSession, - content: string, - ) { - const data = await this.createChatCompletionNewSession(instance, { - remoteJid, - pushName, - openaiCredsId: openaiBot.openaiCredsId, - botId: openaiBot.id, - }); - - session = data.session; - - const creds = data.creds; - - this.client = new OpenAI({ - apiKey: creds.apiKey, - }); - - const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } - - public async processOpenaiChatCompletion( - instance: any, + /** + * Wait for and retrieve the AI response + */ + private async getAIResponse( + threadId: string, + runId: string, + functionUrl: string | null, remoteJid: string, pushName: string, - openaiBot: OpenaiBot, - session: IntegrationSession, - settings: OpenaiSetting, - content: string, ) { - if (session && session.status !== 'opened') { - return; - } - - if (session && settings.expire && settings.expire > 0) { - const now = Date.now(); - - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); + let status = await this.client.beta.threads.runs.retrieve(threadId, runId); + + let maxRetries = 60; // 1 minute with 1s intervals + const checkInterval = 1000; // 1 second + + while ( + status.status !== 'completed' && + status.status !== 'failed' && + status.status !== 'cancelled' && + status.status !== 'expired' && + maxRetries > 0 + ) { + await new Promise((resolve) => setTimeout(resolve, checkInterval)); + status = await this.client.beta.threads.runs.retrieve(threadId, runId); + + // Handle tool calls + if (status.status === 'requires_action' && status.required_action?.type === 'submit_tool_outputs') { + const toolCalls = status.required_action.submit_tool_outputs.tool_calls; + const toolOutputs = []; + + for (const toolCall of toolCalls) { + if (functionUrl) { + try { + const payloadData = JSON.parse(toolCall.function.arguments); - const diff = now - sessionUpdatedAt; + // Add context + payloadData.remoteJid = remoteJid; + payloadData.pushName = pushName; - const diffInMinutes = Math.floor(diff / 1000 / 60); + const response = await axios.post(functionUrl, { + functionName: toolCall.function.name, + functionArguments: payloadData, + }); - if (diffInMinutes > settings.expire) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify(response.data), + }); + } catch (error) { + this.logger.error(`Error calling function: ${error}`); + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify({ error: 'Function call failed' }), + }); + } + } else { + toolOutputs.push({ + tool_call_id: toolCall.id, + output: JSON.stringify({ error: 'No function URL configured' }), + }); + } } - await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); - return; + await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, { + tool_outputs: toolOutputs, + }); } - } - if (!session) { - await this.initChatCompletionNewSession(instance, remoteJid, pushName, openaiBot, settings, session, content); - return; + maxRetries--; } - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'opened', - awaitUser: false, - }, - }); - - if (!content) { - if (settings.unknownMessage) { - this.waMonitor.waInstances[instance.instanceName].textMessage( - { - number: remoteJid.split('@')[0], - delay: settings.delayMessage || 1000, - text: settings.unknownMessage, - }, - false, - ); - - sendTelemetry('/message/sendText'); - } - return; + if (status.status === 'completed') { + const messages = await this.client.beta.threads.messages.list(threadId); + return messages; + } else { + this.logger.error(`Assistant run failed with status: ${status.status}`); + return { data: [{ content: [{ text: { value: 'Failed to get a response from the assistant.' } }] }] }; } + } - if (settings.keywordFinish && content.toLowerCase() === settings.keywordFinish.toLowerCase()) { - if (settings.keepOpen) { - await this.prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); - } else { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: openaiBot.id, - remoteJid: remoteJid, - }, - }); - } - return; - } + protected isImageMessage(content: string): boolean { + return content.includes('imageMessage'); + } - const creds = await this.prismaRepository.openaiCreds.findFirst({ + /** + * Implementation of speech-to-text transcription for audio messages + */ + public async speechToText(msg: any, instance: any): Promise { + const settings = await this.prismaRepository.openaiSetting.findFirst({ where: { - id: openaiBot.openaiCredsId, + instanceId: instance.instanceId, }, }); - if (!creds) throw new Error('Openai Creds not found'); + if (!settings) { + this.logger.error(`OpenAI settings not found. InstanceId: ${instance.instanceId}`); + return null; + } - this.client = new OpenAI({ - apiKey: creds.apiKey, + const creds = await this.prismaRepository.openaiCreds.findUnique({ + where: { id: settings.openaiCredsId }, }); - const message = await this.sendMessageToBot(instance, openaiBot, remoteJid, content); - - await this.sendMessageWhatsapp(instance, session, remoteJid, settings, message); - - return; - } + if (!creds) { + this.logger.error(`OpenAI credentials not found. CredsId: ${settings.openaiCredsId}`); + return null; + } - public async speechToText(creds: OpenaiCreds, msg: any, updateMediaMessage: any) { - let audio; + let audio: Buffer; - if (msg?.message?.mediaUrl) { + if (msg.message.mediaUrl) { audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => { return Buffer.from(response.data, 'binary'); }); + } else if (msg.message.base64) { + audio = Buffer.from(msg.message.base64, 'base64'); } else { + // Fallback for raw WhatsApp audio messages that need downloadMediaMessage audio = await downloadMediaMessage( { key: msg.key, message: msg?.message }, 'buffer', {}, { logger: P({ level: 'error' }) as any, - reuploadRequest: updateMediaMessage, + reuploadRequest: instance, }, ); } @@ -838,15 +716,16 @@ export class OpenaiService { : this.configService.get('LANGUAGE'); const formData = new FormData(); - formData.append('file', audio, 'audio.ogg'); formData.append('model', 'whisper-1'); formData.append('language', lang); + const apiKey = creds?.apiKey || this.configService.get('OPENAI').API_KEY_GLOBAL; + const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, { headers: { 'Content-Type': 'multipart/form-data', - Authorization: `Bearer ${creds.apiKey}`, + Authorization: `Bearer ${apiKey}`, }, }); diff --git a/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts index 7ae227627..a48fe10cc 100644 --- a/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts +++ b/src/api/integrations/chatbot/typebot/controllers/typebot.controller.ts @@ -1,4 +1,3 @@ -import { IgnoreJidDto } from '@api/dto/chatbot.dto'; import { InstanceDto } from '@api/dto/instance.dto'; import { TypebotDto } from '@api/integrations/chatbot/typebot/dto/typebot.dto'; import { TypebotService } from '@api/integrations/chatbot/typebot/services/typebot.service'; @@ -8,13 +7,12 @@ import { Events } from '@api/types/wa.types'; import { configService, Typebot } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { BadRequestException } from '@exceptions'; -import { Typebot as TypebotModel } from '@prisma/client'; -import { getConversationMessage } from '@utils/getConversationMessage'; +import { IntegrationSession, Typebot as TypebotModel } from '@prisma/client'; import axios from 'axios'; -import { ChatbotController, ChatbotControllerInterface } from '../../chatbot.controller'; +import { BaseChatbotController } from '../../base-chatbot.controller'; -export class TypebotController extends ChatbotController implements ChatbotControllerInterface { +export class TypebotController extends BaseChatbotController { constructor( private readonly typebotService: TypebotService, prismaRepository: PrismaRepository, @@ -28,6 +26,7 @@ export class TypebotController extends ChatbotController implements ChatbotContr } public readonly logger = new Logger('TypebotController'); + protected readonly integrationName = 'Typebot'; integrationEnabled = configService.get('TYPEBOT').ENABLED; botRepository: any; @@ -35,245 +34,35 @@ export class TypebotController extends ChatbotController implements ChatbotContr sessionRepository: any; userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {}; - // Bots - public async createBot(instance: InstanceDto, data: TypebotDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - if ( - !data.expire || - !data.keywordFinish || - !data.delayMessage || - !data.unknownMessage || - !data.listeningFromMe || - !data.stopBotFromMe || - !data.keepOpen || - !data.debounceTime || - !data.ignoreJids - ) { - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!data.expire) data.expire = defaultSettingCheck?.expire || 0; - if (!data.keywordFinish) data.keywordFinish = defaultSettingCheck?.keywordFinish || '#SAIR'; - if (!data.delayMessage) data.delayMessage = defaultSettingCheck?.delayMessage || 1000; - if (!data.unknownMessage) data.unknownMessage = defaultSettingCheck?.unknownMessage || 'Desculpe, não entendi'; - if (!data.listeningFromMe) data.listeningFromMe = defaultSettingCheck?.listeningFromMe || false; - if (!data.stopBotFromMe) data.stopBotFromMe = defaultSettingCheck?.stopBotFromMe || false; - if (!data.keepOpen) data.keepOpen = defaultSettingCheck?.keepOpen || false; - if (!data.debounceTime) data.debounceTime = defaultSettingCheck?.debounceTime || 0; - if (!data.ignoreJids) data.ignoreJids = defaultSettingCheck?.ignoreJids || []; - - if (!defaultSettingCheck) { - await this.settings(instance, { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - ignoreJids: data.ignoreJids, - }); - } - } - - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - instanceId: instanceId, - }, - }); - - if (checkTriggerAll && data.triggerType === 'all') { - throw new Error('You already have a typebot with an "All" trigger, you cannot have more bots while it is active'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - url: data.url, - typebot: data.typebot, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Typebot already exists'); - } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.create({ - data: { - enabled: data?.enabled, - description: data.description, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - instanceId: instanceId, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error creating typebot'); - } + protected getFallbackBotId(settings: any): string | undefined { + return settings?.typebotIdFallback; } - public async findBot(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bots = await this.botRepository.findMany({ - where: { - instanceId: instanceId, - }, - }); - - if (!bots.length) { - return null; - } - - return bots; + protected getFallbackFieldName(): string { + return 'typebotIdFallback'; } - public async fetchBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const bot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!bot) { - throw new Error('Typebot not found'); - } - - if (bot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - return bot; + protected getIntegrationType(): string { + return 'typebot'; } - public async updateBot(instance: InstanceDto, botId: string, data: TypebotDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - if (data.triggerType === 'all') { - const checkTriggerAll = await this.botRepository.findFirst({ - where: { - enabled: true, - triggerType: 'all', - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); + protected getAdditionalBotData(data: TypebotDto): Record { + return { + url: data.url, + typebot: data.typebot, + }; + } - if (checkTriggerAll) { - throw new Error( - 'You already have a typebot with an "All" trigger, you cannot have more bots while it is active', - ); - } - } + // Implementation for bot-specific updates + protected getAdditionalUpdateFields(data: TypebotDto): Record { + return { + url: data.url, + typebot: data.typebot, + }; + } + // Implementation for bot-specific duplicate validation on update + protected async validateNoDuplicatesOnUpdate(botId: string, instanceId: string, data: TypebotDto): Promise { const checkDuplicate = await this.botRepository.findFirst({ where: { url: data.url, @@ -288,263 +77,41 @@ export class TypebotController extends ChatbotController implements ChatbotContr if (checkDuplicate) { throw new Error('Typebot already exists'); } - - if (data.triggerType === 'keyword') { - if (!data.triggerOperator || !data.triggerValue) { - throw new Error('Trigger operator and value are required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - id: { - not: botId, - }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - if (data.triggerType === 'advanced') { - if (!data.triggerValue) { - throw new Error('Trigger value is required'); - } - - const checkDuplicate = await this.botRepository.findFirst({ - where: { - triggerValue: data.triggerValue, - id: { not: botId }, - instanceId: instanceId, - }, - }); - - if (checkDuplicate) { - throw new Error('Trigger already exists'); - } - } - - try { - const bot = await this.botRepository.update({ - where: { - id: botId, - }, - data: { - enabled: data?.enabled, - description: data.description, - url: data.url, - typebot: data.typebot, - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - triggerType: data.triggerType, - triggerOperator: data.triggerOperator, - triggerValue: data.triggerValue, - ignoreJids: data.ignoreJids, - }, - }); - - return bot; - } catch (error) { - this.logger.error(error); - throw new Error('Error updating typebot'); - } } - public async deleteBot(instance: InstanceDto, botId: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (!typebot) { - throw new Error('Typebot not found'); - } - - if (typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - try { - await this.prismaRepository.integrationSession.deleteMany({ - where: { - botId: botId, - }, - }); - - await this.botRepository.delete({ - where: { - id: botId, - }, - }); - - return { typebot: { id: botId } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error deleting typebot'); - } - } - - // Settings - public async settings(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (settings) { - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - }, - }); - - return { - expire: updateSettings.expire, - keywordFinish: updateSettings.keywordFinish, - delayMessage: updateSettings.delayMessage, - unknownMessage: updateSettings.unknownMessage, - listeningFromMe: updateSettings.listeningFromMe, - stopBotFromMe: updateSettings.stopBotFromMe, - keepOpen: updateSettings.keepOpen, - debounceTime: updateSettings.debounceTime, - typebotIdFallback: updateSettings.typebotIdFallback, - ignoreJids: updateSettings.ignoreJids, - }; - } - - const newSetttings = await this.settingsRepository.create({ - data: { - expire: data.expire, - keywordFinish: data.keywordFinish, - delayMessage: data.delayMessage, - unknownMessage: data.unknownMessage, - listeningFromMe: data.listeningFromMe, - stopBotFromMe: data.stopBotFromMe, - keepOpen: data.keepOpen, - debounceTime: data.debounceTime, - typebotIdFallback: data.typebotIdFallback, - ignoreJids: data.ignoreJids, - instanceId: instanceId, - }, - }); - - return { - expire: newSetttings.expire, - keywordFinish: newSetttings.keywordFinish, - delayMessage: newSetttings.delayMessage, - unknownMessage: newSetttings.unknownMessage, - listeningFromMe: newSetttings.listeningFromMe, - stopBotFromMe: newSetttings.stopBotFromMe, - keepOpen: newSetttings.keepOpen, - debounceTime: newSetttings.debounceTime, - typebotIdFallback: newSetttings.typebotIdFallback, - ignoreJids: newSetttings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async fetchSettings(instance: InstanceDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - include: { - Fallback: true, - }, - }); - - if (!settings) { - return { - expire: 0, - keywordFinish: '', - delayMessage: 0, - unknownMessage: '', - listeningFromMe: false, - stopBotFromMe: false, - keepOpen: false, - ignoreJids: [], - typebotIdFallback: null, - fallback: null, - }; - } - - return { - expire: settings.expire, - keywordFinish: settings.keywordFinish, - delayMessage: settings.delayMessage, - unknownMessage: settings.unknownMessage, - listeningFromMe: settings.listeningFromMe, - stopBotFromMe: settings.stopBotFromMe, - keepOpen: settings.keepOpen, - ignoreJids: settings.ignoreJids, - typebotIdFallback: settings.typebotIdFallback, - fallback: settings.Fallback, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching default settings'); - } + // Process Typebot-specific bot logic + protected async processBot( + instance: any, + remoteJid: string, + bot: TypebotModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ) { + // Map to the original processTypebot method signature + await this.typebotService.processTypebot( + instance, + remoteJid, + msg, + session, + bot, + bot.url, + settings.expire, + bot.typebot, + settings.keywordFinish, + settings.delayMessage, + settings.unknownMessage, + settings.listeningFromMe, + settings.stopBotFromMe, + settings.keepOpen, + content, + {}, // prefilledVariables (optional) + ); } - // Sessions + // TypeBot specific method for starting a bot from API public async startBot(instance: InstanceDto, data: any) { if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); @@ -661,11 +228,12 @@ export class TypebotController extends ChatbotController implements ChatbotContr }, }); + // Use the original processTypebot method with all parameters await this.typebotService.processTypebot( - instanceData, + this.waMonitor.waInstances[instanceData.name], remoteJid, - null, - null, + null, // msg + null, // session findBot, url, expire, @@ -747,331 +315,4 @@ export class TypebotController extends ChatbotController implements ChatbotContr }, }; } - - public async changeStatus(instance: InstanceDto, data: any) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const remoteJid = data.remoteJid; - const status = data.status; - - const defaultSettingCheck = await this.settingsRepository.findFirst({ - where: { - instanceId, - }, - }); - - if (status === 'delete') { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - botId: { not: null }, - }, - }); - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - if (status === 'closed') { - if (defaultSettingCheck?.keepOpen) { - await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - } else { - await this.sessionRepository.deleteMany({ - where: { - remoteJid: remoteJid, - instanceId: instanceId, - botId: { not: null }, - }, - }); - } - - return { typebot: { ...instance, typebot: { remoteJid: remoteJid, status: status } } }; - } - - const session = await this.sessionRepository.updateMany({ - where: { - instanceId: instanceId, - remoteJid: remoteJid, - botId: { not: null }, - }, - data: { - status: status, - }, - }); - - const typebotData = { - remoteJid: remoteJid, - status: status, - session, - }; - - this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); - - return { typebot: { ...instance, typebot: typebotData } }; - } catch (error) { - this.logger.error(error); - throw new Error('Error changing status'); - } - } - - public async fetchSessions(instance: InstanceDto, botId: string, remoteJid?: string) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const typebot = await this.botRepository.findFirst({ - where: { - id: botId, - }, - }); - - if (typebot && typebot.instanceId !== instanceId) { - throw new Error('Typebot not found'); - } - - return await this.sessionRepository.findMany({ - where: { - instanceId: instanceId, - remoteJid, - botId: botId ?? { not: null }, - type: 'typebot', - }, - }); - } catch (error) { - this.logger.error(error); - throw new Error('Error fetching sessions'); - } - } - - public async ignoreJid(instance: InstanceDto, data: IgnoreJidDto) { - if (!this.integrationEnabled) throw new BadRequestException('Typebot is disabled'); - - try { - const instanceId = await this.prismaRepository.instance - .findFirst({ - where: { - name: instance.instanceName, - }, - }) - .then((instance) => instance.id); - - const settings = await this.settingsRepository.findFirst({ - where: { - instanceId: instanceId, - }, - }); - - if (!settings) { - throw new Error('Settings not found'); - } - - let ignoreJids: any = settings?.ignoreJids || []; - - if (data.action === 'add') { - if (ignoreJids.includes(data.remoteJid)) return { ignoreJids: ignoreJids }; - - ignoreJids.push(data.remoteJid); - } else { - ignoreJids = ignoreJids.filter((jid) => jid !== data.remoteJid); - } - - const updateSettings = await this.settingsRepository.update({ - where: { - id: settings.id, - }, - data: { - ignoreJids: ignoreJids, - }, - }); - - return { - ignoreJids: updateSettings.ignoreJids, - }; - } catch (error) { - this.logger.error(error); - throw new Error('Error setting default settings'); - } - } - - public async emit({ - instance, - remoteJid, - msg, - }: { - instance: InstanceDto; - remoteJid: string; - msg: any; - pushName?: string; - }) { - if (!this.integrationEnabled) return; - - try { - const instanceData = await this.prismaRepository.instance.findFirst({ - where: { - name: instance.instanceName, - }, - }); - - if (!instanceData) throw new Error('Instance not found'); - - const session = await this.getSession(remoteJid, instance); - - const content = getConversationMessage(msg); - - let findBot = (await this.findBotTrigger( - this.botRepository, - this.settingsRepository, - content, - instance, - session, - )) as TypebotModel; - - if (!findBot) { - const fallback = await this.settingsRepository.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - if (fallback?.typebotIdFallback) { - const findFallback = await this.botRepository.findFirst({ - where: { - id: fallback.typebotIdFallback, - }, - }); - - findBot = findFallback; - } else { - return; - } - } - - const settings = await this.prismaRepository.typebotSetting.findFirst({ - where: { - instanceId: instance.instanceId, - }, - }); - - const url = findBot?.url; - const typebot = findBot?.typebot; - let expire = findBot?.expire; - let keywordFinish = findBot?.keywordFinish; - let delayMessage = findBot?.delayMessage; - let unknownMessage = findBot?.unknownMessage; - let listeningFromMe = findBot?.listeningFromMe; - let stopBotFromMe = findBot?.stopBotFromMe; - let keepOpen = findBot?.keepOpen; - let debounceTime = findBot?.debounceTime; - let ignoreJids = findBot?.ignoreJids; - - if (expire === undefined || expire === null) expire = settings.expire; - if (keywordFinish === undefined || keywordFinish === null) keywordFinish = settings.keywordFinish; - if (delayMessage === undefined || delayMessage === null) delayMessage = settings.delayMessage; - if (unknownMessage === undefined || unknownMessage === null) unknownMessage = settings.unknownMessage; - if (listeningFromMe === undefined || listeningFromMe === null) listeningFromMe = settings.listeningFromMe; - if (stopBotFromMe === undefined || stopBotFromMe === null) stopBotFromMe = settings.stopBotFromMe; - if (keepOpen === undefined || keepOpen === null) keepOpen = settings.keepOpen; - if (debounceTime === undefined || debounceTime === null) debounceTime = settings.debounceTime; - if (ignoreJids === undefined || ignoreJids === null) ignoreJids = settings.ignoreJids; - - if (this.checkIgnoreJids(ignoreJids, remoteJid)) return; - - const key = msg.key as { - id: string; - remoteJid: string; - fromMe: boolean; - participant: string; - }; - - if (stopBotFromMe && key.fromMe && session) { - await this.sessionRepository.update({ - where: { - id: session.id, - }, - data: { - status: 'paused', - }, - }); - return; - } - - if (!listeningFromMe && key.fromMe) { - return; - } - - if (session && !session.awaitUser) { - return; - } - - if (debounceTime && debounceTime > 0) { - this.processDebounce(this.userMessageDebounce, content, remoteJid, debounceTime, async (debouncedContent) => { - await this.typebotService.processTypebot( - instanceData, - remoteJid, - msg, - session, - findBot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - debouncedContent, - ); - }); - } else { - await this.typebotService.processTypebot( - instanceData, - remoteJid, - msg, - session, - findBot, - url, - expire, - typebot, - keywordFinish, - delayMessage, - unknownMessage, - listeningFromMe, - stopBotFromMe, - keepOpen, - content, - ); - } - - if (session && !session.awaitUser) return; - } catch (error) { - this.logger.error(error); - return; - } - } } diff --git a/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts index a7565236e..a0c06ae4b 100644 --- a/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts +++ b/src/api/integrations/chatbot/typebot/dto/typebot.dto.ts @@ -1,4 +1,4 @@ -import { TriggerOperator, TriggerType } from '@prisma/client'; +import { BaseChatbotDto, BaseChatbotSettingDto } from '../../base-chatbot.dto'; export class PrefilledVariables { remoteJid?: string; @@ -7,34 +7,11 @@ export class PrefilledVariables { additionalData?: { [key: string]: any }; } -export class TypebotDto { - enabled?: boolean; - description?: string; +export class TypebotDto extends BaseChatbotDto { url: string; - typebot?: string; - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; - triggerType?: TriggerType; - triggerOperator?: TriggerOperator; - triggerValue?: string; - ignoreJids?: any; + typebot: string; } -export class TypebotSettingDto { - expire?: number; - keywordFinish?: string; - delayMessage?: number; - unknownMessage?: string; - listeningFromMe?: boolean; - stopBotFromMe?: boolean; - keepOpen?: boolean; - debounceTime?: number; +export class TypebotSettingDto extends BaseChatbotSettingDto { typebotIdFallback?: string; - ignoreJids?: any; } diff --git a/src/api/integrations/chatbot/typebot/services/typebot.service.ts b/src/api/integrations/chatbot/typebot/services/typebot.service.ts index f0e4dc7f7..03712bfdb 100644 --- a/src/api/integrations/chatbot/typebot/services/typebot.service.ts +++ b/src/api/integrations/chatbot/typebot/services/typebot.service.ts @@ -1,21 +1,87 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; +import { Events } from '@api/types/wa.types'; import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config'; -import { Logger } from '@config/logger.config'; import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client'; import { getConversationMessage } from '@utils/getConversationMessage'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; -export class TypebotService { +import { BaseChatbotService } from '../../base-chatbot.service'; +import { OpenaiService } from '../../openai/services/openai.service'; + +export class TypebotService extends BaseChatbotService { + private openaiService: OpenaiService; + constructor( - private readonly waMonitor: WAMonitoringService, - private readonly configService: ConfigService, - private readonly prismaRepository: PrismaRepository, - ) {} + waMonitor: WAMonitoringService, + configService: ConfigService, + prismaRepository: PrismaRepository, + openaiService: OpenaiService, + ) { + super(waMonitor, prismaRepository, 'TypebotService', configService); + this.openaiService = openaiService; + } - private readonly logger = new Logger('TypebotService'); + /** + * Get the bot type identifier + */ + protected getBotType(): string { + return 'typebot'; + } + + /** + * Base class wrapper - calls the original processTypebot method + */ + protected async sendMessageToBot( + instance: any, + session: IntegrationSession, + settings: any, + bot: TypebotModel, + remoteJid: string, + pushName: string, + content: string, + msg?: any, + ): Promise { + // Map the base class call to the original processTypebot method + await this.processTypebot( + instance, + remoteJid, + msg, + session, + bot, + bot.url, + settings.expire, + bot.typebot, + settings.keywordFinish, + settings.delayMessage, + settings.unknownMessage, + settings.listeningFromMe, + settings.stopBotFromMe, + settings.keepOpen, + content, + ); + } + /** + * Simplified wrapper for controller compatibility + */ + public async processTypebotSimple( + instance: any, + remoteJid: string, + bot: TypebotModel, + session: IntegrationSession, + settings: any, + content: string, + pushName?: string, + msg?: any, + ): Promise { + return this.process(instance, remoteJid, bot, session, settings, content, pushName, msg); + } + + /** + * Create a new TypeBot session with prefilled variables + */ public async createNewSession(instance: Instance, data: any) { if (data.remoteJid === 'status@broadcast') return; const id = Math.floor(Math.random() * 10000000000).toString(); @@ -77,11 +143,23 @@ export class TypebotService { }, awaitUser: false, botId: data.botId, - instanceId: instance.id, type: 'typebot', + Instance: { + connect: { + id: instance.id, + }, + }, }, }); } + + const typebotData = { + remoteJid: data.remoteJid, + status: 'opened', + session, + }; + this.waMonitor.waInstances[instance.name].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + return { ...request.data, session }; } catch (error) { this.logger.error(error); @@ -89,8 +167,11 @@ export class TypebotService { } } + /** + * Send WhatsApp message with complex TypeBot formatting + */ public async sendWAMessage( - instance: Instance, + instanceDb: Instance, session: IntegrationSession, settings: { expire: number; @@ -106,474 +187,384 @@ export class TypebotService { input: any, clientSideActions: any, ) { - processMessages( - this.waMonitor.waInstances[instance.name], + const waInstance = this.waMonitor.waInstances[instanceDb.name]; + await this.processMessages( + waInstance, session, settings, messages, input, clientSideActions, - applyFormatting, + this.applyFormatting.bind(this), this.prismaRepository, ).catch((err) => { console.error('Erro ao processar mensagens:', err); }); + } - function findItemAndGetSecondsToWait(array, targetId) { - if (!array) return null; + /** + * Apply rich text formatting for TypeBot messages + */ + private applyFormatting(element: any): string { + let text = ''; - for (const item of array) { - if (item.lastBubbleBlockId === targetId) { - return item.wait?.secondsToWaitFor; - } - } - return null; + if (element.text) { + text += element.text; } - function applyFormatting(element) { - let text = ''; - - if (element.text) { - text += element.text; - } - - if (element.children && element.type !== 'a') { - for (const child of element.children) { - text += applyFormatting(child); - } - } - - if (element.type === 'p' && element.type !== 'inline-variable') { - text = text.trim() + '\n'; + if (element.children && element.type !== 'a') { + for (const child of element.children) { + text += this.applyFormatting(child); } + } - if (element.type === 'inline-variable') { - text = text.trim(); - } + if (element.type === 'p' && element.type !== 'inline-variable') { + text = text.trim() + '\n'; + } - if (element.type === 'ol') { - text = - '\n' + - text - .split('\n') - .map((line, index) => (line ? `${index + 1}. ${line}` : '')) - .join('\n'); - } + if (element.type === 'inline-variable') { + text = text.trim(); + } - if (element.type === 'li') { - text = text + if (element.type === 'ol') { + text = + '\n' + + text .split('\n') - .map((line) => (line ? ` ${line}` : '')) + .map((line, index) => (line ? `${index + 1}. ${line}` : '')) .join('\n'); - } - - let formats = ''; - - if (element.bold) { - formats += '*'; - } - - if (element.italic) { - formats += '_'; - } - - if (element.underline) { - formats += '~'; - } + } - let formattedText = `${formats}${text}${formats.split('').reverse().join('')}`; + if (element.type === 'li') { + text = text + .split('\n') + .map((line) => (line ? ` ${line}` : '')) + .join('\n'); + } - if (element.url) { - formattedText = element.children[0]?.text ? `[${formattedText}]\n(${element.url})` : `${element.url}`; - } + let formats = ''; - return formattedText; + if (element.bold) { + formats += '*'; } - async function processMessages( - instance: any, - session: IntegrationSession, - settings: { - expire: number; - keywordFinish: string; - delayMessage: number; - unknownMessage: string; - listeningFromMe: boolean; - stopBotFromMe: boolean; - keepOpen: boolean; - }, - messages: any, - input: any, - clientSideActions: any, - applyFormatting: any, - prismaRepository: PrismaRepository, - ) { - for (const message of messages) { - if (message.type === 'text') { - let formattedText = ''; - - for (const richText of message.content.richText) { - for (const element of richText.children) { - formattedText += applyFormatting(element); - } - formattedText += '\n'; - } + if (element.italic) { + formats += '_'; + } - formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, ''); + if (element.underline) { + formats += '~'; + } - formattedText = formattedText.replace(/\n$/, ''); + let formattedText = `${formats}${text}${formats.split('').reverse().join('')}`; - if (formattedText.includes('[list]')) { - const listJson = { - number: remoteJid.split('@')[0], - title: '', - description: '', - buttonText: '', - footerText: '', - sections: [], - }; + if (element.url) { + formattedText = element.children[0]?.text ? `[${formattedText}]\n(${element.url})` : `${element.url}`; + } - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[buttonText\])/); - const buttonTextMatch = formattedText.match(/\[buttonText\]([\s\S]*?)(?=\[footerText\])/); - const footerTextMatch = formattedText.match(/\[footerText\]([\s\S]*?)(?=\[menu\])/); - - if (titleMatch) listJson.title = titleMatch[1].trim(); - if (descriptionMatch) listJson.description = descriptionMatch[1].trim(); - if (buttonTextMatch) listJson.buttonText = buttonTextMatch[1].trim(); - if (footerTextMatch) listJson.footerText = footerTextMatch[1].trim(); - - const menuContent = formattedText.match(/\[menu\]([\s\S]*?)\[\/menu\]/)?.[1]; - if (menuContent) { - const sections = menuContent.match(/\[section\]([\s\S]*?)(?=\[section\]|\[\/section\]|\[\/menu\])/g); - if (sections) { - sections.forEach((section) => { - const sectionTitle = section.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(); - const rows = section.match(/\[row\]([\s\S]*?)(?=\[row\]|\[\/row\]|\[\/section\]|\[\/menu\])/g); - - const sectionData = { - title: sectionTitle, - rows: - rows?.map((row) => ({ - title: row.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(), - description: row.match(/description: (.*?)(?:\n|$)/)?.[1]?.trim(), - rowId: row.match(/rowId: (.*?)(?:\n|$)/)?.[1]?.trim(), - })) || [], - }; - - listJson.sections.push(sectionData); - }); - } - } + return formattedText; + } - await instance.listMessage(listJson); - } else if (formattedText.includes('[buttons]')) { - const buttonJson = { - number: remoteJid.split('@')[0], - thumbnailUrl: undefined, - title: '', - description: '', - footer: '', - buttons: [], - }; + /** + * Process TypeBot messages with full feature support + */ + private async processMessages( + instance: any, + session: IntegrationSession, + settings: { + expire: number; + keywordFinish: string; + delayMessage: number; + unknownMessage: string; + listeningFromMe: boolean; + stopBotFromMe: boolean; + keepOpen: boolean; + }, + messages: any, + input: any, + clientSideActions: any, + applyFormatting: any, + prismaRepository: PrismaRepository, + ) { + // Helper function to find wait time + const findItemAndGetSecondsToWait = (array: any[], targetId: string) => { + if (!array) return null; - const thumbnailUrlMatch = formattedText.match(/\[thumbnailUrl\]([\s\S]*?)(?=\[title\])/); - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[footer\])/); - const footerMatch = formattedText.match(/\[footer\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url))/); - - if (titleMatch) buttonJson.title = titleMatch[1].trim(); - if (thumbnailUrlMatch) buttonJson.thumbnailUrl = thumbnailUrlMatch[1].trim(); - if (descriptionMatch) buttonJson.description = descriptionMatch[1].trim(); - if (footerMatch) buttonJson.footer = footerMatch[1].trim(); - - const buttonTypes = { - reply: /\[reply\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - pix: /\[pix\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - copy: /\[copy\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - call: /\[call\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - url: /\[url\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - }; + for (const item of array) { + if (item.lastBubbleBlockId === targetId) { + return item.wait?.secondsToWaitFor; + } + } + return null; + }; - for (const [type, pattern] of Object.entries(buttonTypes)) { - let match; - while ((match = pattern.exec(formattedText)) !== null) { - const content = match[1].trim(); - const button: any = { type }; - - switch (type) { - case 'pix': - button.currency = content.match(/currency: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.name = content.match(/name: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.keyType = content.match(/keyType: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.key = content.match(/key: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'reply': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.id = content.match(/id: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'copy': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.copyCode = content.match(/copyCode: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'call': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.phoneNumber = content.match(/phone: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'url': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.url = content.match(/url: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - } - - if (Object.keys(button).length > 1) { - buttonJson.buttons.push(button); - } - } - } + for (const message of messages) { + if (message.type === 'text') { + let formattedText = ''; - await instance.buttonMessage(buttonJson); - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); + for (const richText of message.content.richText) { + for (const element of richText.children) { + formattedText += applyFormatting(element); } - - sendTelemetry('/message/sendText'); + formattedText += '\n'; } - if (message.type === 'image') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'image', - media: message.content.url, - }, - null, - false, - ); - - sendTelemetry('/message/sendMedia'); - } + formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, ''); - if (message.type === 'video') { - await instance.mediaMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - mediatype: 'video', - media: message.content.url, - }, - null, - false, - ); + formattedText = formattedText.replace(/\n$/, ''); - sendTelemetry('/message/sendMedia'); + if (formattedText.includes('[list]')) { + await this.processListMessage(instance, formattedText, session.remoteJid); + } else if (formattedText.includes('[buttons]')) { + await this.processButtonMessage(instance, formattedText, session.remoteJid); + } else { + await this.sendMessageWhatsApp(instance, session.remoteJid, formattedText, settings, true); } - if (message.type === 'audio') { - await instance.audioWhatsapp( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - encoding: true, - audio: message.content.url, - }, - false, - ); - - sendTelemetry('/message/sendWhatsAppAudio'); - } + sendTelemetry('/message/sendText'); + } - const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); + if (message.type === 'image') { + await instance.mediaMessage( + { + number: session.remoteJid, + delay: settings?.delayMessage || 1000, + mediatype: 'image', + media: message.content.url, + }, + null, + false, + ); - if (wait) { - await new Promise((resolve) => setTimeout(resolve, wait * 1000)); - } + sendTelemetry('/message/sendMedia'); } - console.log('input', input); - if (input) { - if (input.type === 'choice input') { - let formattedText = ''; + if (message.type === 'video') { + await instance.mediaMessage( + { + number: session.remoteJid, + delay: settings?.delayMessage || 1000, + mediatype: 'video', + media: message.content.url, + }, + null, + false, + ); - const items = input.items; + sendTelemetry('/message/sendMedia'); + } - for (const item of items) { - formattedText += `▶️ ${item.content}\n`; - } + if (message.type === 'audio') { + await instance.audioWhatsapp( + { + number: session.remoteJid, + delay: settings?.delayMessage || 1000, + encoding: true, + audio: message.content.url, + }, + false, + ); - formattedText = formattedText.replace(/\n$/, ''); + sendTelemetry('/message/sendWhatsAppAudio'); + } - if (formattedText.includes('[list]')) { - const listJson = { - number: remoteJid.split('@')[0], - title: '', - description: '', - buttonText: '', - footerText: '', - sections: [], - }; + const wait = findItemAndGetSecondsToWait(clientSideActions, message.id); - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[buttonText\])/); - const buttonTextMatch = formattedText.match(/\[buttonText\]([\s\S]*?)(?=\[footerText\])/); - const footerTextMatch = formattedText.match(/\[footerText\]([\s\S]*?)(?=\[menu\])/); - - if (titleMatch) listJson.title = titleMatch[1].trim(); - if (descriptionMatch) listJson.description = descriptionMatch[1].trim(); - if (buttonTextMatch) listJson.buttonText = buttonTextMatch[1].trim(); - if (footerTextMatch) listJson.footerText = footerTextMatch[1].trim(); - - const menuContent = formattedText.match(/\[menu\]([\s\S]*?)\[\/menu\]/)?.[1]; - if (menuContent) { - const sections = menuContent.match(/\[section\]([\s\S]*?)(?=\[section\]|\[\/section\]|\[\/menu\])/g); - if (sections) { - sections.forEach((section) => { - const sectionTitle = section.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(); - const rows = section.match(/\[row\]([\s\S]*?)(?=\[row\]|\[\/row\]|\[\/section\]|\[\/menu\])/g); - - const sectionData = { - title: sectionTitle, - rows: - rows?.map((row) => ({ - title: row.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(), - description: row.match(/description: (.*?)(?:\n|$)/)?.[1]?.trim(), - rowId: row.match(/rowId: (.*?)(?:\n|$)/)?.[1]?.trim(), - })) || [], - }; - - listJson.sections.push(sectionData); - }); - } - } + if (wait) { + await new Promise((resolve) => setTimeout(resolve, wait * 1000)); + } + } - await instance.listMessage(listJson); - } else if (formattedText.includes('[buttons]')) { - const buttonJson = { - number: remoteJid.split('@')[0], - thumbnailUrl: undefined, - title: '', - description: '', - footer: '', - buttons: [], - }; + // Process input choices + if (input) { + if (input.type === 'choice input') { + let formattedText = ''; - const thumbnailUrlMatch = formattedText.match(/\[thumbnailUrl\]([\s\S]*?)(?=\[title\])/); - const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); - const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[footer\])/); - const footerMatch = formattedText.match(/\[footer\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url))/); - - if (titleMatch) buttonJson.title = titleMatch[1].trim(); - if (thumbnailUrlMatch) buttonJson.thumbnailUrl = thumbnailUrlMatch[1].trim(); - if (descriptionMatch) buttonJson.description = descriptionMatch[1].trim(); - if (footerMatch) buttonJson.footer = footerMatch[1].trim(); - - const buttonTypes = { - reply: /\[reply\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - pix: /\[pix\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - copy: /\[copy\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - call: /\[call\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - url: /\[url\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, - }; + const items = input.items; - for (const [type, pattern] of Object.entries(buttonTypes)) { - let match; - while ((match = pattern.exec(formattedText)) !== null) { - const content = match[1].trim(); - const button: any = { type }; - - switch (type) { - case 'pix': - button.currency = content.match(/currency: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.name = content.match(/name: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.keyType = content.match(/keyType: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.key = content.match(/key: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'reply': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.id = content.match(/id: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'copy': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.copyCode = content.match(/copyCode: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'call': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.phoneNumber = content.match(/phone: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - - case 'url': - button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); - button.url = content.match(/url: (.*?)(?:\n|$)/)?.[1]?.trim(); - break; - } - - if (Object.keys(button).length > 1) { - buttonJson.buttons.push(button); - } - } - } + for (const item of items) { + formattedText += `▶️ ${item.content}\n`; + } - await instance.buttonMessage(buttonJson); - } else { - await instance.textMessage( - { - number: remoteJid.split('@')[0], - delay: settings?.delayMessage || 1000, - text: formattedText, - }, - false, - ); - } + formattedText = formattedText.replace(/\n$/, ''); - sendTelemetry('/message/sendText'); + if (formattedText.includes('[list]')) { + await this.processListMessage(instance, formattedText, session.remoteJid); + } else if (formattedText.includes('[buttons]')) { + await this.processButtonMessage(instance, formattedText, session.remoteJid); + } else { + await this.sendMessageWhatsApp(instance, session.remoteJid, formattedText, settings, true); } + sendTelemetry('/message/sendText'); + } + + await prismaRepository.integrationSession.update({ + where: { + id: session.id, + }, + data: { + awaitUser: true, + }, + }); + } else { + let statusChange = 'closed'; + if (!settings?.keepOpen) { + await prismaRepository.integrationSession.deleteMany({ + where: { + id: session.id, + }, + }); + statusChange = 'delete'; + } else { await prismaRepository.integrationSession.update({ where: { id: session.id, }, data: { - awaitUser: true, + status: 'closed', }, }); - } else { - if (!settings?.keepOpen) { - await prismaRepository.integrationSession.deleteMany({ - where: { - id: session.id, - }, - }); - } else { - await prismaRepository.integrationSession.update({ - where: { - id: session.id, - }, - data: { - status: 'closed', - }, - }); + } + + const typebotData = { + remoteJid: session.remoteJid, + status: statusChange, + session, + }; + instance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + } + } + + /** + * Process list messages for WhatsApp + */ + private async processListMessage(instance: any, formattedText: string, remoteJid: string) { + const listJson = { + number: remoteJid, + title: '', + description: '', + buttonText: '', + footerText: '', + sections: [], + }; + + const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); + const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[buttonText\])/); + const buttonTextMatch = formattedText.match(/\[buttonText\]([\s\S]*?)(?=\[footerText\])/); + const footerTextMatch = formattedText.match(/\[footerText\]([\s\S]*?)(?=\[menu\])/); + + if (titleMatch) listJson.title = titleMatch[1].trim(); + if (descriptionMatch) listJson.description = descriptionMatch[1].trim(); + if (buttonTextMatch) listJson.buttonText = buttonTextMatch[1].trim(); + if (footerTextMatch) listJson.footerText = footerTextMatch[1].trim(); + + const menuContent = formattedText.match(/\[menu\]([\s\S]*?)\[\/menu\]/)?.[1]; + if (menuContent) { + const sections = menuContent.match(/\[section\]([\s\S]*?)(?=\[section\]|\[\/section\]|\[\/menu\])/g); + if (sections) { + sections.forEach((section) => { + const sectionTitle = section.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(); + const rows = section.match(/\[row\]([\s\S]*?)(?=\[row\]|\[\/row\]|\[\/section\]|\[\/menu\])/g); + + const sectionData = { + title: sectionTitle, + rows: + rows?.map((row) => ({ + title: row.match(/title: (.*?)(?:\n|$)/)?.[1]?.trim(), + description: row.match(/description: (.*?)(?:\n|$)/)?.[1]?.trim(), + rowId: row.match(/rowId: (.*?)(?:\n|$)/)?.[1]?.trim(), + })) || [], + }; + + listJson.sections.push(sectionData); + }); + } + } + + await instance.listMessage(listJson); + } + + /** + * Process button messages for WhatsApp + */ + private async processButtonMessage(instance: any, formattedText: string, remoteJid: string) { + const buttonJson = { + number: remoteJid, + thumbnailUrl: undefined, + title: '', + description: '', + footer: '', + buttons: [], + }; + + const thumbnailUrlMatch = formattedText.match(/\[thumbnailUrl\]([\s\S]*?)(?=\[title\])/); + const titleMatch = formattedText.match(/\[title\]([\s\S]*?)(?=\[description\])/); + const descriptionMatch = formattedText.match(/\[description\]([\s\S]*?)(?=\[footer\])/); + const footerMatch = formattedText.match(/\[footer\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url))/); + + if (titleMatch) buttonJson.title = titleMatch[1].trim(); + if (thumbnailUrlMatch) buttonJson.thumbnailUrl = thumbnailUrlMatch[1].trim(); + if (descriptionMatch) buttonJson.description = descriptionMatch[1].trim(); + if (footerMatch) buttonJson.footer = footerMatch[1].trim(); + + const buttonTypes = { + reply: /\[reply\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, + pix: /\[pix\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, + copy: /\[copy\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, + call: /\[call\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, + url: /\[url\]([\s\S]*?)(?=\[(?:reply|pix|copy|call|url)|$)/g, + }; + + for (const [type, pattern] of Object.entries(buttonTypes)) { + let match; + while ((match = pattern.exec(formattedText)) !== null) { + const content = match[1].trim(); + const button: any = { type }; + + switch (type) { + case 'pix': + button.currency = content.match(/currency: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.name = content.match(/name: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.keyType = content.match(/keyType: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.key = content.match(/key: (.*?)(?:\n|$)/)?.[1]?.trim(); + break; + + case 'reply': + button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.id = content.match(/id: (.*?)(?:\n|$)/)?.[1]?.trim(); + break; + + case 'copy': + button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.copyCode = content.match(/copyCode: (.*?)(?:\n|$)/)?.[1]?.trim(); + break; + + case 'call': + button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.phoneNumber = content.match(/phone: (.*?)(?:\n|$)/)?.[1]?.trim(); + break; + + case 'url': + button.displayText = content.match(/displayText: (.*?)(?:\n|$)/)?.[1]?.trim(); + button.url = content.match(/url: (.*?)(?:\n|$)/)?.[1]?.trim(); + break; + } + + if (Object.keys(button).length > 1) { + buttonJson.buttons.push(button); } } } + + await instance.buttonMessage(buttonJson); } + /** + * Original TypeBot processing method with full functionality + */ public async processTypebot( - instance: Instance, + waInstance: any, remoteJid: string, msg: Message, session: IntegrationSession, @@ -590,13 +581,22 @@ export class TypebotService { content: string, prefilledVariables?: any, ) { + // Get the database instance record + const instance = await this.prismaRepository.instance.findFirst({ + where: { + name: waInstance.instanceName, + }, + }); + + if (!instance) { + this.logger.error('Instance not found in database'); + return; + } + // Handle session expiration if (session && expire && expire > 0) { const now = Date.now(); - const sessionUpdatedAt = new Date(session.updatedAt).getTime(); - const diff = now - sessionUpdatedAt; - const diffInMinutes = Math.floor(diff / 1000 / 60); if (diffInMinutes > expire) { @@ -633,30 +633,37 @@ export class TypebotService { prefilledVariables: prefilledVariables, }); - if (data.session) { + if (data?.session) { session = data.session; } - if (data.messages.length === 0) { + if (!data?.messages || data.messages.length === 0) { const content = getConversationMessage(msg.message); if (!content) { if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( + await this.sendMessageWhatsApp( + waInstance, + remoteJid, + unknownMessage, { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, + delayMessage, + expire, + keywordFinish, + listeningFromMe, + stopBotFromMe, + keepOpen, + unknownMessage, }, - false, + true, ); - sendTelemetry('/message/sendText'); } return; } if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + let statusChange = 'closed'; if (keepOpen) { await this.prismaRepository.integrationSession.update({ where: { @@ -667,6 +674,7 @@ export class TypebotService { }, }); } else { + statusChange = 'delete'; await this.prismaRepository.integrationSession.deleteMany({ where: { botId: findTypebot.id, @@ -674,6 +682,14 @@ export class TypebotService { }, }); } + + const typebotData = { + remoteJid: remoteJid, + status: statusChange, + session, + }; + waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + return; } @@ -682,7 +698,7 @@ export class TypebotService { let urlTypebot: string; let reqData: {}; if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; + urlTypebot = `${url}/api/v1/sessions/${data?.sessionId}/continueChat`; reqData = { message: content, }; @@ -690,7 +706,7 @@ export class TypebotService { urlTypebot = `${url}/api/v1/sendMessage`; reqData = { message: content, - sessionId: data.sessionId, + sessionId: data?.sessionId, }; } @@ -709,9 +725,9 @@ export class TypebotService { keepOpen: keepOpen, }, remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, + request?.data?.messages, + request?.data?.input, + request?.data?.clientSideActions, ); } catch (error) { this.logger.error(error); @@ -719,23 +735,25 @@ export class TypebotService { } } - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data.messages, - data.input, - data.clientSideActions, - ); + if (data?.messages && data.messages.length > 0) { + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + data.messages, + data.input, + data.clientSideActions, + ); + } return; } @@ -745,6 +763,7 @@ export class TypebotService { return; } + // Handle new sessions if (!session) { const data = await this.createNewSession(instance, { enabled: findTypebot?.enabled, @@ -765,42 +784,51 @@ export class TypebotService { session = data.session; } - await this.sendWAMessage( - instance, - session, - { - expire: expire, - keywordFinish: keywordFinish, - delayMessage: delayMessage, - unknownMessage: unknownMessage, - listeningFromMe: listeningFromMe, - stopBotFromMe: stopBotFromMe, - keepOpen: keepOpen, - }, - remoteJid, - data?.messages, - data?.input, - data?.clientSideActions, - ); + if (data?.messages && data.messages.length > 0) { + await this.sendWAMessage( + instance, + session, + { + expire: expire, + keywordFinish: keywordFinish, + delayMessage: delayMessage, + unknownMessage: unknownMessage, + listeningFromMe: listeningFromMe, + stopBotFromMe: stopBotFromMe, + keepOpen: keepOpen, + }, + remoteJid, + data.messages, + data.input, + data.clientSideActions, + ); + } - if (data.messages.length === 0) { + if (!data?.messages || data.messages.length === 0) { if (!content) { if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( + await this.sendMessageWhatsApp( + waInstance, + remoteJid, + unknownMessage, { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, + delayMessage, + expire, + keywordFinish, + listeningFromMe, + stopBotFromMe, + keepOpen, + unknownMessage, }, - false, + true, ); - sendTelemetry('/message/sendText'); } return; } if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + let statusChange = 'closed'; if (keepOpen) { await this.prismaRepository.integrationSession.update({ where: { @@ -811,6 +839,7 @@ export class TypebotService { }, }); } else { + statusChange = 'delete'; await this.prismaRepository.integrationSession.deleteMany({ where: { botId: findTypebot.id, @@ -819,6 +848,13 @@ export class TypebotService { }); } + const typebotData = { + remoteJid: remoteJid, + status: statusChange, + session, + }; + waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + return; } @@ -828,7 +864,7 @@ export class TypebotService { let urlTypebot: string; let reqData: {}; if (version === 'latest') { - urlTypebot = `${url}/api/v1/sessions/${data.sessionId}/continueChat`; + urlTypebot = `${url}/api/v1/sessions/${data?.sessionId}/continueChat`; reqData = { message: content, }; @@ -836,7 +872,7 @@ export class TypebotService { urlTypebot = `${url}/api/v1/sendMessage`; reqData = { message: content, - sessionId: data.sessionId, + sessionId: data?.sessionId, }; } request = await axios.post(urlTypebot, reqData); @@ -854,9 +890,9 @@ export class TypebotService { keepOpen: keepOpen, }, remoteJid, - request.data.messages, - request.data.input, - request.data.clientSideActions, + request?.data?.messages, + request?.data?.input, + request?.data?.clientSideActions, ); } catch (error) { this.logger.error(error); @@ -866,6 +902,7 @@ export class TypebotService { return; } + // Update existing session await this.prismaRepository.integrationSession.update({ where: { id: session.id, @@ -878,21 +915,28 @@ export class TypebotService { if (!content) { if (unknownMessage) { - this.waMonitor.waInstances[instance.name].textMessage( + await this.sendMessageWhatsApp( + waInstance, + remoteJid, + unknownMessage, { - number: remoteJid.split('@')[0], - delay: delayMessage || 1000, - text: unknownMessage, + delayMessage, + expire, + keywordFinish, + listeningFromMe, + stopBotFromMe, + keepOpen, + unknownMessage, }, - false, + true, ); - sendTelemetry('/message/sendText'); } return; } if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) { + let statusChange = 'closed'; if (keepOpen) { await this.prismaRepository.integrationSession.update({ where: { @@ -903,6 +947,7 @@ export class TypebotService { }, }); } else { + statusChange = 'delete'; await this.prismaRepository.integrationSession.deleteMany({ where: { botId: findTypebot.id, @@ -910,12 +955,22 @@ export class TypebotService { }, }); } + + const typebotData = { + remoteJid: remoteJid, + status: statusChange, + session, + }; + + waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData); + return; } + // Continue existing chat const version = this.configService.get('TYPEBOT').API_VERSION; let urlTypebot: string; - let reqData: {}; + let reqData: { message: string; sessionId?: string }; if (version === 'latest') { urlTypebot = `${url}/api/v1/sessions/${session.sessionId.split('-')[1]}/continueChat`; reqData = { @@ -928,6 +983,20 @@ export class TypebotService { sessionId: session.sessionId.split('-')[1], }; } + + // Handle audio transcription if OpenAI service is available + if (this.isAudioMessage(content) && msg) { + try { + this.logger.debug(`[TypeBot] Downloading audio for Whisper transcription`); + const transcription = await this.openaiService.speechToText(msg, instance); + if (transcription) { + reqData.message = `[audio] ${transcription}`; + } + } catch (err) { + this.logger.error(`[TypeBot] Failed to transcribe audio: ${err}`); + } + } + const request = await axios.post(urlTypebot, reqData); await this.sendWAMessage( diff --git a/src/api/integrations/event/event.controller.ts b/src/api/integrations/event/event.controller.ts index 0afbead55..39b52184b 100644 --- a/src/api/integrations/event/event.controller.ts +++ b/src/api/integrations/event/event.controller.ts @@ -13,17 +13,30 @@ export type EmitData = { sender: string; apiKey?: string; local?: boolean; + integration?: string[]; + extra?: Record; }; export interface EventControllerInterface { set(instanceName: string, data: any): Promise; get(instanceName: string): Promise; - emit({ instanceName, origin, event, data, serverUrl, dateTime, sender, apiKey, local }: EmitData): Promise; + emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + local, + extra, + }: EmitData): Promise; } export class EventController { public prismaRepository: PrismaRepository; - private waMonitor: WAMonitoringService; + protected waMonitor: WAMonitoringService; private integrationStatus: boolean; private integrationName: string; @@ -131,6 +144,7 @@ export class EventController { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -150,5 +164,8 @@ export class EventController { 'TYPEBOT_CHANGE_STATUS', 'REMOVE_INSTANCE', 'LOGOUT_INSTANCE', + 'INSTANCE_CREATE', + 'INSTANCE_DELETE', + 'STATUS_INSTANCE', ]; } diff --git a/src/api/integrations/event/event.dto.ts b/src/api/integrations/event/event.dto.ts index eaa7cc408..b5292993d 100644 --- a/src/api/integrations/event/event.dto.ts +++ b/src/api/integrations/event/event.dto.ts @@ -26,6 +26,11 @@ export class EventDto { events?: string[]; }; + nats?: { + enabled?: boolean; + events?: string[]; + }; + pusher?: { enabled?: boolean; appId?: string; @@ -35,6 +40,11 @@ export class EventDto { useTLS?: boolean; events?: string[]; }; + + kafka?: { + enabled?: boolean; + events?: string[]; + }; } export function EventInstanceMixin(Base: TBase) { @@ -63,6 +73,11 @@ export function EventInstanceMixin(Base: TBase) { events?: string[]; }; + nats?: { + enabled?: boolean; + events?: string[]; + }; + pusher?: { enabled?: boolean; appId?: string; @@ -72,5 +87,10 @@ export function EventInstanceMixin(Base: TBase) { useTLS?: boolean; events?: string[]; }; + + kafka?: { + enabled?: boolean; + events?: string[]; + }; }; } diff --git a/src/api/integrations/event/event.manager.ts b/src/api/integrations/event/event.manager.ts index b1a21db44..5dd3fcf26 100644 --- a/src/api/integrations/event/event.manager.ts +++ b/src/api/integrations/event/event.manager.ts @@ -1,3 +1,5 @@ +import { KafkaController } from '@api/integrations/event/kafka/kafka.controller'; +import { NatsController } from '@api/integrations/event/nats/nats.controller'; import { PusherController } from '@api/integrations/event/pusher/pusher.controller'; import { RabbitmqController } from '@api/integrations/event/rabbitmq/rabbitmq.controller'; import { SqsController } from '@api/integrations/event/sqs/sqs.controller'; @@ -13,8 +15,10 @@ export class EventManager { private websocketController: WebsocketController; private webhookController: WebhookController; private rabbitmqController: RabbitmqController; + private natsController: NatsController; private sqsController: SqsController; private pusherController: PusherController; + private kafkaController: KafkaController; constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { this.prisma = prismaRepository; @@ -23,8 +27,10 @@ export class EventManager { this.websocket = new WebsocketController(prismaRepository, waMonitor); this.webhook = new WebhookController(prismaRepository, waMonitor); this.rabbitmq = new RabbitmqController(prismaRepository, waMonitor); + this.nats = new NatsController(prismaRepository, waMonitor); this.sqs = new SqsController(prismaRepository, waMonitor); this.pusher = new PusherController(prismaRepository, waMonitor); + this.kafka = new KafkaController(prismaRepository, waMonitor); } public set prisma(prisma: PrismaRepository) { @@ -67,6 +73,14 @@ export class EventManager { return this.rabbitmqController; } + public set nats(nats: NatsController) { + this.natsController = nats; + } + + public get nats() { + return this.natsController; + } + public set sqs(sqs: SqsController) { this.sqsController = sqs; } @@ -82,57 +96,82 @@ export class EventManager { return this.pusherController; } + public set kafka(kafka: KafkaController) { + this.kafkaController = kafka; + } + public get kafka() { + return this.kafkaController; + } + public init(httpServer: Server): void { this.websocket.init(httpServer); this.rabbitmq.init(); + this.nats.init(); this.sqs.init(); this.pusher.init(); + this.kafka.init(); } public async emit(eventData: { instanceName: string; origin: string; event: string; - data: Object; + data: object; serverUrl: string; dateTime: string; sender: string; apiKey?: string; local?: boolean; + integration?: string[]; + extra?: Record; }): Promise { await this.websocket.emit(eventData); await this.rabbitmq.emit(eventData); + await this.nats.emit(eventData); await this.sqs.emit(eventData); await this.webhook.emit(eventData); await this.pusher.emit(eventData); + await this.kafka.emit(eventData); } public async setInstance(instanceName: string, data: any): Promise { - if (data.websocket) + if (data.websocket) { await this.websocket.set(instanceName, { websocket: { enabled: true, events: data.websocket?.events, }, }); + } - if (data.rabbitmq) + if (data.rabbitmq) { await this.rabbitmq.set(instanceName, { rabbitmq: { enabled: true, events: data.rabbitmq?.events, }, }); + } - if (data.sqs) + if (data.nats) { + await this.nats.set(instanceName, { + nats: { + enabled: true, + events: data.nats?.events, + }, + }); + } + + if (data.sqs) { await this.sqs.set(instanceName, { sqs: { enabled: true, events: data.sqs?.events, }, }); + } - if (data.webhook) + if (data.webhook) { await this.webhook.set(instanceName, { webhook: { enabled: true, @@ -143,8 +182,9 @@ export class EventManager { byEvents: data.webhook?.byEvents, }, }); + } - if (data.pusher) + if (data.pusher) { await this.pusher.set(instanceName, { pusher: { enabled: true, @@ -156,5 +196,15 @@ export class EventManager { useTLS: data.pusher?.useTLS, }, }); + } + + if (data.kafka) { + await this.kafka.set(instanceName, { + kafka: { + enabled: true, + events: data.kafka?.events, + }, + }); + } } } diff --git a/src/api/integrations/event/event.router.ts b/src/api/integrations/event/event.router.ts index 580b0324a..f80907bcd 100644 --- a/src/api/integrations/event/event.router.ts +++ b/src/api/integrations/event/event.router.ts @@ -1,3 +1,5 @@ +import { KafkaRouter } from '@api/integrations/event/kafka/kafka.router'; +import { NatsRouter } from '@api/integrations/event/nats/nats.router'; import { PusherRouter } from '@api/integrations/event/pusher/pusher.router'; import { RabbitmqRouter } from '@api/integrations/event/rabbitmq/rabbitmq.router'; import { SqsRouter } from '@api/integrations/event/sqs/sqs.router'; @@ -14,7 +16,9 @@ export class EventRouter { this.router.use('/webhook', new WebhookRouter(configService, ...guards).router); this.router.use('/websocket', new WebsocketRouter(...guards).router); this.router.use('/rabbitmq', new RabbitmqRouter(...guards).router); + this.router.use('/nats', new NatsRouter(...guards).router); this.router.use('/pusher', new PusherRouter(...guards).router); this.router.use('/sqs', new SqsRouter(...guards).router); + this.router.use('/kafka', new KafkaRouter(...guards).router); } } diff --git a/src/api/integrations/event/event.schema.ts b/src/api/integrations/event/event.schema.ts index 5ec8866f9..812bbd534 100644 --- a/src/api/integrations/event/event.schema.ts +++ b/src/api/integrations/event/event.schema.ts @@ -16,9 +16,15 @@ export const eventSchema: JSONSchema7 = { rabbitmq: { $ref: '#/$defs/event', }, + nats: { + $ref: '#/$defs/event', + }, sqs: { $ref: '#/$defs/event', }, + kafka: { + $ref: '#/$defs/event', + }, }, $defs: { event: { diff --git a/src/api/integrations/event/kafka/kafka.controller.ts b/src/api/integrations/event/kafka/kafka.controller.ts new file mode 100644 index 000000000..543c759ad --- /dev/null +++ b/src/api/integrations/event/kafka/kafka.controller.ts @@ -0,0 +1,416 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Kafka, Log } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { Consumer, ConsumerConfig, Kafka as KafkaJS, KafkaConfig, Producer, ProducerConfig } from 'kafkajs'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class KafkaController extends EventController implements EventControllerInterface { + private kafkaClient: KafkaJS | null = null; + private producer: Producer | null = null; + private consumer: Consumer | null = null; + private readonly logger = new Logger('KafkaController'); + private reconnectAttempts = 0; + private maxReconnectAttempts = 10; + private reconnectDelay = 5000; // 5 seconds + private isReconnecting = false; + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('KAFKA')?.ENABLED, 'kafka'); + } + + public async init(): Promise { + if (!this.status) { + return; + } + + await this.connect(); + } + + private async connect(): Promise { + try { + const kafkaConfig = configService.get('KAFKA'); + + const clientConfig: KafkaConfig = { + clientId: kafkaConfig.CLIENT_ID || 'evolution-api', + brokers: kafkaConfig.BROKERS || ['localhost:9092'], + connectionTimeout: kafkaConfig.CONNECTION_TIMEOUT || 3000, + requestTimeout: kafkaConfig.REQUEST_TIMEOUT || 30000, + retry: { + initialRetryTime: 100, + retries: 8, + }, + }; + + // Add SASL authentication if configured + if (kafkaConfig.SASL?.ENABLED) { + clientConfig.sasl = { + mechanism: (kafkaConfig.SASL.MECHANISM as any) || 'plain', + username: kafkaConfig.SASL.USERNAME, + password: kafkaConfig.SASL.PASSWORD, + }; + } + + // Add SSL configuration if enabled + if (kafkaConfig.SSL?.ENABLED) { + clientConfig.ssl = { + rejectUnauthorized: kafkaConfig.SSL.REJECT_UNAUTHORIZED !== false, + ca: kafkaConfig.SSL.CA ? [kafkaConfig.SSL.CA] : undefined, + key: kafkaConfig.SSL.KEY, + cert: kafkaConfig.SSL.CERT, + }; + } + + this.kafkaClient = new KafkaJS(clientConfig); + + // Initialize producer + const producerConfig: ProducerConfig = { + maxInFlightRequests: 1, + idempotent: true, + transactionTimeout: 30000, + }; + + this.producer = this.kafkaClient.producer(producerConfig); + await this.producer.connect(); + + // Initialize consumer for global events if enabled + if (kafkaConfig.GLOBAL_ENABLED) { + await this.initGlobalConsumer(); + } + + this.reconnectAttempts = 0; + this.isReconnecting = false; + + this.logger.info('Kafka initialized successfully'); + + // Create topics if they don't exist + if (kafkaConfig.AUTO_CREATE_TOPICS) { + await this.createTopics(); + } + } catch (error) { + this.logger.error({ + local: 'KafkaController.connect', + message: 'Failed to connect to Kafka', + error: error.message || error, + }); + this.scheduleReconnect(); + throw error; + } + } + + private async initGlobalConsumer(): Promise { + try { + const kafkaConfig = configService.get('KAFKA'); + + const consumerConfig: ConsumerConfig = { + groupId: kafkaConfig.CONSUMER_GROUP_ID || 'evolution-api-consumers', + sessionTimeout: 30000, + heartbeatInterval: 3000, + }; + + this.consumer = this.kafkaClient.consumer(consumerConfig); + await this.consumer.connect(); + + // Subscribe to global topics + const events = kafkaConfig.EVENTS; + if (events) { + const eventKeys = Object.keys(events).filter((event) => events[event]); + + for (const event of eventKeys) { + const topicName = this.getTopicName(event, true); + await this.consumer.subscribe({ topic: topicName }); + } + + // Start consuming messages + await this.consumer.run({ + eachMessage: async ({ topic, message }) => { + try { + const data = JSON.parse(message.value?.toString() || '{}'); + this.logger.debug(`Received message from topic ${topic}: ${JSON.stringify(data)}`); + + // Process the message here if needed + // This is where you can add custom message processing logic + } catch (error) { + this.logger.error(`Error processing message from topic ${topic}: ${error}`); + } + }, + }); + + this.logger.info('Global Kafka consumer initialized'); + } + } catch (error) { + this.logger.error(`Failed to initialize global Kafka consumer: ${error}`); + } + } + + private async createTopics(): Promise { + try { + const kafkaConfig = configService.get('KAFKA'); + const admin = this.kafkaClient.admin(); + await admin.connect(); + + const topics = []; + + // Create global topics if enabled + if (kafkaConfig.GLOBAL_ENABLED && kafkaConfig.EVENTS) { + const eventKeys = Object.keys(kafkaConfig.EVENTS).filter((event) => kafkaConfig.EVENTS[event]); + + for (const event of eventKeys) { + const topicName = this.getTopicName(event, true); + topics.push({ + topic: topicName, + numPartitions: kafkaConfig.NUM_PARTITIONS || 1, + replicationFactor: kafkaConfig.REPLICATION_FACTOR || 1, + }); + } + } + + if (topics.length > 0) { + await admin.createTopics({ + topics, + waitForLeaders: true, + }); + + this.logger.info(`Created ${topics.length} Kafka topics`); + } + + await admin.disconnect(); + } catch (error) { + this.logger.error(`Failed to create Kafka topics: ${error}`); + } + } + + private getTopicName(event: string, isGlobal: boolean = false, instanceName?: string): string { + const kafkaConfig = configService.get('KAFKA'); + const prefix = kafkaConfig.TOPIC_PREFIX || 'evolution'; + + if (isGlobal) { + return `${prefix}.global.${event.toLowerCase().replace(/_/g, '.')}`; + } else { + return `${prefix}.${instanceName}.${event.toLowerCase().replace(/_/g, '.')}`; + } + } + + private handleConnectionLoss(): void { + if (this.isReconnecting) { + return; + } + + this.cleanup(); + this.scheduleReconnect(); + } + + private scheduleReconnect(): void { + if (this.reconnectAttempts >= this.maxReconnectAttempts) { + this.logger.error( + `Maximum reconnect attempts (${this.maxReconnectAttempts}) reached. Stopping reconnection attempts.`, + ); + return; + } + + if (this.isReconnecting) { + return; + } + + this.isReconnecting = true; + this.reconnectAttempts++; + + const delay = this.reconnectDelay * Math.pow(2, Math.min(this.reconnectAttempts - 1, 5)); + + this.logger.info( + `Scheduling Kafka reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`, + ); + + setTimeout(async () => { + try { + this.logger.info( + `Attempting to reconnect to Kafka (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`, + ); + await this.connect(); + this.logger.info('Successfully reconnected to Kafka'); + } catch (error) { + this.logger.error({ + local: 'KafkaController.scheduleReconnect', + message: `Reconnection attempt ${this.reconnectAttempts} failed`, + error: error.message || error, + }); + this.isReconnecting = false; + this.scheduleReconnect(); + } + }, delay); + } + + private async ensureConnection(): Promise { + if (!this.producer) { + this.logger.warn('Kafka producer is not available, attempting to reconnect...'); + if (!this.isReconnecting) { + this.scheduleReconnect(); + } + return false; + } + return true; + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + integration, + extra, + }: EmitData): Promise { + if (integration && !integration.includes('kafka')) { + return; + } + + if (!this.status) { + return; + } + + if (!(await this.ensureConnection())) { + this.logger.warn(`Failed to emit event ${event} for instance ${instanceName}: No Kafka connection`); + return; + } + + const instanceKafka = await this.get(instanceName); + const kafkaLocal = instanceKafka?.events; + const kafkaGlobal = configService.get('KAFKA').GLOBAL_ENABLED; + const kafkaEvents = configService.get('KAFKA').EVENTS; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + const logEnabled = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + + const message = { + ...(extra ?? {}), + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + timestamp: Date.now(), + }; + + const messageValue = JSON.stringify(message); + + // Instance-specific events + if (instanceKafka?.enabled && this.producer && Array.isArray(kafkaLocal) && kafkaLocal.includes(we)) { + const topicName = this.getTopicName(event, false, instanceName); + + let retry = 0; + while (retry < 3) { + try { + await this.producer.send({ + topic: topicName, + messages: [ + { + key: instanceName, + value: messageValue, + headers: { + event, + instance: instanceName, + origin, + timestamp: dateTime, + }, + }, + ], + }); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-Kafka`, + ...message, + }; + this.logger.log(logData); + } + + break; + } catch (error) { + this.logger.error({ + local: 'KafkaController.emit', + message: `Error publishing local Kafka message (attempt ${retry + 1}/3)`, + error: error.message || error, + }); + retry++; + if (retry >= 3) { + this.handleConnectionLoss(); + } + } + } + } + + // Global events + if (kafkaGlobal && kafkaEvents[we] && this.producer) { + const topicName = this.getTopicName(event, true); + + let retry = 0; + while (retry < 3) { + try { + await this.producer.send({ + topic: topicName, + messages: [ + { + key: `${instanceName}-${event}`, + value: messageValue, + headers: { + event, + instance: instanceName, + origin, + timestamp: dateTime, + }, + }, + ], + }); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-Kafka-Global`, + ...message, + }; + this.logger.log(logData); + } + + break; + } catch (error) { + this.logger.error({ + local: 'KafkaController.emit', + message: `Error publishing global Kafka message (attempt ${retry + 1}/3)`, + error: error.message || error, + }); + retry++; + if (retry >= 3) { + this.handleConnectionLoss(); + } + } + } + } + } + + public async cleanup(): Promise { + try { + if (this.consumer) { + await this.consumer.disconnect(); + this.consumer = null; + } + if (this.producer) { + await this.producer.disconnect(); + this.producer = null; + } + this.kafkaClient = null; + } catch (error) { + this.logger.warn({ + local: 'KafkaController.cleanup', + message: 'Error during cleanup', + error: error.message || error, + }); + this.producer = null; + this.consumer = null; + this.kafkaClient = null; + } + } +} diff --git a/src/api/integrations/event/kafka/kafka.router.ts b/src/api/integrations/event/kafka/kafka.router.ts new file mode 100644 index 000000000..eb8465086 --- /dev/null +++ b/src/api/integrations/event/kafka/kafka.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class KafkaRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.kafka.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.kafka.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/kafka/kafka.schema.ts b/src/api/integrations/event/kafka/kafka.schema.ts new file mode 100644 index 000000000..3decb27e2 --- /dev/null +++ b/src/api/integrations/event/kafka/kafka.schema.ts @@ -0,0 +1,21 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +import { EventController } from '../event.controller'; + +export const kafkaSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + enabled: { type: 'boolean', enum: [true, false] }, + events: { + type: 'array', + minItems: 0, + items: { + type: 'string', + enum: EventController.events, + }, + }, + }, + required: ['enabled'], +}; diff --git a/src/api/integrations/event/nats/nats.controller.ts b/src/api/integrations/event/nats/nats.controller.ts new file mode 100644 index 000000000..1ff4fbae8 --- /dev/null +++ b/src/api/integrations/event/nats/nats.controller.ts @@ -0,0 +1,163 @@ +import { PrismaRepository } from '@api/repository/repository.service'; +import { WAMonitoringService } from '@api/services/monitor.service'; +import { configService, Log, Nats } from '@config/env.config'; +import { Logger } from '@config/logger.config'; +import { connect, NatsConnection, StringCodec } from 'nats'; + +import { EmitData, EventController, EventControllerInterface } from '../event.controller'; + +export class NatsController extends EventController implements EventControllerInterface { + public natsClient: NatsConnection | null = null; + private readonly logger = new Logger('NatsController'); + private readonly sc = StringCodec(); + + constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { + super(prismaRepository, waMonitor, configService.get('NATS')?.ENABLED, 'nats'); + } + + public async init(): Promise { + if (!this.status) { + return; + } + + try { + const uri = configService.get('NATS').URI; + + this.natsClient = await connect({ servers: uri }); + + this.logger.info('NATS initialized'); + + if (configService.get('NATS')?.GLOBAL_ENABLED) { + await this.initGlobalSubscriptions(); + } + } catch (error) { + this.logger.error('Failed to connect to NATS:'); + this.logger.error(error); + throw error; + } + } + + public async emit({ + instanceName, + origin, + event, + data, + serverUrl, + dateTime, + sender, + apiKey, + integration, + extra, + }: EmitData): Promise { + if (integration && !integration.includes('nats')) { + return; + } + + if (!this.status || !this.natsClient) { + return; + } + + const instanceNats = await this.get(instanceName); + const natsLocal = instanceNats?.events; + const natsGlobal = configService.get('NATS').GLOBAL_ENABLED; + const natsEvents = configService.get('NATS').EVENTS; + const prefixKey = configService.get('NATS').PREFIX_KEY; + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + const logEnabled = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + + const message = { + ...(extra ?? {}), + event, + instance: instanceName, + data, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + // Instância específica + if (instanceNats?.enabled) { + if (Array.isArray(natsLocal) && natsLocal.includes(we)) { + const subject = `${instanceName}.${event.toLowerCase()}`; + + try { + this.natsClient.publish(subject, this.sc.encode(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-NATS`, + ...message, + }; + this.logger.log(logData); + } + } catch (error) { + this.logger.error(`Failed to publish to NATS (instance): ${error}`); + } + } + } + + // Global + if (natsGlobal && natsEvents[we]) { + try { + const subject = prefixKey ? `${prefixKey}.${event.toLowerCase()}` : event.toLowerCase(); + + this.natsClient.publish(subject, this.sc.encode(JSON.stringify(message))); + + if (logEnabled) { + const logData = { + local: `${origin}.sendData-NATS-Global`, + ...message, + }; + this.logger.log(logData); + } + } catch (error) { + this.logger.error(`Failed to publish to NATS (global): ${error}`); + } + } + } + + private async initGlobalSubscriptions(): Promise { + this.logger.info('Initializing global subscriptions'); + + const events = configService.get('NATS').EVENTS; + const prefixKey = configService.get('NATS').PREFIX_KEY; + + if (!events) { + this.logger.warn('No events to initialize on NATS'); + return; + } + + const eventKeys = Object.keys(events); + + for (const event of eventKeys) { + if (events[event] === false) continue; + + const subject = prefixKey ? `${prefixKey}.${event.toLowerCase()}` : event.toLowerCase(); + + // Criar uma subscription para cada evento + try { + const subscription = this.natsClient.subscribe(subject); + this.logger.info(`Subscribed to: ${subject}`); + + // Processar mensagens (exemplo básico) + (async () => { + for await (const msg of subscription) { + try { + const data = JSON.parse(this.sc.decode(msg.data)); + // Aqui você pode adicionar a lógica de processamento + this.logger.debug(`Received message on ${subject}:`); + this.logger.debug(data); + } catch (error) { + this.logger.error(`Error processing message on ${subject}:`); + this.logger.error(error); + } + } + })(); + } catch (error) { + this.logger.error(`Failed to subscribe to ${subject}:`); + this.logger.error(error); + } + } + } +} diff --git a/src/api/integrations/event/nats/nats.router.ts b/src/api/integrations/event/nats/nats.router.ts new file mode 100644 index 000000000..945b75f3a --- /dev/null +++ b/src/api/integrations/event/nats/nats.router.ts @@ -0,0 +1,36 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { InstanceDto } from '@api/dto/instance.dto'; +import { EventDto } from '@api/integrations/event/event.dto'; +import { HttpStatus } from '@api/routes/index.router'; +import { eventManager } from '@api/server.module'; +import { eventSchema, instanceSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +export class NatsRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('set'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: eventSchema, + ClassRef: EventDto, + execute: (instance, data) => eventManager.nats.set(instance.instanceName, data), + }); + + res.status(HttpStatus.CREATED).json(response); + }) + .get(this.routerPath('find'), ...guards, async (req, res) => { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => eventManager.nats.get(instance.instanceName), + }); + + res.status(HttpStatus.OK).json(response); + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/integrations/event/pusher/pusher.controller.ts b/src/api/integrations/event/pusher/pusher.controller.ts index 3f3a74eeb..045f7cc4f 100644 --- a/src/api/integrations/event/pusher/pusher.controller.ts +++ b/src/api/integrations/event/pusher/pusher.controller.ts @@ -120,7 +120,12 @@ export class PusherController extends EventController implements EventController sender, apiKey, local, + integration, + extra, }: EmitData): Promise { + if (integration && !integration.includes('pusher')) { + return; + } if (!this.status) { return; } @@ -129,6 +134,7 @@ export class PusherController extends EventController implements EventController const enabledLog = configService.get('LOG').LEVEL.includes('WEBHOOKS'); const eventName = event.replace(/_/g, '.').toLowerCase(); const pusherData = { + ...(extra ?? {}), event, instance: instanceName, data, diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts index c4e0cc36b..b4625508b 100644 --- a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts @@ -8,7 +8,12 @@ import { EmitData, EventController, EventControllerInterface } from '../event.co export class RabbitmqController extends EventController implements EventControllerInterface { public amqpChannel: amqp.Channel | null = null; + private amqpConnection: amqp.Connection | null = null; private readonly logger = new Logger('RabbitmqController'); + private reconnectAttempts = 0; + private maxReconnectAttempts = 10; + private reconnectDelay = 5000; // 5 seconds + private isReconnecting = false; constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) { super(prismaRepository, waMonitor, configService.get('RABBITMQ')?.ENABLED, 'rabbitmq'); @@ -19,24 +24,79 @@ export class RabbitmqController extends EventController implements EventControll return; } - await new Promise((resolve, reject) => { + await this.connect(); + } + + private async connect(): Promise { + return new Promise((resolve, reject) => { const uri = configService.get('RABBITMQ').URI; + const frameMax = configService.get('RABBITMQ').FRAME_MAX; const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; - amqp.connect(uri, (error, connection) => { + const url = new URL(uri); + const connectionOptions = { + protocol: url.protocol.slice(0, -1), + hostname: url.hostname, + port: url.port || 5672, + username: url.username || 'guest', + password: url.password || 'guest', + vhost: url.pathname.slice(1) || '/', + frameMax: frameMax, + heartbeat: 30, // Add heartbeat of 30 seconds + }; + + amqp.connect(connectionOptions, (error: Error, connection: amqp.Connection) => { if (error) { + this.logger.error({ + local: 'RabbitmqController.connect', + message: 'Failed to connect to RabbitMQ', + error: error.message || error, + }); reject(error); - return; } - connection.createChannel((channelError, channel) => { + // Connection event handlers + connection.on('error', (err: Error) => { + this.logger.error({ + local: 'RabbitmqController.connectionError', + message: 'RabbitMQ connection error', + error: err.message || err, + }); + this.handleConnectionLoss(); + }); + + connection.on('close', () => { + this.logger.warn('RabbitMQ connection closed'); + this.handleConnectionLoss(); + }); + + connection.createChannel((channelError: Error, channel: amqp.Channel) => { if (channelError) { + this.logger.error({ + local: 'RabbitmqController.createChannel', + message: 'Failed to create RabbitMQ channel', + error: channelError.message || channelError, + }); reject(channelError); - return; } + // Channel event handlers + channel.on('error', (err: Error) => { + this.logger.error({ + local: 'RabbitmqController.channelError', + message: 'RabbitMQ channel error', + error: err.message || err, + }); + this.handleConnectionLoss(); + }); + + channel.on('close', () => { + this.logger.warn('RabbitMQ channel closed'); + this.handleConnectionLoss(); + }); + const exchangeName = rabbitmqExchangeName; channel.assertExchange(exchangeName, 'topic', { @@ -44,16 +104,80 @@ export class RabbitmqController extends EventController implements EventControll autoDelete: false, }); + this.amqpConnection = connection; this.amqpChannel = channel; + this.reconnectAttempts = 0; // Reset reconnect attempts on successful connection + this.isReconnecting = false; - this.logger.info('AMQP initialized'); + this.logger.info('AMQP initialized successfully'); resolve(); }); }); - }).then(() => { - if (configService.get('RABBITMQ')?.GLOBAL_ENABLED) this.initGlobalQueues(); - }); + }) + .then(() => { + if (configService.get('RABBITMQ')?.GLOBAL_ENABLED) { + this.initGlobalQueues(); + } + }) + .catch((error) => { + this.logger.error({ + local: 'RabbitmqController.init', + message: 'Failed to initialize AMQP', + error: error.message || error, + }); + this.scheduleReconnect(); + throw error; + }); + } + + private handleConnectionLoss(): void { + if (this.isReconnecting) { + return; // Already attempting to reconnect + } + + this.cleanup(); + this.scheduleReconnect(); + } + + private scheduleReconnect(): void { + if (this.reconnectAttempts >= this.maxReconnectAttempts) { + this.logger.error( + `Maximum reconnect attempts (${this.maxReconnectAttempts}) reached. Stopping reconnection attempts.`, + ); + return; + } + + if (this.isReconnecting) { + return; // Already scheduled + } + + this.isReconnecting = true; + this.reconnectAttempts++; + + const delay = this.reconnectDelay * Math.pow(2, Math.min(this.reconnectAttempts - 1, 5)); // Exponential backoff with max delay + + this.logger.info( + `Scheduling RabbitMQ reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms`, + ); + + setTimeout(async () => { + try { + this.logger.info( + `Attempting to reconnect to RabbitMQ (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`, + ); + await this.connect(); + this.logger.info('Successfully reconnected to RabbitMQ'); + } catch (error) { + this.logger.error({ + local: 'RabbitmqController.scheduleReconnect', + message: `Reconnection attempt ${this.reconnectAttempts} failed`, + error: error.message || error, + }); + this.isReconnecting = false; + this.scheduleReconnect(); + } + }, delay); } private set channel(channel: amqp.Channel) { @@ -64,6 +188,17 @@ export class RabbitmqController extends EventController implements EventControll return this.amqpChannel; } + private async ensureConnection(): Promise { + if (!this.amqpChannel) { + this.logger.warn('AMQP channel is not available, attempting to reconnect...'); + if (!this.isReconnecting) { + this.scheduleReconnect(); + } + return false; + } + return true; + } + public async emit({ instanceName, origin, @@ -73,20 +208,33 @@ export class RabbitmqController extends EventController implements EventControll dateTime, sender, apiKey, + integration, + extra, }: EmitData): Promise { + if (integration && !integration.includes('rabbitmq')) { + return; + } + if (!this.status) { return; } + if (!(await this.ensureConnection())) { + this.logger.warn(`Failed to emit event ${event} for instance ${instanceName}: No AMQP connection`); + return; + } + const instanceRabbitmq = await this.get(instanceName); const rabbitmqLocal = instanceRabbitmq?.events; const rabbitmqGlobal = configService.get('RABBITMQ').GLOBAL_ENABLED; const rabbitmqEvents = configService.get('RABBITMQ').EVENTS; + const prefixKey = configService.get('RABBITMQ').PREFIX_KEY; const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; const we = event.replace(/[.-]/gm, '_').toUpperCase(); const logEnabled = configService.get('LOG').LEVEL.includes('WEBHOOKS'); const message = { + ...(extra ?? {}), event, instance: instanceName, data, @@ -136,7 +284,15 @@ export class RabbitmqController extends EventController implements EventControll break; } catch (error) { + this.logger.error({ + local: 'RabbitmqController.emit', + message: `Error publishing local RabbitMQ message (attempt ${retry + 1}/3)`, + error: error.message || error, + }); retry++; + if (retry >= 3) { + this.handleConnectionLoss(); + } } } } @@ -154,7 +310,9 @@ export class RabbitmqController extends EventController implements EventControll autoDelete: false, }); - const queueName = event; + const queueName = prefixKey + ? `${prefixKey}.${event.replace(/_/g, '.').toLowerCase()}` + : event.replace(/_/g, '.').toLowerCase(); await this.amqpChannel.assertQueue(queueName, { durable: true, @@ -179,7 +337,15 @@ export class RabbitmqController extends EventController implements EventControll break; } catch (error) { + this.logger.error({ + local: 'RabbitmqController.emit', + message: `Error publishing global RabbitMQ message (attempt ${retry + 1}/3)`, + error: error.message || error, + }); retry++; + if (retry >= 3) { + this.handleConnectionLoss(); + } } } } @@ -188,37 +354,78 @@ export class RabbitmqController extends EventController implements EventControll private async initGlobalQueues(): Promise { this.logger.info('Initializing global queues'); + if (!(await this.ensureConnection())) { + this.logger.error('Cannot initialize global queues: No AMQP connection'); + return; + } + const rabbitmqExchangeName = configService.get('RABBITMQ').EXCHANGE_NAME; const events = configService.get('RABBITMQ').EVENTS; + const prefixKey = configService.get('RABBITMQ').PREFIX_KEY; if (!events) { this.logger.warn('No events to initialize on AMQP'); - return; } const eventKeys = Object.keys(events); - eventKeys.forEach((event) => { - if (events[event] === false) return; + for (const event of eventKeys) { + if (events[event] === false) continue; - const queueName = `${event.replace(/_/g, '.').toLowerCase()}`; - const exchangeName = rabbitmqExchangeName; + try { + const queueName = + prefixKey !== '' + ? `${prefixKey}.${event.replace(/_/g, '.').toLowerCase()}` + : `${event.replace(/_/g, '.').toLowerCase()}`; + const exchangeName = rabbitmqExchangeName; - this.amqpChannel.assertExchange(exchangeName, 'topic', { - durable: true, - autoDelete: false, - }); + await this.amqpChannel.assertExchange(exchangeName, 'topic', { + durable: true, + autoDelete: false, + }); - this.amqpChannel.assertQueue(queueName, { - durable: true, - autoDelete: false, - arguments: { - 'x-queue-type': 'quorum', - }, - }); + await this.amqpChannel.assertQueue(queueName, { + durable: true, + autoDelete: false, + arguments: { + 'x-queue-type': 'quorum', + }, + }); + + await this.amqpChannel.bindQueue(queueName, exchangeName, event); + + this.logger.info(`Global queue initialized: ${queueName}`); + } catch (error) { + this.logger.error({ + local: 'RabbitmqController.initGlobalQueues', + message: `Failed to initialize global queue for event ${event}`, + error: error.message || error, + }); + this.handleConnectionLoss(); + break; + } + } + } - this.amqpChannel.bindQueue(queueName, exchangeName, event); - }); + public async cleanup(): Promise { + try { + if (this.amqpChannel) { + await this.amqpChannel.close(); + this.amqpChannel = null; + } + if (this.amqpConnection) { + await this.amqpConnection.close(); + this.amqpConnection = null; + } + } catch (error) { + this.logger.warn({ + local: 'RabbitmqController.cleanup', + message: 'Error during cleanup', + error: error.message || error, + }); + this.amqpChannel = null; + this.amqpConnection = null; + } } } diff --git a/src/api/integrations/event/sqs/sqs.controller.ts b/src/api/integrations/event/sqs/sqs.controller.ts index 3c94fe810..2b0398ef2 100644 --- a/src/api/integrations/event/sqs/sqs.controller.ts +++ b/src/api/integrations/event/sqs/sqs.controller.ts @@ -1,10 +1,12 @@ +import * as s3Service from '@api/integrations/storage/s3/libs/minio.server'; import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; -import { SQS } from '@aws-sdk/client-sqs'; -import { configService, Log, Sqs } from '@config/env.config'; +import { CreateQueueCommand, DeleteQueueCommand, ListQueuesCommand, SQS } from '@aws-sdk/client-sqs'; +import { configService, HttpServer, Log, S3, Sqs } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; +import { EventDto } from '../event.dto'; export class SqsController extends EventController implements EventControllerInterface { private sqs: SQS; @@ -14,27 +16,29 @@ export class SqsController extends EventController implements EventControllerInt super(prismaRepository, waMonitor, configService.get('SQS')?.ENABLED, 'sqs'); } - public init(): void { + public async init(): Promise { if (!this.status) { return; } - new Promise((resolve) => { - const awsConfig = configService.get('SQS'); + const awsConfig = configService.get('SQS'); - this.sqs = new SQS({ - credentials: { - accessKeyId: awsConfig.ACCESS_KEY_ID, - secretAccessKey: awsConfig.SECRET_ACCESS_KEY, - }, + this.sqs = new SQS({ + credentials: { + accessKeyId: awsConfig.ACCESS_KEY_ID, + secretAccessKey: awsConfig.SECRET_ACCESS_KEY, + }, - region: awsConfig.REGION, - }); + region: awsConfig.REGION, + }); - this.logger.info('SQS initialized'); + this.logger.info('SQS initialized'); - resolve(); - }); + const sqsConfig = configService.get('SQS'); + if (this.sqs && sqsConfig.GLOBAL_ENABLED) { + const sqsEvents = Object.keys(sqsConfig.EVENTS).filter((e) => sqsConfig.EVENTS[e]); + await this.saveQueues(sqsConfig.GLOBAL_PREFIX_NAME, sqsEvents, true); + } } private set channel(sqs: SQS) { @@ -45,6 +49,40 @@ export class SqsController extends EventController implements EventControllerInt return this.sqs; } + override async set(instanceName: string, data: EventDto): Promise { + if (!this.status || configService.get('SQS').GLOBAL_ENABLED) { + return; + } + + if (!data[this.name]?.enabled) { + data[this.name].events = []; + } else { + if (0 === data[this.name].events.length) { + data[this.name].events = EventController.events; + } + } + + await this.saveQueues(instanceName, data[this.name].events, data[this.name]?.enabled); + + const payload: any = { + where: { + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + update: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + }, + create: { + enabled: data[this.name]?.enabled, + events: data[this.name].events, + instanceId: this.monitor.waInstances[instanceName].instanceId, + }, + }; + + console.log('*** payload: ', payload); + return this.prisma[this.name].upsert(payload); + } + public async emit({ instanceName, origin, @@ -54,132 +92,214 @@ export class SqsController extends EventController implements EventControllerInt dateTime, sender, apiKey, + integration, + extra, }: EmitData): Promise { + if (integration && !integration.includes('sqs')) { + return; + } + if (!this.status) { return; } - const instanceSqs = await this.get(instanceName); - const sqsLocal = instanceSqs?.events; - const we = event.replace(/[.-]/gm, '_').toUpperCase(); - - if (instanceSqs?.enabled) { - if (this.sqs) { - if (Array.isArray(sqsLocal) && sqsLocal.includes(we)) { - const eventFormatted = `${event.replace('.', '_').toLowerCase()}`; - const queueName = `${instanceName}_${eventFormatted}.fifo`; - const sqsConfig = configService.get('SQS'); - const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`; - - const message = { - event, - instance: instanceName, - data, - server_url: serverUrl, - date_time: dateTime, - sender, - apikey: apiKey, - }; - - const params = { - MessageBody: JSON.stringify(message), - MessageGroupId: 'evolution', - MessageDeduplicationId: `${instanceName}_${eventFormatted}_${Date.now()}`, - QueueUrl: sqsUrl, - }; - - this.sqs.sendMessage(params, (err) => { - if (err) { - this.logger.error({ - local: `${origin}.sendData-SQS`, - message: err?.message, - hostName: err?.hostname, - code: err?.code, - stack: err?.stack, - name: err?.name, - url: queueName, - server_url: serverUrl, - }); - } else { - if (configService.get('LOG').LEVEL.includes('WEBHOOKS')) { - const logData = { - local: `${origin}.sendData-SQS`, - ...message, - }; - - this.logger.log(logData); - } - } + if (this.sqs) { + const serverConfig = configService.get('SERVER'); + const sqsConfig = configService.get('SQS'); + + const we = event.replace(/[.-]/gm, '_').toUpperCase(); + + let sqsEvents = []; + if (sqsConfig.GLOBAL_ENABLED) { + sqsEvents = Object.keys(sqsConfig.EVENTS).filter((e) => sqsConfig.EVENTS[e]); + } else { + const instanceSqs = await this.get(instanceName); + if (instanceSqs?.enabled && Array.isArray(instanceSqs?.events)) { + sqsEvents = instanceSqs?.events; + } + } + + if (Array.isArray(sqsEvents) && sqsEvents.includes(we)) { + const prefixName = sqsConfig.GLOBAL_ENABLED ? sqsConfig.GLOBAL_PREFIX_NAME : instanceName; + const eventFormatted = + sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE + ? 'singlequeue' + : `${event.replace('.', '_').toLowerCase()}`; + const queueName = `${prefixName}_${eventFormatted}.fifo`; + const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`; + + const message = { + ...(extra ?? {}), + event, + instance: instanceName, + dataType: 'json', + data, + server: serverConfig.NAME, + server_url: serverUrl, + date_time: dateTime, + sender, + apikey: apiKey, + }; + + const jsonStr = JSON.stringify(message); + const size = Buffer.byteLength(jsonStr, 'utf8'); + if (size > sqsConfig.MAX_PAYLOAD_SIZE) { + if (!configService.get('S3').ENABLE) { + this.logger.error( + `${instanceName} - ${eventFormatted} - SQS ignored: payload (${size} bytes) exceeds SQS size limit (${sqsConfig.MAX_PAYLOAD_SIZE} bytes) and S3 storage is not enabled.`, + ); + return; + } + + const buffer = Buffer.from(jsonStr, 'utf8'); + const fullName = `messages/${instanceName}_${eventFormatted}_${Date.now()}.json`; + + await s3Service.uploadFile(fullName, buffer, size, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', }); + + const fileUrl = await s3Service.getObjectUrl(fullName); + + message.data = { fileUrl }; + message.dataType = 's3'; } + + const messageGroupId = sqsConfig.GLOBAL_ENABLED + ? `${serverConfig.NAME}-${eventFormatted}-${instanceName}` + : 'evolution'; + const isGlobalEnabled = sqsConfig.GLOBAL_ENABLED; + const params = { + MessageBody: JSON.stringify(message), + MessageGroupId: messageGroupId, + QueueUrl: sqsUrl, + ...(!isGlobalEnabled && { + MessageDeduplicationId: `${instanceName}_${eventFormatted}_${Date.now()}`, + }), + }; + + this.sqs.sendMessage(params, (err) => { + if (err) { + this.logger.error({ + local: `${origin}.sendData-SQS`, + params: JSON.stringify(message), + sqsUrl: sqsUrl, + message: err?.message, + hostName: err?.hostname, + code: err?.code, + stack: err?.stack, + name: err?.name, + url: queueName, + server_url: serverUrl, + }); + } else if (configService.get('LOG').LEVEL.includes('WEBHOOKS')) { + const logData = { + local: `${origin}.sendData-SQS`, + ...message, + }; + + this.logger.log(logData); + } + }); } } } - public async initQueues(instanceName: string, events: string[]) { - if (!events || !events.length) return; + private async saveQueues(prefixName: string, events: string[], enable: boolean) { + if (enable) { + const sqsConfig = configService.get('SQS'); + const eventsFinded = await this.listQueues(prefixName); + console.log('eventsFinded', eventsFinded); - const queues = events.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); + for (const event of events) { + const normalizedEvent = + sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE ? 'singlequeue' : event.toLowerCase(); + if (eventsFinded.includes(normalizedEvent)) { + this.logger.info(`A queue para o evento "${normalizedEvent}" já existe. Ignorando criação.`); + continue; + } - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; - - this.sqs.createQueue( - { - QueueName: queueName, - Attributes: { - FifoQueue: 'true', - }, - }, - (err, data) => { - if (err) { - this.logger.error(`Error creating queue ${queueName}: ${err.message}`); - } else { - this.logger.info(`Queue ${queueName} created: ${data.QueueUrl}`); - } - }, - ); - }); + const queueName = `${prefixName}_${normalizedEvent}.fifo`; + try { + const isGlobalEnabled = sqsConfig.GLOBAL_ENABLED; + const createCommand = new CreateQueueCommand({ + QueueName: queueName, + Attributes: { + FifoQueue: 'true', + ...(isGlobalEnabled && { ContentBasedDeduplication: 'true' }), + }, + }); + + const data = await this.sqs.send(createCommand); + this.logger.info(`Queue ${queueName} criada: ${data.QueueUrl}`); + } catch (err: any) { + this.logger.error(`Erro ao criar queue ${queueName}: ${err.message}`); + } + + if (sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE) { + break; + } + } + } } - public async removeQueues(instanceName: string, events: any) { - const eventsArray = Array.isArray(events) ? events.map((event) => String(event)) : []; - if (!events || !eventsArray.length) return; + private async listQueues(prefixName: string) { + let existingQueues: string[] = []; - const queues = eventsArray.map((event) => { - return `${event.replace(/_/g, '_').toLowerCase()}`; - }); + try { + const listCommand = new ListQueuesCommand({ + QueueNamePrefix: `${prefixName}_`, + }); - queues.forEach((event) => { - const queueName = `${instanceName}_${event}.fifo`; + const listData = await this.sqs.send(listCommand); + if (listData.QueueUrls && listData.QueueUrls.length > 0) { + // Extrai o nome da fila a partir da URL + existingQueues = listData.QueueUrls.map((queueUrl) => { + const parts = queueUrl.split('/'); + return parts[parts.length - 1]; + }); + } + } catch (error: any) { + this.logger.error(`Erro ao listar filas para ${prefixName}: ${error.message}`); + return; + } - this.sqs.getQueueUrl( - { - QueueName: queueName, - }, - (err, data) => { - if (err) { - this.logger.error(`Error getting queue URL for ${queueName}: ${err.message}`); - } else { - const queueUrl = data.QueueUrl; - - this.sqs.deleteQueue( - { - QueueUrl: queueUrl, - }, - (deleteErr) => { - if (deleteErr) { - this.logger.error(`Error deleting queue ${queueName}: ${deleteErr.message}`); - } else { - this.logger.info(`Queue ${queueName} deleted`); - } - }, - ); - } - }, - ); - }); + // Mapeia os eventos já existentes nas filas: remove o prefixo e o sufixo ".fifo" + return existingQueues + .map((queueName) => { + // Espera-se que o nome seja `${instanceName}_${event}.fifo` + if (queueName.startsWith(`${prefixName}_`) && queueName.endsWith('.fifo')) { + return queueName.substring(prefixName.length + 1, queueName.length - 5).toLowerCase(); + } + return ''; + }) + .filter((event) => event !== ''); + } + + // Para uma futura feature de exclusão forçada das queues + private async removeQueuesByInstance(prefixName: string) { + try { + const listCommand = new ListQueuesCommand({ + QueueNamePrefix: `${prefixName}_`, + }); + const listData = await this.sqs.send(listCommand); + + if (!listData.QueueUrls || listData.QueueUrls.length === 0) { + this.logger.info(`No queues found for ${prefixName}`); + return; + } + + for (const queueUrl of listData.QueueUrls) { + try { + const deleteCommand = new DeleteQueueCommand({ QueueUrl: queueUrl }); + await this.sqs.send(deleteCommand); + this.logger.info(`Queue ${queueUrl} deleted`); + } catch (err: any) { + this.logger.error(`Error deleting queue ${queueUrl}: ${err.message}`); + } + } + } catch (err: any) { + this.logger.error(`Error listing queues for ${prefixName}: ${err.message}`); + } } } diff --git a/src/api/integrations/event/webhook/webhook.controller.ts b/src/api/integrations/event/webhook/webhook.controller.ts index 2fcf6c44d..7f1dd8dc0 100644 --- a/src/api/integrations/event/webhook/webhook.controller.ts +++ b/src/api/integrations/event/webhook/webhook.controller.ts @@ -4,9 +4,9 @@ import { WAMonitoringService } from '@api/services/monitor.service'; import { wa } from '@api/types/wa.types'; import { configService, Log, Webhook } from '@config/env.config'; import { Logger } from '@config/logger.config'; -import { BadRequestException } from '@exceptions'; -import axios from 'axios'; -import { isURL } from 'class-validator'; +// import { BadRequestException } from '@exceptions'; +import axios, { AxiosInstance } from 'axios'; +import * as jwt from 'jsonwebtoken'; import { EmitData, EventController, EventControllerInterface } from '../event.controller'; @@ -18,9 +18,9 @@ export class WebhookController extends EventController implements EventControlle } override async set(instanceName: string, data: EventDto): Promise { - if (!isURL(data.webhook.url, { require_tld: false })) { - throw new BadRequestException('Invalid "url" property'); - } + // if (!/^(https?:\/\/)/.test(data.webhook.url)) { + // throw new BadRequestException('Invalid "url" property'); + // } if (!data.webhook?.enabled) { data.webhook.events = []; @@ -64,32 +64,45 @@ export class WebhookController extends EventController implements EventControlle sender, apiKey, local, + integration, + extra, }: EmitData): Promise { - const instance = (await this.get(instanceName)) as wa.LocalWebHook; - - if (!instance || !instance?.enabled) { + if (integration && !integration.includes('webhook')) { return; } + const instance = (await this.get(instanceName)) as wa.LocalWebHook; + const webhookConfig = configService.get('WEBHOOK'); const webhookLocal = instance?.events; - const webhookHeaders = instance?.headers; + const webhookHeaders = { ...((instance?.headers as Record) || {}) }; + + if (webhookHeaders && 'jwt_key' in webhookHeaders) { + const jwtKey = webhookHeaders['jwt_key']; + const jwtToken = this.generateJwtToken(jwtKey); + webhookHeaders['Authorization'] = `Bearer ${jwtToken}`; + + delete webhookHeaders['jwt_key']; + } + const we = event.replace(/[.-]/gm, '_').toUpperCase(); const transformedWe = we.replace(/_/gm, '-').toLowerCase(); const enabledLog = configService.get('LOG').LEVEL.includes('WEBHOOKS'); + const regex = /^(https?:\/\/)/; const webhookData = { + ...(extra ?? {}), event, instance: instanceName, data, - destination: instance?.url, + destination: instance?.url || `${webhookConfig.GLOBAL.URL}/${transformedWe}`, date_time: dateTime, sender, server_url: serverUrl, apikey: apiKey, }; - if (local) { + if (local && instance?.enabled) { if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) { let baseURL: string; @@ -110,18 +123,19 @@ export class WebhookController extends EventController implements EventControlle } try { - if (instance?.enabled && isURL(instance.url, { require_tld: false })) { + if (instance?.enabled && regex.test(instance.url)) { const httpService = axios.create({ baseURL, headers: webhookHeaders as Record | undefined, + timeout: webhookConfig.REQUEST?.TIMEOUT_MS ?? 30000, }); - await httpService.post('', webhookData); + await this.retryWebhookRequest(httpService, webhookData, `${origin}.sendData-Webhook`, baseURL, serverUrl); } } catch (error) { this.logger.error({ local: `${origin}.sendData-Webhook`, - message: error?.message, + message: `Todas as tentativas falharam: ${error?.message}`, hostName: error?.hostname, syscall: error?.syscall, code: error?.code, @@ -154,15 +168,24 @@ export class WebhookController extends EventController implements EventControlle } try { - if (isURL(globalURL)) { - const httpService = axios.create({ baseURL: globalURL }); + if (regex.test(globalURL)) { + const httpService = axios.create({ + baseURL: globalURL, + timeout: webhookConfig.REQUEST?.TIMEOUT_MS ?? 30000, + }); - await httpService.post('', webhookData); + await this.retryWebhookRequest( + httpService, + webhookData, + `${origin}.sendData-Webhook-Global`, + globalURL, + serverUrl, + ); } } catch (error) { this.logger.error({ local: `${origin}.sendData-Webhook-Global`, - message: error?.message, + message: `Todas as tentativas falharam: ${error?.message}`, hostName: error?.hostname, syscall: error?.syscall, code: error?.code, @@ -176,4 +199,108 @@ export class WebhookController extends EventController implements EventControlle } } } + + private async retryWebhookRequest( + httpService: AxiosInstance, + webhookData: any, + origin: string, + baseURL: string, + serverUrl: string, + maxRetries?: number, + delaySeconds?: number, + ): Promise { + const webhookConfig = configService.get('WEBHOOK'); + const maxRetryAttempts = maxRetries ?? webhookConfig.RETRY?.MAX_ATTEMPTS ?? 10; + const initialDelay = delaySeconds ?? webhookConfig.RETRY?.INITIAL_DELAY_SECONDS ?? 5; + const useExponentialBackoff = webhookConfig.RETRY?.USE_EXPONENTIAL_BACKOFF ?? true; + const maxDelay = webhookConfig.RETRY?.MAX_DELAY_SECONDS ?? 300; + const jitterFactor = webhookConfig.RETRY?.JITTER_FACTOR ?? 0.2; + const nonRetryableStatusCodes = webhookConfig.RETRY?.NON_RETRYABLE_STATUS_CODES ?? [400, 401, 403, 404, 422]; + + let attempts = 0; + + while (attempts < maxRetryAttempts) { + try { + await httpService.post('', webhookData); + if (attempts > 0) { + this.logger.log({ + local: `${origin}`, + message: `Sucesso no envio após ${attempts + 1} tentativas`, + url: baseURL, + }); + } + return; + } catch (error) { + attempts++; + + const isTimeout = error.code === 'ECONNABORTED'; + + if (error?.response?.status && nonRetryableStatusCodes.includes(error.response.status)) { + this.logger.error({ + local: `${origin}`, + message: `Erro não recuperável (${error.response.status}): ${error?.message}. Cancelando retentativas.`, + statusCode: error?.response?.status, + url: baseURL, + server_url: serverUrl, + }); + throw error; + } + + this.logger.error({ + local: `${origin}`, + message: `Tentativa ${attempts}/${maxRetryAttempts} falhou: ${isTimeout ? 'Timeout da requisição' : error?.message}`, + hostName: error?.hostname, + syscall: error?.syscall, + code: error?.code, + isTimeout, + statusCode: error?.response?.status, + error: error?.errno, + stack: error?.stack, + name: error?.name, + url: baseURL, + server_url: serverUrl, + }); + + if (attempts === maxRetryAttempts) { + throw error; + } + + let nextDelay = initialDelay; + if (useExponentialBackoff) { + nextDelay = Math.min(initialDelay * Math.pow(2, attempts - 1), maxDelay); + + const jitter = nextDelay * jitterFactor * (Math.random() * 2 - 1); + nextDelay = Math.max(initialDelay, nextDelay + jitter); + } + + this.logger.log({ + local: `${origin}`, + message: `Aguardando ${nextDelay.toFixed(1)} segundos antes da próxima tentativa`, + url: baseURL, + }); + + await new Promise((resolve) => setTimeout(resolve, nextDelay * 1000)); + } + } + } + + private generateJwtToken(authToken: string): string { + try { + const payload = { + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + 600, // 10 min expiration + app: 'evolution', + action: 'webhook', + }; + + const token = jwt.sign(payload, authToken, { algorithm: 'HS256' }); + return token; + } catch (error) { + this.logger.error({ + local: 'WebhookController.generateJwtToken', + message: `JWT generation failed: ${error?.message}`, + }); + throw error; + } + } } diff --git a/src/api/integrations/event/webhook/webhook.router.ts b/src/api/integrations/event/webhook/webhook.router.ts index 5193bec58..149f940b3 100644 --- a/src/api/integrations/event/webhook/webhook.router.ts +++ b/src/api/integrations/event/webhook/webhook.router.ts @@ -8,7 +8,10 @@ import { instanceSchema, webhookSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; export class WebhookRouter extends RouterBroker { - constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { + constructor( + readonly configService: ConfigService, + ...guards: RequestHandler[] + ) { super(); this.router .post(this.routerPath('set'), ...guards, async (req, res) => { diff --git a/src/api/integrations/event/websocket/websocket.controller.ts b/src/api/integrations/event/websocket/websocket.controller.ts index e7dab1df3..3c763f08d 100644 --- a/src/api/integrations/event/websocket/websocket.controller.ts +++ b/src/api/integrations/event/websocket/websocket.controller.ts @@ -1,6 +1,6 @@ import { PrismaRepository } from '@api/repository/repository.service'; import { WAMonitoringService } from '@api/services/monitor.service'; -import { configService, Cors, Log, Websocket } from '@config/env.config'; +import { Auth, configService, Cors, Log, Websocket } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { Server } from 'http'; import { Server as SocketIO } from 'socket.io'; @@ -24,8 +24,50 @@ export class WebsocketController extends EventController implements EventControl } this.socket = new SocketIO(httpServer, { - cors: { - origin: this.cors, + cors: { origin: this.cors }, + allowRequest: async (req, callback) => { + try { + const url = new URL(req.url || '', 'http://localhost'); + const params = new URLSearchParams(url.search); + + const { remoteAddress } = req.socket; + const websocketConfig = configService.get('WEBSOCKET'); + const allowedHosts = websocketConfig.ALLOWED_HOSTS || '127.0.0.1,::1,::ffff:127.0.0.1'; + const allowAllHosts = allowedHosts.trim() === '*'; + const isAllowedHost = + allowAllHosts || + allowedHosts + .split(',') + .map((h) => h.trim()) + .includes(remoteAddress); + + if (params.has('EIO') && isAllowedHost) { + return callback(null, true); + } + + const apiKey = params.get('apikey') || (req.headers.apikey as string); + + if (!apiKey) { + this.logger.error('Connection rejected: apiKey not provided'); + return callback('apiKey is required', false); + } + + const instance = await this.prismaRepository.instance.findFirst({ where: { token: apiKey } }); + + if (!instance) { + const globalToken = configService.get('AUTHENTICATION').API_KEY.KEY; + if (apiKey !== globalToken) { + this.logger.error('Connection rejected: invalid global token'); + return callback('Invalid global token', false); + } + } + + callback(null, true); + } catch (error) { + this.logger.error('Authentication error:'); + this.logger.error(error); + callback('Authentication error', false); + } }, }); @@ -35,6 +77,16 @@ export class WebsocketController extends EventController implements EventControl socket.on('disconnect', () => { this.logger.info('User disconnected'); }); + + socket.on('sendNode', async (data) => { + try { + await this.waMonitor.waInstances[data.instanceId].baileysSendNode(data.stanza); + this.logger.info('Node sent successfully'); + } catch (error) { + this.logger.error('Error sending node:'); + this.logger.error(error); + } + }); }); this.logger.info('Socket.io initialized'); @@ -65,7 +117,13 @@ export class WebsocketController extends EventController implements EventControl dateTime, sender, apiKey, + integration, + extra, }: EmitData): Promise { + if (integration && !integration.includes('websocket')) { + return; + } + if (!this.status) { return; } @@ -73,6 +131,7 @@ export class WebsocketController extends EventController implements EventControl const configEv = event.replace(/[.-]/gm, '_').toUpperCase(); const logEnabled = configService.get('LOG').LEVEL.includes('WEBSOCKET'); const message = { + ...(extra ?? {}), event, instance: instanceName, data, @@ -86,10 +145,7 @@ export class WebsocketController extends EventController implements EventControl this.socket.emit(event, message); if (logEnabled) { - this.logger.log({ - local: `${origin}.sendData-WebsocketGlobal`, - ...message, - }); + this.logger.log({ local: `${origin}.sendData-WebsocketGlobal`, ...message }); } } @@ -104,10 +160,7 @@ export class WebsocketController extends EventController implements EventControl this.socket.of(`/${instanceName}`).emit(event, message); if (logEnabled) { - this.logger.log({ - local: `${origin}.sendData-Websocket`, - ...message, - }); + this.logger.log({ local: `${origin}.sendData-Websocket`, ...message }); } } } catch (err) { diff --git a/src/api/integrations/storage/s3/libs/minio.server.ts b/src/api/integrations/storage/s3/libs/minio.server.ts index 5a66305c1..47145a4cb 100644 --- a/src/api/integrations/storage/s3/libs/minio.server.ts +++ b/src/api/integrations/storage/s3/libs/minio.server.ts @@ -26,14 +26,14 @@ const minioClient = (() => { } })(); -const bucketName = process.env.S3_BUCKET; +const bucketName = BUCKET.BUCKET_NAME; const bucketExists = async () => { if (minioClient) { try { const list = await minioClient.listBuckets(); return list.find((bucket) => bucket.name === bucketName); - } catch (error) { + } catch { return false; } } @@ -63,9 +63,9 @@ const createBucket = async () => { if (!exists) { await minioClient.makeBucket(bucketName); } - - await setBucketPolicy(); - + if (!BUCKET.SKIP_POLICY) { + await setBucketPolicy(); + } logger.info(`S3 Bucket ${bucketName} - ON`); return true; } catch (error) { diff --git a/src/api/provider/sessions.ts b/src/api/provider/sessions.ts index 05668232a..e211ecdcf 100644 --- a/src/api/provider/sessions.ts +++ b/src/api/provider/sessions.ts @@ -1,7 +1,7 @@ import { Auth, ConfigService, ProviderSession } from '@config/env.config'; import { Logger } from '@config/logger.config'; import axios from 'axios'; -import { execSync } from 'child_process'; +import { execFileSync } from 'child_process'; type ResponseSuccess = { status: number; data?: any }; type ResponseProvider = Promise<[ResponseSuccess?, Error?]>; @@ -36,7 +36,7 @@ export class ProviderFiles { } catch (error) { this.logger.error(['Failed to connect to the file server', error?.message, error?.stack]); const pid = process.pid; - execSync(`kill -9 ${pid}`); + execFileSync('kill', ['-9', `${pid}`]); } } } diff --git a/src/api/routes/business.router.ts b/src/api/routes/business.router.ts new file mode 100644 index 000000000..faca7b33f --- /dev/null +++ b/src/api/routes/business.router.ts @@ -0,0 +1,56 @@ +import { RouterBroker } from '@api/abstract/abstract.router'; +import { NumberDto } from '@api/dto/chat.dto'; +import { businessController } from '@api/server.module'; +import { createMetaErrorResponse } from '@utils/errorResponse'; +import { catalogSchema, collectionsSchema } from '@validate/validate.schema'; +import { RequestHandler, Router } from 'express'; + +import { HttpStatus } from './index.router'; + +export class BusinessRouter extends RouterBroker { + constructor(...guards: RequestHandler[]) { + super(); + this.router + .post(this.routerPath('getCatalog'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: catalogSchema, + ClassRef: NumberDto, + execute: (instance, data) => businessController.fetchCatalog(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + } catch (error) { + // Log error for debugging + console.error('Business catalog error:', error); + + // Use utility function to create standardized error response + const errorResponse = createMetaErrorResponse(error, 'business_catalog'); + return res.status(errorResponse.status).json(errorResponse); + } + }) + + .post(this.routerPath('getCollections'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: collectionsSchema, + ClassRef: NumberDto, + execute: (instance, data) => businessController.fetchCollections(instance, data), + }); + + return res.status(HttpStatus.OK).json(response); + } catch (error) { + // Log error for debugging + console.error('Business collections error:', error); + + // Use utility function to create standardized error response + const errorResponse = createMetaErrorResponse(error, 'business_collections'); + return res.status(errorResponse.status).json(errorResponse); + } + }); + } + + public readonly router: Router = Router(); +} diff --git a/src/api/routes/chat.router.ts b/src/api/routes/chat.router.ts index 20126c1a5..158947ed2 100644 --- a/src/api/routes/chat.router.ts +++ b/src/api/routes/chat.router.ts @@ -46,14 +46,19 @@ export class ChatRouter extends RouterBroker { super(); this.router .post(this.routerPath('whatsappNumbers'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: whatsappNumberSchema, - ClassRef: WhatsAppNumberDto, - execute: (instance, data) => chatController.whatsappNumber(instance, data), - }); + try { + const response = await this.dataValidate({ + request: req, + schema: whatsappNumberSchema, + ClassRef: WhatsAppNumberDto, + execute: (instance, data) => chatController.whatsappNumber(instance, data), + }); - return res.status(HttpStatus.OK).json(response); + return res.status(HttpStatus.OK).json(response); + } catch (error) { + console.log(error); + return res.status(HttpStatus.BAD_REQUEST).json(error); + } }) .post(this.routerPath('markMessageAsRead'), ...guards, async (req, res) => { const response = await this.dataValidate({ @@ -186,6 +191,16 @@ export class ChatRouter extends RouterBroker { return res.status(HttpStatus.OK).json(response); }) + .get(this.routerPath('findChatByRemoteJid'), ...guards, async (req, res) => { + const instance = req.params as unknown as InstanceDto; + const { remoteJid } = req.query as unknown as { remoteJid: string }; + if (!remoteJid) { + return res.status(HttpStatus.BAD_REQUEST).json({ error: 'remoteJid is a required query parameter' }); + } + const response = await chatController.findChatByRemoteJid(instance, remoteJid); + + return res.status(HttpStatus.OK).json(response); + }) // Profile routes .post(this.routerPath('fetchBusinessProfile'), ...guards, async (req, res) => { const response = await this.dataValidate({ @@ -207,7 +222,6 @@ export class ChatRouter extends RouterBroker { return res.status(HttpStatus.OK).json(response); }) - .post(this.routerPath('updateProfileName'), ...guards, async (req, res) => { const response = await this.dataValidate({ request: req, diff --git a/src/api/routes/index.router.ts b/src/api/routes/index.router.ts index 5587f7b6e..45c43fca5 100644 --- a/src/api/routes/index.router.ts +++ b/src/api/routes/index.router.ts @@ -5,12 +5,15 @@ import { ChannelRouter } from '@api/integrations/channel/channel.router'; import { ChatbotRouter } from '@api/integrations/chatbot/chatbot.router'; import { EventRouter } from '@api/integrations/event/event.router'; import { StorageRouter } from '@api/integrations/storage/storage.router'; -import { configService } from '@config/env.config'; -import { Router } from 'express'; +import { waMonitor } from '@api/server.module'; +import { configService, Database, Facebook } from '@config/env.config'; +import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion'; +import { NextFunction, Request, Response, Router } from 'express'; import fs from 'fs'; -import mime from 'mime'; +import mimeTypes from 'mime-types'; import path from 'path'; +import { BusinessRouter } from './business.router'; import { CallRouter } from './call.router'; import { ChatRouter } from './chat.router'; import { GroupRouter } from './group.router'; @@ -34,23 +37,154 @@ enum HttpStatus { const router: Router = Router(); const serverConfig = configService.get('SERVER'); +const databaseConfig = configService.get('DATABASE'); const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']]; const telemetry = new Telemetry(); const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8')); +// Middleware for metrics IP whitelist +const metricsIPWhitelist = (req: Request, res: Response, next: NextFunction) => { + const metricsConfig = configService.get('METRICS'); + const allowedIPs = metricsConfig.ALLOWED_IPS?.split(',').map((ip) => ip.trim()) || ['127.0.0.1']; + const clientIPs = [ + req.ip, + req.connection.remoteAddress, + req.socket.remoteAddress, + req.headers['x-forwarded-for'], + ].filter((ip) => ip !== undefined); + + if (allowedIPs.filter((ip) => clientIPs.includes(ip)) === 0) { + return res.status(403).send('Forbidden: IP not allowed'); + } + + next(); +}; + +// Middleware for metrics Basic Authentication +const metricsBasicAuth = (req: Request, res: Response, next: NextFunction) => { + const metricsConfig = configService.get('METRICS'); + const metricsUser = metricsConfig.USER; + const metricsPass = metricsConfig.PASSWORD; + + if (!metricsUser || !metricsPass) { + return res.status(500).send('Metrics authentication not configured'); + } + + const auth = req.get('Authorization'); + if (!auth || !auth.startsWith('Basic ')) { + res.set('WWW-Authenticate', 'Basic realm="Evolution API Metrics"'); + return res.status(401).send('Authentication required'); + } + + const credentials = Buffer.from(auth.slice(6), 'base64').toString(); + const [user, pass] = credentials.split(':'); + + if (user !== metricsUser || pass !== metricsPass) { + return res.status(401).send('Invalid credentials'); + } + + next(); +}; + +// Expose Prometheus metrics when enabled by env flag +const metricsConfig = configService.get('METRICS'); +if (metricsConfig.ENABLED) { + const metricsMiddleware = []; + + // Add IP whitelist if configured + if (metricsConfig.ALLOWED_IPS) { + metricsMiddleware.push(metricsIPWhitelist); + } + + // Add Basic Auth if required + if (metricsConfig.AUTH_REQUIRED) { + metricsMiddleware.push(metricsBasicAuth); + } + + router.get('/metrics', ...metricsMiddleware, async (req, res) => { + res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8'); + res.set('Cache-Control', 'no-cache, no-store, must-revalidate'); + + const escapeLabel = (value: unknown) => + String(value ?? '') + .replace(/\\/g, '\\\\') + .replace(/\n/g, '\\n') + .replace(/"/g, '\\"'); + + const lines: string[] = []; + + const clientName = databaseConfig.CONNECTION.CLIENT_NAME || 'unknown'; + const serverUrl = serverConfig.URL || ''; + + // environment info + lines.push('# HELP evolution_environment_info Environment information'); + lines.push('# TYPE evolution_environment_info gauge'); + lines.push( + `evolution_environment_info{version="${escapeLabel(packageJson.version)}",clientName="${escapeLabel( + clientName, + )}",serverUrl="${escapeLabel(serverUrl)}"} 1`, + ); + + const instances = (waMonitor && waMonitor.waInstances) || {}; + const instanceEntries = Object.entries(instances); + + // total instances + lines.push('# HELP evolution_instances_total Total number of instances'); + lines.push('# TYPE evolution_instances_total gauge'); + lines.push(`evolution_instances_total ${instanceEntries.length}`); + + // per-instance status + lines.push('# HELP evolution_instance_up 1 if instance state is open, else 0'); + lines.push('# TYPE evolution_instance_up gauge'); + lines.push('# HELP evolution_instance_state Instance state as a labelled metric'); + lines.push('# TYPE evolution_instance_state gauge'); + + for (const [name, instance] of instanceEntries) { + const state = instance?.connectionStatus?.state || 'unknown'; + const integration = instance?.integration || ''; + const up = state === 'open' ? 1 : 0; + + lines.push( + `evolution_instance_up{instance="${escapeLabel(name)}",integration="${escapeLabel(integration)}"} ${up}`, + ); + lines.push( + `evolution_instance_state{instance="${escapeLabel(name)}",integration="${escapeLabel( + integration, + )}",state="${escapeLabel(state)}"} 1`, + ); + } + + res.send(lines.join('\n') + '\n'); + }); +} + if (!serverConfig.DISABLE_MANAGER) router.use('/manager', new ViewsRouter().router); router.get('/assets/*', (req, res) => { const fileName = req.params[0]; + + // Security: Reject paths containing traversal patterns + if (!fileName || fileName.includes('..') || fileName.includes('\\') || path.isAbsolute(fileName)) { + return res.status(403).send('Forbidden'); + } + const basePath = path.join(process.cwd(), 'manager', 'dist'); + const assetsPath = path.join(basePath, 'assets'); + const filePath = path.join(assetsPath, fileName); - const filePath = path.join(basePath, 'assets/', fileName); + // Security: Ensure the resolved path is within the assets directory + const resolvedPath = path.resolve(filePath); + const resolvedAssetsPath = path.resolve(assetsPath); + + if (!resolvedPath.startsWith(resolvedAssetsPath + path.sep) && resolvedPath !== resolvedAssetsPath) { + return res.status(403).send('Forbidden'); + } - if (fs.existsSync(filePath)) { - res.set('Content-Type', mime.getType(filePath) || 'text/css'); - res.send(fs.readFileSync(filePath)); + if (fs.existsSync(resolvedPath)) { + res.set('Content-Type', mimeTypes.lookup(resolvedPath) || 'text/css'); + res.send(fs.readFileSync(resolvedPath)); } else { res.status(404).send('File not found'); } @@ -59,35 +193,38 @@ router.get('/assets/*', (req, res) => { router .use((req, res, next) => telemetry.collectTelemetry(req, res, next)) - .get('/', (req, res) => { + .get('/', async (req, res) => { res.status(HttpStatus.OK).json({ status: HttpStatus.OK, message: 'Welcome to the Evolution API, it is working!', version: packageJson.version, - clientName: process.env.DATABASE_CONNECTION_CLIENT_NAME, + clientName: databaseConfig.CONNECTION.CLIENT_NAME, manager: !serverConfig.DISABLE_MANAGER ? `${req.protocol}://${req.get('host')}/manager` : undefined, documentation: `https://doc.evolution-api.com`, + whatsappWebVersion: (await fetchLatestWaWebVersion({})).version.join('.'), }); }) .post('/verify-creds', authGuard['apikey'], async (req, res) => { + const facebookConfig = configService.get('FACEBOOK'); return res.status(HttpStatus.OK).json({ status: HttpStatus.OK, message: 'Credentials are valid', - facebookAppId: process.env.FACEBOOK_APP_ID, - facebookConfigId: process.env.FACEBOOK_CONFIG_ID, - facebookUserToken: process.env.FACEBOOK_USER_TOKEN, + facebookAppId: facebookConfig.APP_ID, + facebookConfigId: facebookConfig.CONFIG_ID, + facebookUserToken: facebookConfig.USER_TOKEN, }); }) .use('/instance', new InstanceRouter(configService, ...guards).router) .use('/message', new MessageRouter(...guards).router) .use('/call', new CallRouter(...guards).router) .use('/chat', new ChatRouter(...guards).router) + .use('/business', new BusinessRouter(...guards).router) .use('/group', new GroupRouter(...guards).router) .use('/template', new TemplateRouter(configService, ...guards).router) .use('/settings', new SettingsRouter(...guards).router) .use('/proxy', new ProxyRouter(...guards).router) .use('/label', new LabelRouter(...guards).router) - .use('', new ChannelRouter(configService).router) + .use('', new ChannelRouter(configService, ...guards).router) .use('', new EventRouter(configService, ...guards).router) .use('', new ChatbotRouter(...guards).router) .use('', new StorageRouter(...guards).router); diff --git a/src/api/routes/instance.router.ts b/src/api/routes/instance.router.ts index 7b81368da..3559893e6 100644 --- a/src/api/routes/instance.router.ts +++ b/src/api/routes/instance.router.ts @@ -8,7 +8,10 @@ import { RequestHandler, Router } from 'express'; import { HttpStatus } from './index.router'; export class InstanceRouter extends RouterBroker { - constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { + constructor( + readonly configService: ConfigService, + ...guards: RequestHandler[] + ) { super(); this.router .post('/create', ...guards, async (req, res) => { diff --git a/src/api/routes/template.router.ts b/src/api/routes/template.router.ts index 67607dc8e..249019a0c 100644 --- a/src/api/routes/template.router.ts +++ b/src/api/routes/template.router.ts @@ -1,36 +1,92 @@ import { RouterBroker } from '@api/abstract/abstract.router'; import { InstanceDto } from '@api/dto/instance.dto'; -import { TemplateDto } from '@api/dto/template.dto'; +import { TemplateDeleteDto, TemplateDto, TemplateEditDto } from '@api/dto/template.dto'; import { templateController } from '@api/server.module'; import { ConfigService } from '@config/env.config'; +import { createMetaErrorResponse } from '@utils/errorResponse'; +import { templateDeleteSchema } from '@validate/templateDelete.schema'; +import { templateEditSchema } from '@validate/templateEdit.schema'; import { instanceSchema, templateSchema } from '@validate/validate.schema'; import { RequestHandler, Router } from 'express'; import { HttpStatus } from './index.router'; export class TemplateRouter extends RouterBroker { - constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) { + constructor( + readonly configService: ConfigService, + ...guards: RequestHandler[] + ) { super(); this.router .post(this.routerPath('create'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: templateSchema, - ClassRef: TemplateDto, - execute: (instance, data) => templateController.createTemplate(instance, data), - }); - - res.status(HttpStatus.CREATED).json(response); + try { + const response = await this.dataValidate({ + request: req, + schema: templateSchema, + ClassRef: TemplateDto, + execute: (instance, data) => templateController.createTemplate(instance, data), + }); + + res.status(HttpStatus.CREATED).json(response); + } catch (error) { + // Log error for debugging + console.error('Template creation error:', error); + + // Use utility function to create standardized error response + const errorResponse = createMetaErrorResponse(error, 'template_creation'); + res.status(errorResponse.status).json(errorResponse); + } + }) + .post(this.routerPath('edit'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: templateEditSchema, + ClassRef: TemplateEditDto, + execute: (instance, data) => templateController.editTemplate(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + } catch (error) { + console.error('Template edit error:', error); + const errorResponse = createMetaErrorResponse(error, 'template_edit'); + res.status(errorResponse.status).json(errorResponse); + } + }) + .delete(this.routerPath('delete'), ...guards, async (req, res) => { + try { + const response = await this.dataValidate({ + request: req, + schema: templateDeleteSchema, + ClassRef: TemplateDeleteDto, + execute: (instance, data) => templateController.deleteTemplate(instance, data), + }); + + res.status(HttpStatus.OK).json(response); + } catch (error) { + console.error('Template delete error:', error); + const errorResponse = createMetaErrorResponse(error, 'template_delete'); + res.status(errorResponse.status).json(errorResponse); + } }) .get(this.routerPath('find'), ...guards, async (req, res) => { - const response = await this.dataValidate({ - request: req, - schema: instanceSchema, - ClassRef: InstanceDto, - execute: (instance) => templateController.findTemplate(instance), - }); - - res.status(HttpStatus.OK).json(response); + try { + const response = await this.dataValidate({ + request: req, + schema: instanceSchema, + ClassRef: InstanceDto, + execute: (instance) => templateController.findTemplate(instance), + }); + + res.status(HttpStatus.OK).json(response); + } catch (error) { + // Log error for debugging + console.error('Template find error:', error); + + // Use utility function to create standardized error response + const errorResponse = createMetaErrorResponse(error, 'template_find'); + res.status(errorResponse.status).json(errorResponse); + } }); } diff --git a/src/api/server.module.ts b/src/api/server.module.ts index 84999cb8a..668b9e272 100644 --- a/src/api/server.module.ts +++ b/src/api/server.module.ts @@ -3,6 +3,7 @@ import { Chatwoot, configService, ProviderSession } from '@config/env.config'; import { eventEmitter } from '@config/event.config'; import { Logger } from '@config/logger.config'; +import { BusinessController } from './controllers/business.controller'; import { CallController } from './controllers/call.controller'; import { ChatController } from './controllers/chat.controller'; import { GroupController } from './controllers/group.controller'; @@ -15,15 +16,20 @@ import { TemplateController } from './controllers/template.controller'; import { ChannelController } from './integrations/channel/channel.controller'; import { EvolutionController } from './integrations/channel/evolution/evolution.controller'; import { MetaController } from './integrations/channel/meta/meta.controller'; +import { BaileysController } from './integrations/channel/whatsapp/baileys.controller'; import { ChatbotController } from './integrations/chatbot/chatbot.controller'; import { ChatwootController } from './integrations/chatbot/chatwoot/controllers/chatwoot.controller'; import { ChatwootService } from './integrations/chatbot/chatwoot/services/chatwoot.service'; import { DifyController } from './integrations/chatbot/dify/controllers/dify.controller'; import { DifyService } from './integrations/chatbot/dify/services/dify.service'; +import { EvoaiController } from './integrations/chatbot/evoai/controllers/evoai.controller'; +import { EvoaiService } from './integrations/chatbot/evoai/services/evoai.service'; import { EvolutionBotController } from './integrations/chatbot/evolutionBot/controllers/evolutionBot.controller'; import { EvolutionBotService } from './integrations/chatbot/evolutionBot/services/evolutionBot.service'; import { FlowiseController } from './integrations/chatbot/flowise/controllers/flowise.controller'; import { FlowiseService } from './integrations/chatbot/flowise/services/flowise.service'; +import { N8nController } from './integrations/chatbot/n8n/controllers/n8n.controller'; +import { N8nService } from './integrations/chatbot/n8n/services/n8n.service'; import { OpenaiController } from './integrations/chatbot/openai/controllers/openai.controller'; import { OpenaiService } from './integrations/chatbot/openai/services/openai.service'; import { TypebotController } from './integrations/chatbot/typebot/controllers/typebot.controller'; @@ -76,7 +82,7 @@ const proxyService = new ProxyService(waMonitor); export const proxyController = new ProxyController(proxyService, waMonitor); const chatwootService = new ChatwootService(waMonitor, configService, prismaRepository, chatwootCache); -export const chatwootController = new ChatwootController(chatwootService, configService, prismaRepository); +export const chatwootController = new ChatwootController(chatwootService, configService); const settingsService = new SettingsService(waMonitor); export const settingsController = new SettingsController(settingsService); @@ -97,6 +103,7 @@ export const instanceController = new InstanceController( export const sendMessageController = new SendMessageController(waMonitor); export const callController = new CallController(waMonitor); export const chatController = new ChatController(waMonitor); +export const businessController = new BusinessController(waMonitor); export const groupController = new GroupController(waMonitor); export const labelController = new LabelController(waMonitor); @@ -107,21 +114,28 @@ export const channelController = new ChannelController(prismaRepository, waMonit // channels export const evolutionController = new EvolutionController(prismaRepository, waMonitor); export const metaController = new MetaController(prismaRepository, waMonitor); +export const baileysController = new BaileysController(waMonitor); + +const openaiService = new OpenaiService(waMonitor, prismaRepository, configService); +export const openaiController = new OpenaiController(openaiService, prismaRepository, waMonitor); // chatbots -const typebotService = new TypebotService(waMonitor, configService, prismaRepository); +const typebotService = new TypebotService(waMonitor, configService, prismaRepository, openaiService); export const typebotController = new TypebotController(typebotService, prismaRepository, waMonitor); -const openaiService = new OpenaiService(waMonitor, configService, prismaRepository); -export const openaiController = new OpenaiController(openaiService, prismaRepository, waMonitor); - -const difyService = new DifyService(waMonitor, configService, prismaRepository); +const difyService = new DifyService(waMonitor, prismaRepository, configService, openaiService); export const difyController = new DifyController(difyService, prismaRepository, waMonitor); -const evolutionBotService = new EvolutionBotService(waMonitor, configService, prismaRepository); +const evolutionBotService = new EvolutionBotService(waMonitor, prismaRepository, configService, openaiService); export const evolutionBotController = new EvolutionBotController(evolutionBotService, prismaRepository, waMonitor); -const flowiseService = new FlowiseService(waMonitor, configService, prismaRepository); +const flowiseService = new FlowiseService(waMonitor, prismaRepository, configService, openaiService); export const flowiseController = new FlowiseController(flowiseService, prismaRepository, waMonitor); +const n8nService = new N8nService(waMonitor, prismaRepository, configService, openaiService); +export const n8nController = new N8nController(n8nService, prismaRepository, waMonitor); + +const evoaiService = new EvoaiService(waMonitor, prismaRepository, configService, openaiService); +export const evoaiController = new EvoaiController(evoaiService, prismaRepository, waMonitor); + logger.info('Module - ON'); diff --git a/src/api/services/channel.service.ts b/src/api/services/channel.service.ts index 146375cb7..56bec0802 100644 --- a/src/api/services/channel.service.ts +++ b/src/api/services/channel.service.ts @@ -9,10 +9,11 @@ import { TypebotService } from '@api/integrations/chatbot/typebot/services/typeb import { PrismaRepository, Query } from '@api/repository/repository.service'; import { eventManager, waMonitor } from '@api/server.module'; import { Events, wa } from '@api/types/wa.types'; -import { Auth, Chatwoot, ConfigService, HttpServer } from '@config/env.config'; +import { Auth, Chatwoot, ConfigService, HttpServer, Proxy } from '@config/env.config'; import { Logger } from '@config/logger.config'; import { NotFoundException } from '@exceptions'; -import { Contact, Message } from '@prisma/client'; +import { Contact, Message, Prisma } from '@prisma/client'; +import { createJid } from '@utils/createJid'; import { WASocket } from 'baileys'; import { isArray } from 'class-validator'; import EventEmitter2 from 'eventemitter2'; @@ -44,11 +45,11 @@ export class ChannelStartupService { this.chatwootCache, ); - public typebotService = new TypebotService(waMonitor, this.configService, this.prismaRepository); + public openaiService = new OpenaiService(waMonitor, this.prismaRepository, this.configService); - public openaiService = new OpenaiService(waMonitor, this.configService, this.prismaRepository); + public typebotService = new TypebotService(waMonitor, this.configService, this.prismaRepository, this.openaiService); - public difyService = new DifyService(waMonitor, this.configService, this.prismaRepository); + public difyService = new DifyService(waMonitor, this.prismaRepository, this.configService, this.openaiService); public setInstance(instance: InstanceDto) { this.logger.setInstance(instance.instanceName); @@ -59,6 +60,7 @@ export class ChannelStartupService { this.instance.number = instance.number; this.instance.token = instance.token; this.instance.businessId = instance.businessId; + this.instance.ownerJid = instance.ownerJid; if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled) { this.chatwootService.eventWhatsapp( @@ -151,6 +153,7 @@ export class ChannelStartupService { this.localSettings.readMessages = data?.readMessages; this.localSettings.readStatus = data?.readStatus; this.localSettings.syncFullHistory = data?.syncFullHistory; + this.localSettings.wavoipToken = data?.wavoipToken; } public async setSettings(data: SettingsDto) { @@ -166,6 +169,7 @@ export class ChannelStartupService { readMessages: data.readMessages, readStatus: data.readStatus, syncFullHistory: data.syncFullHistory, + wavoipToken: data.wavoipToken, }, create: { rejectCall: data.rejectCall, @@ -175,6 +179,7 @@ export class ChannelStartupService { readMessages: data.readMessages, readStatus: data.readStatus, syncFullHistory: data.syncFullHistory, + wavoipToken: data.wavoipToken, instanceId: this.instanceId, }, }); @@ -186,6 +191,12 @@ export class ChannelStartupService { this.localSettings.readMessages = data?.readMessages; this.localSettings.readStatus = data?.readStatus; this.localSettings.syncFullHistory = data?.syncFullHistory; + this.localSettings.wavoipToken = data?.wavoipToken; + + if (this.localSettings.wavoipToken && this.localSettings.wavoipToken.length > 0) { + this.client.ws.close(); + this.client.ws.connect(); + } } public async findSettings() { @@ -207,6 +218,7 @@ export class ChannelStartupService { readMessages: data.readMessages, readStatus: data.readStatus, syncFullHistory: data.syncFullHistory, + wavoipToken: data.wavoipToken, }; } @@ -353,13 +365,14 @@ export class ChannelStartupService { public async loadProxy() { this.localProxy.enabled = false; - if (process.env.PROXY_HOST) { + const proxyConfig = this.configService.get('PROXY'); + if (proxyConfig.HOST) { this.localProxy.enabled = true; - this.localProxy.host = process.env.PROXY_HOST; - this.localProxy.port = process.env.PROXY_PORT || '80'; - this.localProxy.protocol = process.env.PROXY_PROTOCOL || 'http'; - this.localProxy.username = process.env.PROXY_USERNAME; - this.localProxy.password = process.env.PROXY_PASSWORD; + this.localProxy.host = proxyConfig.HOST; + this.localProxy.port = proxyConfig.PORT || '80'; + this.localProxy.protocol = proxyConfig.PROTOCOL || 'http'; + this.localProxy.username = proxyConfig.USERNAME; + this.localProxy.password = proxyConfig.PASSWORD; } const data = await this.prismaRepository.proxy.findUnique({ @@ -419,7 +432,13 @@ export class ChannelStartupService { return data; } - public async sendDataWebhook(event: Events, data: T, local = true) { + public async sendDataWebhook( + event: Events, + data: T, + local = true, + integration?: string[], + extra?: Record, + ) { const serverUrl = this.configService.get('SERVER').URL; const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds const localISOTime = new Date(Date.now() - tzoffset).toISOString(); @@ -439,6 +458,8 @@ export class ChannelStartupService { sender: this.wuid, apiKey: expose && instanceApikey ? instanceApikey : null, local, + integration, + extra, }); } @@ -476,60 +497,104 @@ export class ChannelStartupService { } } - public createJid(number: string): string { - if (number.includes('@g.us') || number.includes('@s.whatsapp.net') || number.includes('@lid')) { - return number; + public async fetchContacts(query: Query) { + const where: any = { + instanceId: this.instanceId, + }; + + if (query?.where?.remoteJid) { + const remoteJid = query.where.remoteJid.includes('@') ? query.where.remoteJid : createJid(query.where.remoteJid); + where['remoteJid'] = remoteJid; } - if (number.includes('@broadcast')) { - return number; + if (query?.where?.id) { + where['id'] = query.where.id; } - number = number - ?.replace(/\s/g, '') - .replace(/\+/g, '') - .replace(/\(/g, '') - .replace(/\)/g, '') - .split(':')[0] - .split('@')[0]; - - if (number.includes('-') && number.length >= 24) { - number = number.replace(/[^\d-]/g, ''); - return `${number}@g.us`; + if (query?.where?.pushName) { + where['pushName'] = query.where.pushName; } - number = number.replace(/\D/g, ''); + const contactFindManyArgs: Prisma.ContactFindManyArgs = { + where, + }; - if (number.length >= 18) { - number = number.replace(/[^\d-]/g, ''); - return `${number}@g.us`; + if (query.offset) contactFindManyArgs.take = query.offset; + if (query.page) { + const validPage = Math.max(query.page as number, 1); + contactFindManyArgs.skip = query.offset * (validPage - 1); } - number = this.formatMXOrARNumber(number); + const contacts = await this.prismaRepository.contact.findMany(contactFindManyArgs); + + return contacts.map((contact) => { + const remoteJid = contact.remoteJid; + const isGroup = remoteJid.endsWith('@g.us'); + const isSaved = !!contact.pushName || !!contact.profilePicUrl; + const type = isGroup ? 'group' : isSaved ? 'contact' : 'group_member'; + return { + ...contact, + isGroup, + isSaved, + type, + }; + }); + } - number = this.formatBRNumber(number); + public cleanMessageData(message: any) { + if (!message) return message; + const cleanedMessage = { ...message }; - return `${number}@s.whatsapp.net`; - } + if (cleanedMessage.message) { + const { mediaUrl } = cleanedMessage.message; + delete cleanedMessage.message.base64; - public async fetchContacts(query: Query) { - const remoteJid = query?.where?.remoteJid - ? query?.where?.remoteJid.includes('@') - ? query.where?.remoteJid - : this.createJid(query.where?.remoteJid) - : null; + // Limpa imageMessage + if (cleanedMessage.message.imageMessage) { + cleanedMessage.message.imageMessage = { + caption: cleanedMessage.message.imageMessage.caption, + }; + } - const where = { - instanceId: this.instanceId, - }; + // Limpa videoMessage + if (cleanedMessage.message.videoMessage) { + cleanedMessage.message.videoMessage = { + caption: cleanedMessage.message.videoMessage.caption, + }; + } - if (remoteJid) { - where['remoteJid'] = remoteJid; + // Limpa audioMessage + if (cleanedMessage.message.audioMessage) { + cleanedMessage.message.audioMessage = { + seconds: cleanedMessage.message.audioMessage.seconds, + }; + } + + // Limpa stickerMessage + if (cleanedMessage.message.stickerMessage) { + cleanedMessage.message.stickerMessage = {}; + } + + // Limpa documentMessage + if (cleanedMessage.message.documentMessage) { + cleanedMessage.message.documentMessage = { + caption: cleanedMessage.message.documentMessage.caption, + name: cleanedMessage.message.documentMessage.name, + }; + } + + // Limpa documentWithCaptionMessage + if (cleanedMessage.message.documentWithCaptionMessage) { + cleanedMessage.message.documentWithCaptionMessage = { + caption: cleanedMessage.message.documentWithCaptionMessage.caption, + name: cleanedMessage.message.documentWithCaptionMessage.name, + }; + } + + if (mediaUrl) cleanedMessage.message.mediaUrl = mediaUrl; } - return await this.prismaRepository.contact.findMany({ - where, - }); + return cleanedMessage; } public async fetchMessages(query: Query) { @@ -540,12 +605,23 @@ export class ChannelStartupService { participants?: string; }; + const timestampFilter = {}; + if (query?.where?.messageTimestamp) { + if (query.where.messageTimestamp['gte'] && query.where.messageTimestamp['lte']) { + timestampFilter['messageTimestamp'] = { + gte: Math.floor(new Date(query.where.messageTimestamp['gte']).getTime() / 1000), + lte: Math.floor(new Date(query.where.messageTimestamp['lte']).getTime() / 1000), + }; + } + } + const count = await this.prismaRepository.message.count({ where: { instanceId: this.instanceId, id: query?.where?.id, source: query?.where?.source, messageType: query?.where?.messageType, + ...timestampFilter, AND: [ keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, @@ -569,6 +645,7 @@ export class ChannelStartupService { id: query?.where?.id, source: query?.where?.source, messageType: query?.where?.messageType, + ...timestampFilter, AND: [ keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {}, keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {}, @@ -610,6 +687,14 @@ export class ChannelStartupService { } public async fetchStatusMessage(query: any) { + if (!query?.offset) { + query.offset = 50; + } + + if (!query?.page) { + query.page = 1; + } + return await this.prismaRepository.messageUpdate.findMany({ where: { instanceId: this.instanceId, @@ -621,119 +706,150 @@ export class ChannelStartupService { }); } + public async findChatByRemoteJid(remoteJid: string) { + if (!remoteJid) return null; + return await this.prismaRepository.chat.findFirst({ + where: { + instanceId: this.instanceId, + remoteJid: remoteJid, + }, + }); + } + public async fetchChats(query: any) { const remoteJid = query?.where?.remoteJid ? query?.where?.remoteJid.includes('@') ? query.where?.remoteJid - : this.createJid(query.where?.remoteJid) + : createJid(query.where?.remoteJid) : null; - let results = []; - - if (!remoteJid) { - results = await this.prismaRepository.$queryRaw` - SELECT - "Chat"."id", - "Chat"."remoteJid", - "Chat"."name", - "Chat"."labels", - "Chat"."createdAt", - "Chat"."updatedAt", - "Contact"."pushName", - "Contact"."profilePicUrl", - "Chat"."unreadMessages", - (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, - (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, - (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name, - (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, - (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type, - (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, - (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info, - (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, - (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp, - (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id, - (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id, - (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status - FROM "Chat" - LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid" - LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" - WHERE - "Chat"."instanceId" = ${this.instanceId} - GROUP BY - "Chat"."id", - "Chat"."remoteJid", - "Contact"."id" - ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC; - `; - } else { - results = await this.prismaRepository.$queryRaw` - SELECT - "Chat"."id", - "Chat"."remoteJid", - "Chat"."name", - "Chat"."labels", - "Chat"."createdAt", - "Chat"."updatedAt", - "Contact"."pushName", - "Contact"."profilePicUrl", - "Chat"."unreadMessages", - (ARRAY_AGG("Message"."id" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_id, - (ARRAY_AGG("Message"."key" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_key, - (ARRAY_AGG("Message"."pushName" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_push_name, - (ARRAY_AGG("Message"."participant" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_participant, - (ARRAY_AGG("Message"."messageType" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_type, - (ARRAY_AGG("Message"."message" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message, - (ARRAY_AGG("Message"."contextInfo" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_context_info, - (ARRAY_AGG("Message"."source" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_source, - (ARRAY_AGG("Message"."messageTimestamp" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_message_timestamp, - (ARRAY_AGG("Message"."instanceId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_instance_id, - (ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id, - (ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status - FROM "Chat" - LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid" - LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" - WHERE - "Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} and "Message"."messageType" != 'reactionMessage' - GROUP BY - "Chat"."id", - "Chat"."remoteJid", - "Contact"."id" - ORDER BY last_message_message_timestamp DESC NULLS LAST, "Chat"."updatedAt" DESC; - `; + const where = { + instanceId: this.instanceId, + }; + + if (remoteJid) { + where['remoteJid'] = remoteJid; } + const timestampFilter = + query?.where?.messageTimestamp?.gte && query?.where?.messageTimestamp?.lte + ? Prisma.sql` + AND "Message"."messageTimestamp" >= ${Math.floor(new Date(query.where.messageTimestamp.gte).getTime() / 1000)} + AND "Message"."messageTimestamp" <= ${Math.floor(new Date(query.where.messageTimestamp.lte).getTime() / 1000)}` + : Prisma.sql``; + + const limit = query?.take ? Prisma.sql`LIMIT ${query.take}` : Prisma.sql``; + const offset = query?.skip ? Prisma.sql`OFFSET ${query.skip}` : Prisma.sql``; + + const results = await this.prismaRepository.$queryRaw` + WITH rankedMessages AS ( + SELECT DISTINCT ON ("Message"."key"->>'remoteJid') + "Contact"."id" as "contactId", + "Message"."key"->>'remoteJid' as "remoteJid", + CASE + WHEN "Message"."key"->>'remoteJid' LIKE '%@g.us' THEN COALESCE("Chat"."name", "Contact"."pushName") + ELSE COALESCE("Contact"."pushName", "Message"."pushName") + END as "pushName", + "Contact"."profilePicUrl", + COALESCE( + to_timestamp("Message"."messageTimestamp"::double precision), + "Contact"."updatedAt" + ) as "updatedAt", + "Chat"."name" as "pushName", + "Chat"."createdAt" as "windowStart", + "Chat"."createdAt" + INTERVAL '24 hours' as "windowExpires", + "Chat"."unreadMessages" as "unreadMessages", + CASE WHEN "Chat"."createdAt" + INTERVAL '24 hours' > NOW() THEN true ELSE false END as "windowActive", + "Message"."id" AS "lastMessageId", + "Message"."key" AS "lastMessage_key", + CASE + WHEN "Message"."key"->>'fromMe' = 'true' THEN 'Você' + ELSE "Message"."pushName" + END AS "lastMessagePushName", + "Message"."participant" AS "lastMessageParticipant", + "Message"."messageType" AS "lastMessageMessageType", + "Message"."message" AS "lastMessageMessage", + "Message"."contextInfo" AS "lastMessageContextInfo", + "Message"."source" AS "lastMessageSource", + "Message"."messageTimestamp" AS "lastMessageMessageTimestamp", + "Message"."instanceId" AS "lastMessageInstanceId", + "Message"."sessionId" AS "lastMessageSessionId", + "Message"."status" AS "lastMessageStatus" + FROM "Message" + LEFT JOIN "Contact" ON "Contact"."remoteJid" = "Message"."key"->>'remoteJid' AND "Contact"."instanceId" = "Message"."instanceId" + LEFT JOIN "Chat" ON "Chat"."remoteJid" = "Message"."key"->>'remoteJid' AND "Chat"."instanceId" = "Message"."instanceId" + WHERE "Message"."instanceId" = ${this.instanceId} + ${remoteJid ? Prisma.sql`AND "Message"."key"->>'remoteJid' = ${remoteJid}` : Prisma.sql``} + ${timestampFilter} + ORDER BY "Message"."key"->>'remoteJid', "Message"."messageTimestamp" DESC + ) + SELECT * FROM rankedMessages + ORDER BY "updatedAt" DESC NULLS LAST + ${limit} + ${offset}; + `; + if (results && isArray(results) && results.length > 0) { - return results.map((chat) => { + const mappedResults = results.map((contact) => { + const lastMessage = contact.lastMessageId + ? { + id: contact.lastMessageId, + key: contact.lastMessage_key, + pushName: contact.lastMessagePushName, + participant: contact.lastMessageParticipant, + messageType: contact.lastMessageMessageType, + message: contact.lastMessageMessage, + contextInfo: contact.lastMessageContextInfo, + source: contact.lastMessageSource, + messageTimestamp: contact.lastMessageMessageTimestamp, + instanceId: contact.lastMessageInstanceId, + sessionId: contact.lastMessageSessionId, + status: contact.lastMessageStatus, + } + : undefined; + return { - id: chat.id, - remoteJid: chat.remoteJid, - name: chat.name, - labels: chat.labels, - createdAt: chat.createdAt, - updatedAt: chat.updatedAt, - pushName: chat.pushName, - profilePicUrl: chat.profilePicUrl, - unreadMessages: chat.unreadMessages, - lastMessage: chat.last_message_id - ? { - id: chat.last_message_id, - key: chat.last_message_key, - pushName: chat.last_message_push_name, - participant: chat.last_message_participant, - messageType: chat.last_message_message_type, - message: chat.last_message_message, - contextInfo: chat.last_message_context_info, - source: chat.last_message_source, - messageTimestamp: chat.last_message_message_timestamp, - instanceId: chat.last_message_instance_id, - sessionId: chat.last_message_session_id, - status: chat.last_message_status, - } - : undefined, + id: contact.contactId || null, + remoteJid: contact.remoteJid, + pushName: contact.pushName, + profilePicUrl: contact.profilePicUrl, + updatedAt: contact.updatedAt, + windowStart: contact.windowStart, + windowExpires: contact.windowExpires, + windowActive: contact.windowActive, + lastMessage: lastMessage ? this.cleanMessageData(lastMessage) : undefined, + unreadCount: contact.unreadMessages, + isSaved: !!contact.contactId, }; }); + + return mappedResults; } return []; } + + public hasValidMediaContent(message: any): boolean { + if (!message?.message) return false; + + const msg = message.message; + + // Se só tem messageContextInfo, não é mídia válida + if (Object.keys(msg).length === 1 && Object.prototype.hasOwnProperty.call(msg, 'messageContextInfo')) { + return false; + } + + // Verifica se tem pelo menos um tipo de mídia válido + const mediaTypes = [ + 'imageMessage', + 'videoMessage', + 'stickerMessage', + 'documentMessage', + 'documentWithCaptionMessage', + 'ptvMessage', + 'audioMessage', + ]; + + return mediaTypes.some((type) => msg[type] && Object.keys(msg[type]).length > 0); + } } diff --git a/src/api/services/monitor.service.ts b/src/api/services/monitor.service.ts index c69e4fca5..438530b57 100644 --- a/src/api/services/monitor.service.ts +++ b/src/api/services/monitor.service.ts @@ -7,7 +7,7 @@ import { CacheConf, Chatwoot, ConfigService, Database, DelInstance, ProviderSess import { Logger } from '@config/logger.config'; import { INSTANCE_DIR, STORE_DIR } from '@config/path.config'; import { NotFoundException } from '@exceptions'; -import { execSync } from 'child_process'; +import { execFileSync } from 'child_process'; import EventEmitter2 from 'eventemitter2'; import { rmSync } from 'fs'; import { join } from 'path'; @@ -29,6 +29,8 @@ export class WAMonitoringService { Object.assign(this.db, configService.get('DATABASE')); Object.assign(this.redis, configService.get('CACHE')); + + (this as any).providerSession = Object.freeze(configService.get('PROVIDER')); } private readonly db: Partial = {}; @@ -36,26 +38,48 @@ export class WAMonitoringService { private readonly logger = new Logger('WAMonitoringService'); public readonly waInstances: Record = {}; + private readonly delInstanceTimeouts: Record = {}; - private readonly providerSession = Object.freeze(this.configService.get('PROVIDER')); + private readonly providerSession: ProviderSession; public delInstanceTime(instance: string) { const time = this.configService.get('DEL_INSTANCE'); if (typeof time === 'number' && time > 0) { - setTimeout(async () => { - if (this.waInstances[instance]?.connectionStatus?.state !== 'open') { - if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') { - if ((await this.waInstances[instance].integration) === Integration.WHATSAPP_BAILEYS) { - await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance); - this.waInstances[instance]?.client?.ws?.close(); - this.waInstances[instance]?.client?.end(undefined); + // Clear previous timeout if exists + if (this.delInstanceTimeouts[instance]) { + clearTimeout(this.delInstanceTimeouts[instance]); + } + + // Set new timeout and store reference + this.delInstanceTimeouts[instance] = setTimeout( + async () => { + try { + if (this.waInstances[instance]?.connectionStatus?.state !== 'open') { + if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') { + if ((await this.waInstances[instance].integration) === Integration.WHATSAPP_BAILEYS) { + await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance); + this.waInstances[instance]?.client?.ws?.close(); + this.waInstances[instance]?.client?.end(undefined); + } + this.eventEmitter.emit('remove.instance', instance, 'inner'); + } else { + this.eventEmitter.emit('remove.instance', instance, 'inner'); + } } - this.eventEmitter.emit('remove.instance', instance, 'inner'); - } else { - this.eventEmitter.emit('remove.instance', instance, 'inner'); + } finally { + // Clean up timeout reference + delete this.delInstanceTimeouts[instance]; } - } - }, 1000 * 60 * time); + }, + 1000 * 60 * time, + ); + } + } + + public clearDelInstanceTime(instance: string) { + if (this.delInstanceTimeouts[instance]) { + clearTimeout(this.delInstanceTimeouts[instance]); + delete this.delInstanceTimeouts[instance]; } } @@ -72,14 +96,15 @@ export class WAMonitoringService { const clientName = this.configService.get('DATABASE').CONNECTION.CLIENT_NAME; - const where = instanceNames && instanceNames.length > 0 - ? { - name: { - in: instanceNames, - }, - clientName, - } - : { clientName }; + const where = + instanceNames && instanceNames.length > 0 + ? { + name: { + in: instanceNames, + }, + clientName, + } + : { clientName }; const instances = await this.prismaRepository.instance.findMany({ where, @@ -87,6 +112,7 @@ export class WAMonitoringService { Chatwoot: true, Proxy: true, Rabbitmq: true, + Nats: true, Sqs: true, Websocket: true, Setting: true, @@ -164,7 +190,8 @@ export class WAMonitoringService { public async cleaningStoreData(instanceName: string) { if (this.configService.get('CHATWOOT').ENABLED) { - execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`); + const instancePath = join(STORE_DIR, 'chatwoot', instanceName); + execFileSync('rm', ['-rf', instancePath]); } const instance = await this.prismaRepository.instance.findFirst({ @@ -186,6 +213,7 @@ export class WAMonitoringService { await this.prismaRepository.chatwoot.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.proxy.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.rabbitmq.deleteMany({ where: { instanceId: instance.id } }); + await this.prismaRepository.nats.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.sqs.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.integrationSession.deleteMany({ where: { instanceId: instance.id } }); await this.prismaRepository.typebot.deleteMany({ where: { instanceId: instance.id } }); @@ -217,8 +245,11 @@ export class WAMonitoringService { data: { id: data.instanceId, name: data.instanceName, + ownerJid: data.ownerJid, + profileName: data.profileName, + profilePicUrl: data.profilePicUrl, connectionStatus: - data.integration && data.integration === Integration.WHATSAPP_BAILEYS ? 'close' : data.status ?? 'open', + data.integration && data.integration === Integration.WHATSAPP_BAILEYS ? 'close' : (data.status ?? 'open'), number: data.number, integration: data.integration || Integration.WHATSAPP_BAILEYS, token: data.hash, @@ -259,9 +290,19 @@ export class WAMonitoringService { token: instanceData.token, number: instanceData.number, businessId: instanceData.businessId, + ownerJid: instanceData.ownerJid, }); - await instance.connectToWhatsapp(); + if (instanceData.connectionStatus === 'open' || instanceData.connectionStatus === 'connecting') { + this.logger.info( + `Auto-connecting instance "${instanceData.instanceName}" (status: ${instanceData.connectionStatus})`, + ); + await instance.connectToWhatsapp(); + } else { + this.logger.info( + `Skipping auto-connect for instance "${instanceData.instanceName}" (status: ${instanceData.connectionStatus || 'close'})`, + ); + } this.waInstances[instanceData.instanceName] = instance; } @@ -287,6 +328,7 @@ export class WAMonitoringService { token: instanceData.token, number: instanceData.number, businessId: instanceData.businessId, + connectionStatus: instanceData.connectionStatus as any, // Pass connection status }; this.setInstance(instance); @@ -315,6 +357,8 @@ export class WAMonitoringService { token: instance.token, number: instance.number, businessId: instance.businessId, + ownerJid: instance.ownerJid, + connectionStatus: instance.connectionStatus as any, // Pass connection status }); }), ); @@ -339,6 +383,7 @@ export class WAMonitoringService { integration: instance.integration, token: instance.token, businessId: instance.businessId, + connectionStatus: instance.connectionStatus as any, // Pass connection status }); }), ); @@ -349,6 +394,8 @@ export class WAMonitoringService { try { await this.waInstances[instanceName]?.sendDataWebhook(Events.REMOVE_INSTANCE, null); + this.clearDelInstanceTime(instanceName); + this.cleaningUp(instanceName); this.cleaningStoreData(instanceName); } finally { @@ -365,6 +412,8 @@ export class WAMonitoringService { try { await this.waInstances[instanceName]?.sendDataWebhook(Events.LOGOUT_INSTANCE, null); + this.clearDelInstanceTime(instanceName); + if (this.configService.get('CHATWOOT').ENABLED) { this.waInstances[instanceName]?.clearCacheChatwoot(); } diff --git a/src/api/services/proxy.service.ts b/src/api/services/proxy.service.ts index 69ba87b41..a1e5b2100 100644 --- a/src/api/services/proxy.service.ts +++ b/src/api/services/proxy.service.ts @@ -25,7 +25,7 @@ export class ProxyService { } return result; - } catch (error) { + } catch { return null; } } diff --git a/src/api/services/settings.service.ts b/src/api/services/settings.service.ts index 5b7ab1b83..da477c46b 100644 --- a/src/api/services/settings.service.ts +++ b/src/api/services/settings.service.ts @@ -24,7 +24,7 @@ export class SettingsService { } return result; - } catch (error) { + } catch { return null; } } diff --git a/src/api/services/template.service.ts b/src/api/services/template.service.ts index 949f71c78..5bf0ba5d6 100644 --- a/src/api/services/template.service.ts +++ b/src/api/services/template.service.ts @@ -60,6 +60,13 @@ export class TemplateService { const response = await this.requestTemplate(postData, 'POST'); if (!response || response.error) { + // If there's an error from WhatsApp API, throw it with the real error data + if (response && response.error) { + // Create an error object that includes the template field for Meta errors + const metaError = new Error(response.error.message || 'WhatsApp API Error'); + (metaError as any).template = response.error; + throw metaError; + } throw new Error('Error to create template'); } @@ -75,9 +82,81 @@ export class TemplateService { return template; } catch (error) { - this.logger.error(error); - throw new Error('Error to create template'); + this.logger.error('Error in create template: ' + error); + // Propagate the real error instead of "engolindo" it + throw error; + } + } + + public async edit( + instance: InstanceDto, + data: { templateId: string; category?: string; components?: any; allowCategoryChange?: boolean; ttl?: number }, + ) { + const getInstance = await this.waMonitor.waInstances[instance.instanceName].instance; + if (!getInstance) { + throw new Error('Instance not found'); + } + + this.businessId = getInstance.businessId; + this.token = getInstance.token; + + const payload: Record = {}; + if (typeof data.category === 'string') payload.category = data.category; + if (typeof data.allowCategoryChange === 'boolean') payload.allow_category_change = data.allowCategoryChange; + if (typeof data.ttl === 'number') payload.time_to_live = data.ttl; + if (data.components) payload.components = data.components; + + const response = await this.requestEditTemplate(data.templateId, payload); + + if (!response || response.error) { + if (response && response.error) { + const metaError = new Error(response.error.message || 'WhatsApp API Error'); + (metaError as any).template = response.error; + throw metaError; + } + throw new Error('Error to edit template'); } + + return response; + } + + public async delete(instance: InstanceDto, data: { name: string; hsmId?: string }) { + const getInstance = await this.waMonitor.waInstances[instance.instanceName].instance; + if (!getInstance) { + throw new Error('Instance not found'); + } + + this.businessId = getInstance.businessId; + this.token = getInstance.token; + + const response = await this.requestDeleteTemplate({ name: data.name, hsm_id: data.hsmId }); + + if (!response || response.error) { + if (response && response.error) { + const metaError = new Error(response.error.message || 'WhatsApp API Error'); + (metaError as any).template = response.error; + throw metaError; + } + throw new Error('Error to delete template'); + } + + try { + // Best-effort local cleanup of stored template metadata + await this.prismaRepository.template.deleteMany({ + where: { + OR: [ + { name: data.name, instanceId: getInstance.id }, + data.hsmId ? { templateId: data.hsmId, instanceId: getInstance.id } : undefined, + ].filter(Boolean) as any, + }, + }); + } catch (err) { + this.logger.warn( + `Failed to cleanup local template records after delete: ${(err as Error)?.message || String(err)}`, + ); + } + + return response; } private async requestTemplate(data: any, method: string) { @@ -86,6 +165,7 @@ export class TemplateService { const version = this.configService.get('WA_BUSINESS').VERSION; urlServer = `${urlServer}/${version}/${this.businessId}/message_templates`; const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; + if (method === 'GET') { const result = await axios.get(urlServer, { headers }); return result.data; @@ -94,8 +174,51 @@ export class TemplateService { return result.data; } } catch (e) { - this.logger.error(e.response.data); - return e.response.data.error; + this.logger.error( + 'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message), + ); + + // Return the complete error response from WhatsApp API + if (e.response?.data) { + return e.response.data; + } + + // If no response data, throw connection error + throw new Error(`Connection error: ${e.message}`); + } + } + + private async requestEditTemplate(templateId: string, data: any) { + try { + let urlServer = this.configService.get('WA_BUSINESS').URL; + const version = this.configService.get('WA_BUSINESS').VERSION; + urlServer = `${urlServer}/${version}/${templateId}`; + const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` }; + const result = await axios.post(urlServer, data, { headers }); + return result.data; + } catch (e) { + this.logger.error( + 'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message), + ); + if (e.response?.data) return e.response.data; + throw new Error(`Connection error: ${e.message}`); + } + } + + private async requestDeleteTemplate(params: { name: string; hsm_id?: string }) { + try { + let urlServer = this.configService.get('WA_BUSINESS').URL; + const version = this.configService.get('WA_BUSINESS').VERSION; + urlServer = `${urlServer}/${version}/${this.businessId}/message_templates`; + const headers = { Authorization: `Bearer ${this.token}` }; + const result = await axios.delete(urlServer, { headers, params }); + return result.data; + } catch (e) { + this.logger.error( + 'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message), + ); + if (e.response?.data) return e.response.data; + throw new Error(`Connection error: ${e.message}`); } } } diff --git a/src/api/types/wa.types.ts b/src/api/types/wa.types.ts index 72c183b23..8f7c6a390 100644 --- a/src/api/types/wa.types.ts +++ b/src/api/types/wa.types.ts @@ -15,6 +15,7 @@ export enum Events { MESSAGES_UPDATE = 'messages.update', MESSAGES_DELETE = 'messages.delete', SEND_MESSAGE = 'send.message', + SEND_MESSAGE_UPDATE = 'send.message.update', CONTACTS_SET = 'contacts.set', CONTACTS_UPSERT = 'contacts.upsert', CONTACTS_UPDATE = 'contacts.update', @@ -51,6 +52,7 @@ export declare namespace wa { pairingCode?: string; authState?: { state: AuthenticationState; saveCreds: () => void }; name?: string; + ownerJid?: string; wuid?: string; profileName?: string; profilePictureUrl?: string; @@ -85,6 +87,7 @@ export declare namespace wa { readMessages?: boolean; readStatus?: boolean; syncFullHistory?: boolean; + wavoipToken?: string; }; export type LocalEvent = { @@ -131,7 +134,14 @@ export declare namespace wa { export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED'; } -export const TypeMediaMessage = ['imageMessage', 'documentMessage', 'audioMessage', 'videoMessage', 'stickerMessage', 'ptvMessage']; +export const TypeMediaMessage = [ + 'imageMessage', + 'documentMessage', + 'audioMessage', + 'videoMessage', + 'stickerMessage', + 'ptvMessage', +]; export const MessageSubtype = [ 'ephemeralMessage', diff --git a/src/cache/cacheengine.ts b/src/cache/cacheengine.ts index e09703311..cc4a1b9c4 100644 --- a/src/cache/cacheengine.ts +++ b/src/cache/cacheengine.ts @@ -10,7 +10,10 @@ const logger = new Logger('CacheEngine'); export class CacheEngine { private engine: ICache; - constructor(private readonly configService: ConfigService, module: string) { + constructor( + private readonly configService: ConfigService, + module: string, + ) { const cacheConf = configService.get('CACHE'); if (cacheConf?.REDIS?.ENABLED && cacheConf?.REDIS?.URI !== '') { diff --git a/src/cache/localcache.ts b/src/cache/localcache.ts index d926bdd9b..f7769e584 100644 --- a/src/cache/localcache.ts +++ b/src/cache/localcache.ts @@ -9,7 +9,10 @@ export class LocalCache implements ICache { private conf: CacheConfLocal; static localCache = new NodeCache(); - constructor(private readonly configService: ConfigService, private readonly module: string) { + constructor( + private readonly configService: ConfigService, + private readonly module: string, + ) { this.conf = this.configService.get('CACHE')?.LOCAL; } @@ -50,7 +53,7 @@ export class LocalCache implements ICache { async hGet(key: string, field: string) { try { - const data = LocalCache.localCache.get(this.buildKey(key)) as Object; + const data = LocalCache.localCache.get(this.buildKey(key)) as object; if (data && field in data) { return JSON.parse(data[field], BufferJSON.reviver); @@ -81,7 +84,7 @@ export class LocalCache implements ICache { async hDelete(key: string, field: string) { try { - const data = LocalCache.localCache.get(this.buildKey(key)) as Object; + const data = LocalCache.localCache.get(this.buildKey(key)) as object; if (data && field in data) { delete data[field]; diff --git a/src/cache/rediscache.ts b/src/cache/rediscache.ts index 67c21c378..1ec67e760 100644 --- a/src/cache/rediscache.ts +++ b/src/cache/rediscache.ts @@ -11,7 +11,10 @@ export class RedisCache implements ICache { private client: RedisClientType; private conf: CacheConfRedis; - constructor(private readonly configService: ConfigService, private readonly module: string) { + constructor( + private readonly configService: ConfigService, + private readonly module: string, + ) { this.conf = this.configService.get('CACHE')?.REDIS; this.client = redisClient.getConnection(); } diff --git a/src/config/env.config.ts b/src/config/env.config.ts index a46fb2aa3..7c4e382e7 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -4,6 +4,7 @@ import dotenv from 'dotenv'; dotenv.config(); export type HttpServer = { + NAME: string; TYPE: 'http' | 'https'; PORT: number; URL: string; @@ -72,6 +73,7 @@ export type EventsRabbitmq = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -94,22 +96,95 @@ export type EventsRabbitmq = { export type Rabbitmq = { ENABLED: boolean; URI: string; + FRAME_MAX: number; EXCHANGE_NAME: string; GLOBAL_ENABLED: boolean; EVENTS: EventsRabbitmq; + PREFIX_KEY?: string; +}; + +export type Nats = { + ENABLED: boolean; + URI: string; + EXCHANGE_NAME: string; + GLOBAL_ENABLED: boolean; + EVENTS: EventsRabbitmq; + PREFIX_KEY?: string; }; export type Sqs = { ENABLED: boolean; + GLOBAL_ENABLED: boolean; + GLOBAL_FORCE_SINGLE_QUEUE: boolean; + GLOBAL_PREFIX_NAME: string; ACCESS_KEY_ID: string; SECRET_ACCESS_KEY: string; ACCOUNT_ID: string; REGION: string; + MAX_PAYLOAD_SIZE: number; + EVENTS: { + APPLICATION_STARTUP: boolean; + CALL: boolean; + CHATS_DELETE: boolean; + CHATS_SET: boolean; + CHATS_UPDATE: boolean; + CHATS_UPSERT: boolean; + CONNECTION_UPDATE: boolean; + CONTACTS_SET: boolean; + CONTACTS_UPDATE: boolean; + CONTACTS_UPSERT: boolean; + GROUP_PARTICIPANTS_UPDATE: boolean; + GROUPS_UPDATE: boolean; + GROUPS_UPSERT: boolean; + LABELS_ASSOCIATION: boolean; + LABELS_EDIT: boolean; + LOGOUT_INSTANCE: boolean; + MESSAGES_DELETE: boolean; + MESSAGES_EDITED: boolean; + MESSAGES_SET: boolean; + MESSAGES_UPDATE: boolean; + MESSAGES_UPSERT: boolean; + PRESENCE_UPDATE: boolean; + QRCODE_UPDATED: boolean; + REMOVE_INSTANCE: boolean; + SEND_MESSAGE: boolean; + TYPEBOT_CHANGE_STATUS: boolean; + TYPEBOT_START: boolean; + }; +}; + +export type Kafka = { + ENABLED: boolean; + CLIENT_ID: string; + BROKERS: string[]; + CONNECTION_TIMEOUT: number; + REQUEST_TIMEOUT: number; + GLOBAL_ENABLED: boolean; + CONSUMER_GROUP_ID: string; + TOPIC_PREFIX: string; + NUM_PARTITIONS: number; + REPLICATION_FACTOR: number; + AUTO_CREATE_TOPICS: boolean; + EVENTS: EventsRabbitmq; + SASL?: { + ENABLED: boolean; + MECHANISM: string; + USERNAME: string; + PASSWORD: string; + }; + SSL?: { + ENABLED: boolean; + REJECT_UNAUTHORIZED: boolean; + CA?: string; + KEY?: string; + CERT?: string; + }; }; export type Websocket = { ENABLED: boolean; GLOBAL_EVENTS: boolean; + ALLOWED_HOSTS?: string; }; export type WaBusiness = { @@ -130,6 +205,7 @@ export type EventsWebhook = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -162,6 +238,7 @@ export type EventsPusher = { MESSAGES_UPDATE: boolean; MESSAGES_DELETE: boolean; SEND_MESSAGE: boolean; + SEND_MESSAGE_UPDATE: boolean; CONTACTS_SET: boolean; CONTACTS_UPDATE: boolean; CONTACTS_UPSERT: boolean; @@ -219,9 +296,23 @@ export type CacheConfLocal = { TTL: number; }; export type SslConf = { PRIVKEY: string; FULLCHAIN: string }; -export type Webhook = { GLOBAL?: GlobalWebhook; EVENTS: EventsWebhook }; +export type Webhook = { + GLOBAL?: GlobalWebhook; + EVENTS: EventsWebhook; + REQUEST?: { + TIMEOUT_MS?: number; + }; + RETRY?: { + MAX_ATTEMPTS?: number; + INITIAL_DELAY_SECONDS?: number; + USE_EXPONENTIAL_BACKOFF?: boolean; + MAX_DELAY_SECONDS?: number; + JITTER_FACTOR?: number; + NON_RETRYABLE_STATUS_CODES?: number[]; + }; +}; export type Pusher = { ENABLED: boolean; GLOBAL?: GlobalPusher; EVENTS: EventsPusher }; -export type ConfigSessionPhone = { CLIENT: string; NAME: string; VERSION: string }; +export type ConfigSessionPhone = { CLIENT: string; NAME: string }; export type QrCode = { LIMIT: number; COLOR: string }; export type Typebot = { ENABLED: boolean; API_VERSION: string; SEND_MEDIA_BASE64: boolean }; export type Chatwoot = { @@ -240,6 +331,9 @@ export type Chatwoot = { }; export type Openai = { ENABLED: boolean; API_KEY_GLOBAL?: string }; export type Dify = { ENABLED: boolean }; +export type N8n = { ENABLED: boolean }; +export type Evoai = { ENABLED: boolean }; +export type Flowise = { ENABLED: boolean }; export type S3 = { ACCESS_KEY: string; @@ -250,9 +344,51 @@ export type S3 = { PORT?: number; USE_SSL?: boolean; REGION?: string; + SKIP_POLICY?: boolean; + SAVE_VIDEO?: boolean; }; export type CacheConf = { REDIS: CacheConfRedis; LOCAL: CacheConfLocal }; +export type Metrics = { + ENABLED: boolean; + AUTH_REQUIRED: boolean; + USER?: string; + PASSWORD?: string; + ALLOWED_IPS?: string; +}; + +export type Telemetry = { + ENABLED: boolean; + URL?: string; +}; + +export type Proxy = { + HOST?: string; + PORT?: string; + PROTOCOL?: string; + USERNAME?: string; + PASSWORD?: string; +}; + +export type AudioConverter = { + API_URL?: string; + API_KEY?: string; +}; + +export type Facebook = { + APP_ID?: string; + CONFIG_ID?: string; + USER_TOKEN?: string; +}; + +export type Sentry = { + DSN?: string; +}; + +export type EventEmitter = { + MAX_LISTENERS: number; +}; + export type Production = boolean; export interface Env { @@ -262,7 +398,9 @@ export interface Env { PROVIDER: ProviderSession; DATABASE: Database; RABBITMQ: Rabbitmq; + NATS: Nats; SQS: Sqs; + KAFKA: Kafka; WEBSOCKET: Websocket; WA_BUSINESS: WaBusiness; LOG: Log; @@ -277,9 +415,19 @@ export interface Env { CHATWOOT: Chatwoot; OPENAI: Openai; DIFY: Dify; + N8N: N8n; + EVOAI: Evoai; + FLOWISE: Flowise; CACHE: CacheConf; S3?: S3; AUTHENTICATION: Auth; + METRICS: Metrics; + TELEMETRY: Telemetry; + PROXY: Proxy; + AUDIO_CONVERTER: AudioConverter; + FACEBOOK: Facebook; + SENTRY: Sentry; + EVENT_EMITTER: EventEmitter; PRODUCTION?: Production; } @@ -308,6 +456,7 @@ export class ConfigService { private envProcess(): Env { return { SERVER: { + NAME: process.env?.SERVER_NAME || 'evolution', TYPE: (process.env.SERVER_TYPE as 'http' | 'https') || 'http', PORT: Number.parseInt(process.env.SERVER_PORT) || 8080, URL: process.env.SERVER_URL, @@ -355,8 +504,10 @@ export class ConfigService { RABBITMQ: { ENABLED: process.env?.RABBITMQ_ENABLED === 'true', GLOBAL_ENABLED: process.env?.RABBITMQ_GLOBAL_ENABLED === 'true', + PREFIX_KEY: process.env?.RABBITMQ_PREFIX_KEY, EXCHANGE_NAME: process.env?.RABBITMQ_EXCHANGE_NAME || 'evolution_exchange', URI: process.env.RABBITMQ_URI || '', + FRAME_MAX: Number.parseInt(process.env.RABBITMQ_FRAME_MAX) || 8192, EVENTS: { APPLICATION_STARTUP: process.env?.RABBITMQ_EVENTS_APPLICATION_STARTUP === 'true', INSTANCE_CREATE: process.env?.RABBITMQ_EVENTS_INSTANCE_CREATE === 'true', @@ -368,6 +519,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.RABBITMQ_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.RABBITMQ_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.RABBITMQ_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.RABBITMQ_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.RABBITMQ_EVENTS_CONTACTS_UPSERT === 'true', @@ -387,16 +539,149 @@ export class ConfigService { TYPEBOT_CHANGE_STATUS: process.env?.RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS === 'true', }, }, + NATS: { + ENABLED: process.env?.NATS_ENABLED === 'true', + GLOBAL_ENABLED: process.env?.NATS_GLOBAL_ENABLED === 'true', + PREFIX_KEY: process.env?.NATS_PREFIX_KEY, + EXCHANGE_NAME: process.env?.NATS_EXCHANGE_NAME || 'evolution_exchange', + URI: process.env.NATS_URI || '', + EVENTS: { + APPLICATION_STARTUP: process.env?.NATS_EVENTS_APPLICATION_STARTUP === 'true', + INSTANCE_CREATE: process.env?.NATS_EVENTS_INSTANCE_CREATE === 'true', + INSTANCE_DELETE: process.env?.NATS_EVENTS_INSTANCE_DELETE === 'true', + QRCODE_UPDATED: process.env?.NATS_EVENTS_QRCODE_UPDATED === 'true', + MESSAGES_SET: process.env?.NATS_EVENTS_MESSAGES_SET === 'true', + MESSAGES_UPSERT: process.env?.NATS_EVENTS_MESSAGES_UPSERT === 'true', + MESSAGES_EDITED: process.env?.NATS_EVENTS_MESSAGES_EDITED === 'true', + MESSAGES_UPDATE: process.env?.NATS_EVENTS_MESSAGES_UPDATE === 'true', + MESSAGES_DELETE: process.env?.NATS_EVENTS_MESSAGES_DELETE === 'true', + SEND_MESSAGE: process.env?.NATS_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.NATS_EVENTS_SEND_MESSAGE_UPDATE === 'true', + CONTACTS_SET: process.env?.NATS_EVENTS_CONTACTS_SET === 'true', + CONTACTS_UPDATE: process.env?.NATS_EVENTS_CONTACTS_UPDATE === 'true', + CONTACTS_UPSERT: process.env?.NATS_EVENTS_CONTACTS_UPSERT === 'true', + PRESENCE_UPDATE: process.env?.NATS_EVENTS_PRESENCE_UPDATE === 'true', + CHATS_SET: process.env?.NATS_EVENTS_CHATS_SET === 'true', + CHATS_UPDATE: process.env?.NATS_EVENTS_CHATS_UPDATE === 'true', + CHATS_UPSERT: process.env?.NATS_EVENTS_CHATS_UPSERT === 'true', + CHATS_DELETE: process.env?.NATS_EVENTS_CHATS_DELETE === 'true', + CONNECTION_UPDATE: process.env?.NATS_EVENTS_CONNECTION_UPDATE === 'true', + LABELS_EDIT: process.env?.NATS_EVENTS_LABELS_EDIT === 'true', + LABELS_ASSOCIATION: process.env?.NATS_EVENTS_LABELS_ASSOCIATION === 'true', + GROUPS_UPSERT: process.env?.NATS_EVENTS_GROUPS_UPSERT === 'true', + GROUP_UPDATE: process.env?.NATS_EVENTS_GROUPS_UPDATE === 'true', + GROUP_PARTICIPANTS_UPDATE: process.env?.NATS_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true', + CALL: process.env?.NATS_EVENTS_CALL === 'true', + TYPEBOT_START: process.env?.NATS_EVENTS_TYPEBOT_START === 'true', + TYPEBOT_CHANGE_STATUS: process.env?.NATS_EVENTS_TYPEBOT_CHANGE_STATUS === 'true', + }, + }, SQS: { ENABLED: process.env?.SQS_ENABLED === 'true', + GLOBAL_ENABLED: process.env?.SQS_GLOBAL_ENABLED === 'true', + GLOBAL_FORCE_SINGLE_QUEUE: process.env?.SQS_GLOBAL_FORCE_SINGLE_QUEUE === 'true', + GLOBAL_PREFIX_NAME: process.env?.SQS_GLOBAL_PREFIX_NAME || 'global', ACCESS_KEY_ID: process.env.SQS_ACCESS_KEY_ID || '', SECRET_ACCESS_KEY: process.env.SQS_SECRET_ACCESS_KEY || '', ACCOUNT_ID: process.env.SQS_ACCOUNT_ID || '', REGION: process.env.SQS_REGION || '', + MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE ?? '1048576'), + EVENTS: { + APPLICATION_STARTUP: process.env?.SQS_GLOBAL_APPLICATION_STARTUP === 'true', + CALL: process.env?.SQS_GLOBAL_CALL === 'true', + CHATS_DELETE: process.env?.SQS_GLOBAL_CHATS_DELETE === 'true', + CHATS_SET: process.env?.SQS_GLOBAL_CHATS_SET === 'true', + CHATS_UPDATE: process.env?.SQS_GLOBAL_CHATS_UPDATE === 'true', + CHATS_UPSERT: process.env?.SQS_GLOBAL_CHATS_UPSERT === 'true', + CONNECTION_UPDATE: process.env?.SQS_GLOBAL_CONNECTION_UPDATE === 'true', + CONTACTS_SET: process.env?.SQS_GLOBAL_CONTACTS_SET === 'true', + CONTACTS_UPDATE: process.env?.SQS_GLOBAL_CONTACTS_UPDATE === 'true', + CONTACTS_UPSERT: process.env?.SQS_GLOBAL_CONTACTS_UPSERT === 'true', + GROUP_PARTICIPANTS_UPDATE: process.env?.SQS_GLOBAL_GROUP_PARTICIPANTS_UPDATE === 'true', + GROUPS_UPDATE: process.env?.SQS_GLOBAL_GROUPS_UPDATE === 'true', + GROUPS_UPSERT: process.env?.SQS_GLOBAL_GROUPS_UPSERT === 'true', + LABELS_ASSOCIATION: process.env?.SQS_GLOBAL_LABELS_ASSOCIATION === 'true', + LABELS_EDIT: process.env?.SQS_GLOBAL_LABELS_EDIT === 'true', + LOGOUT_INSTANCE: process.env?.SQS_GLOBAL_LOGOUT_INSTANCE === 'true', + MESSAGES_DELETE: process.env?.SQS_GLOBAL_MESSAGES_DELETE === 'true', + MESSAGES_EDITED: process.env?.SQS_GLOBAL_MESSAGES_EDITED === 'true', + MESSAGES_SET: process.env?.SQS_GLOBAL_MESSAGES_SET === 'true', + MESSAGES_UPDATE: process.env?.SQS_GLOBAL_MESSAGES_UPDATE === 'true', + MESSAGES_UPSERT: process.env?.SQS_GLOBAL_MESSAGES_UPSERT === 'true', + PRESENCE_UPDATE: process.env?.SQS_GLOBAL_PRESENCE_UPDATE === 'true', + QRCODE_UPDATED: process.env?.SQS_GLOBAL_QRCODE_UPDATED === 'true', + REMOVE_INSTANCE: process.env?.SQS_GLOBAL_REMOVE_INSTANCE === 'true', + SEND_MESSAGE: process.env?.SQS_GLOBAL_SEND_MESSAGE === 'true', + TYPEBOT_CHANGE_STATUS: process.env?.SQS_GLOBAL_TYPEBOT_CHANGE_STATUS === 'true', + TYPEBOT_START: process.env?.SQS_GLOBAL_TYPEBOT_START === 'true', + }, + }, + KAFKA: { + ENABLED: process.env?.KAFKA_ENABLED === 'true', + CLIENT_ID: process.env?.KAFKA_CLIENT_ID || 'evolution-api', + BROKERS: process.env?.KAFKA_BROKERS?.split(',') || ['localhost:9092'], + CONNECTION_TIMEOUT: Number.parseInt(process.env?.KAFKA_CONNECTION_TIMEOUT || '3000'), + REQUEST_TIMEOUT: Number.parseInt(process.env?.KAFKA_REQUEST_TIMEOUT || '30000'), + GLOBAL_ENABLED: process.env?.KAFKA_GLOBAL_ENABLED === 'true', + CONSUMER_GROUP_ID: process.env?.KAFKA_CONSUMER_GROUP_ID || 'evolution-api-consumers', + TOPIC_PREFIX: process.env?.KAFKA_TOPIC_PREFIX || 'evolution', + NUM_PARTITIONS: Number.parseInt(process.env?.KAFKA_NUM_PARTITIONS || '1'), + REPLICATION_FACTOR: Number.parseInt(process.env?.KAFKA_REPLICATION_FACTOR || '1'), + AUTO_CREATE_TOPICS: process.env?.KAFKA_AUTO_CREATE_TOPICS === 'true', + EVENTS: { + APPLICATION_STARTUP: process.env?.KAFKA_EVENTS_APPLICATION_STARTUP === 'true', + INSTANCE_CREATE: process.env?.KAFKA_EVENTS_INSTANCE_CREATE === 'true', + INSTANCE_DELETE: process.env?.KAFKA_EVENTS_INSTANCE_DELETE === 'true', + QRCODE_UPDATED: process.env?.KAFKA_EVENTS_QRCODE_UPDATED === 'true', + MESSAGES_SET: process.env?.KAFKA_EVENTS_MESSAGES_SET === 'true', + MESSAGES_UPSERT: process.env?.KAFKA_EVENTS_MESSAGES_UPSERT === 'true', + MESSAGES_EDITED: process.env?.KAFKA_EVENTS_MESSAGES_EDITED === 'true', + MESSAGES_UPDATE: process.env?.KAFKA_EVENTS_MESSAGES_UPDATE === 'true', + MESSAGES_DELETE: process.env?.KAFKA_EVENTS_MESSAGES_DELETE === 'true', + SEND_MESSAGE: process.env?.KAFKA_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.KAFKA_EVENTS_SEND_MESSAGE_UPDATE === 'true', + CONTACTS_SET: process.env?.KAFKA_EVENTS_CONTACTS_SET === 'true', + CONTACTS_UPSERT: process.env?.KAFKA_EVENTS_CONTACTS_UPSERT === 'true', + CONTACTS_UPDATE: process.env?.KAFKA_EVENTS_CONTACTS_UPDATE === 'true', + PRESENCE_UPDATE: process.env?.KAFKA_EVENTS_PRESENCE_UPDATE === 'true', + CHATS_SET: process.env?.KAFKA_EVENTS_CHATS_SET === 'true', + CHATS_UPSERT: process.env?.KAFKA_EVENTS_CHATS_UPSERT === 'true', + CHATS_UPDATE: process.env?.KAFKA_EVENTS_CHATS_UPDATE === 'true', + CHATS_DELETE: process.env?.KAFKA_EVENTS_CHATS_DELETE === 'true', + CONNECTION_UPDATE: process.env?.KAFKA_EVENTS_CONNECTION_UPDATE === 'true', + LABELS_EDIT: process.env?.KAFKA_EVENTS_LABELS_EDIT === 'true', + LABELS_ASSOCIATION: process.env?.KAFKA_EVENTS_LABELS_ASSOCIATION === 'true', + GROUPS_UPSERT: process.env?.KAFKA_EVENTS_GROUPS_UPSERT === 'true', + GROUP_UPDATE: process.env?.KAFKA_EVENTS_GROUPS_UPDATE === 'true', + GROUP_PARTICIPANTS_UPDATE: process.env?.KAFKA_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true', + CALL: process.env?.KAFKA_EVENTS_CALL === 'true', + TYPEBOT_START: process.env?.KAFKA_EVENTS_TYPEBOT_START === 'true', + TYPEBOT_CHANGE_STATUS: process.env?.KAFKA_EVENTS_TYPEBOT_CHANGE_STATUS === 'true', + }, + SASL: + process.env?.KAFKA_SASL_ENABLED === 'true' + ? { + ENABLED: true, + MECHANISM: process.env?.KAFKA_SASL_MECHANISM || 'plain', + USERNAME: process.env?.KAFKA_SASL_USERNAME || '', + PASSWORD: process.env?.KAFKA_SASL_PASSWORD || '', + } + : undefined, + SSL: + process.env?.KAFKA_SSL_ENABLED === 'true' + ? { + ENABLED: true, + REJECT_UNAUTHORIZED: process.env?.KAFKA_SSL_REJECT_UNAUTHORIZED !== 'false', + CA: process.env?.KAFKA_SSL_CA, + KEY: process.env?.KAFKA_SSL_KEY, + CERT: process.env?.KAFKA_SSL_CERT, + } + : undefined, }, WEBSOCKET: { ENABLED: process.env?.WEBSOCKET_ENABLED === 'true', GLOBAL_EVENTS: process.env?.WEBSOCKET_GLOBAL_EVENTS === 'true', + ALLOWED_HOSTS: process.env?.WEBSOCKET_ALLOWED_HOSTS, }, PUSHER: { ENABLED: process.env?.PUSHER_ENABLED === 'true', @@ -419,6 +704,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.PUSHER_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.PUSHER_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.PUSHER_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.PUSHER_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.PUSHER_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.PUSHER_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.PUSHER_EVENTS_CONTACTS_UPSERT === 'true', @@ -475,6 +761,7 @@ export class ConfigService { MESSAGES_UPDATE: process.env?.WEBHOOK_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_DELETE: process.env?.WEBHOOK_EVENTS_MESSAGES_DELETE === 'true', SEND_MESSAGE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE === 'true', + SEND_MESSAGE_UPDATE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE_UPDATE === 'true', CONTACTS_SET: process.env?.WEBHOOK_EVENTS_CONTACTS_SET === 'true', CONTACTS_UPDATE: process.env?.WEBHOOK_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPSERT: process.env?.WEBHOOK_EVENTS_CONTACTS_UPSERT === 'true', @@ -495,11 +782,23 @@ export class ConfigService { ERRORS: process.env?.WEBHOOK_EVENTS_ERRORS === 'true', ERRORS_WEBHOOK: process.env?.WEBHOOK_EVENTS_ERRORS_WEBHOOK || '', }, + REQUEST: { + TIMEOUT_MS: Number.parseInt(process.env?.WEBHOOK_REQUEST_TIMEOUT_MS) || 30000, + }, + RETRY: { + MAX_ATTEMPTS: Number.parseInt(process.env?.WEBHOOK_RETRY_MAX_ATTEMPTS) || 10, + INITIAL_DELAY_SECONDS: Number.parseInt(process.env?.WEBHOOK_RETRY_INITIAL_DELAY_SECONDS) || 5, + USE_EXPONENTIAL_BACKOFF: process.env?.WEBHOOK_RETRY_USE_EXPONENTIAL_BACKOFF !== 'false', + MAX_DELAY_SECONDS: Number.parseInt(process.env?.WEBHOOK_RETRY_MAX_DELAY_SECONDS) || 300, + JITTER_FACTOR: Number.parseFloat(process.env?.WEBHOOK_RETRY_JITTER_FACTOR) || 0.2, + NON_RETRYABLE_STATUS_CODES: process.env?.WEBHOOK_RETRY_NON_RETRYABLE_STATUS_CODES?.split(',').map(Number) || [ + 400, 401, 403, 404, 422, + ], + }, }, CONFIG_SESSION_PHONE: { CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT || 'Evolution API', NAME: process.env?.CONFIG_SESSION_PHONE_NAME || 'Chrome', - VERSION: process.env?.CONFIG_SESSION_PHONE_VERSION || null, }, QRCODE: { LIMIT: Number.parseInt(process.env.QRCODE_LIMIT) || 30, @@ -531,6 +830,15 @@ export class ConfigService { DIFY: { ENABLED: process.env?.DIFY_ENABLED === 'true', }, + N8N: { + ENABLED: process.env?.N8N_ENABLED === 'true', + }, + EVOAI: { + ENABLED: process.env?.EVOAI_ENABLED === 'true', + }, + FLOWISE: { + ENABLED: process.env?.FLOWISE_ENABLED === 'true', + }, CACHE: { REDIS: { ENABLED: process.env?.CACHE_REDIS_ENABLED === 'true', @@ -553,6 +861,8 @@ export class ConfigService { PORT: Number.parseInt(process.env?.S3_PORT || '9000'), USE_SSL: process.env?.S3_USE_SSL === 'true', REGION: process.env?.S3_REGION, + SKIP_POLICY: process.env?.S3_SKIP_POLICY === 'true', + SAVE_VIDEO: process.env?.S3_SAVE_VIDEO === 'true', }, AUTHENTICATION: { API_KEY: { @@ -560,6 +870,39 @@ export class ConfigService { }, EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true', }, + METRICS: { + ENABLED: process.env?.PROMETHEUS_METRICS === 'true', + AUTH_REQUIRED: process.env?.METRICS_AUTH_REQUIRED === 'true', + USER: process.env?.METRICS_USER, + PASSWORD: process.env?.METRICS_PASSWORD, + ALLOWED_IPS: process.env?.METRICS_ALLOWED_IPS, + }, + TELEMETRY: { + ENABLED: process.env?.TELEMETRY_ENABLED === undefined || process.env?.TELEMETRY_ENABLED === 'true', + URL: process.env?.TELEMETRY_URL, + }, + PROXY: { + HOST: process.env?.PROXY_HOST, + PORT: process.env?.PROXY_PORT, + PROTOCOL: process.env?.PROXY_PROTOCOL, + USERNAME: process.env?.PROXY_USERNAME, + PASSWORD: process.env?.PROXY_PASSWORD, + }, + AUDIO_CONVERTER: { + API_URL: process.env?.API_AUDIO_CONVERTER, + API_KEY: process.env?.API_AUDIO_CONVERTER_KEY, + }, + FACEBOOK: { + APP_ID: process.env?.FACEBOOK_APP_ID, + CONFIG_ID: process.env?.FACEBOOK_CONFIG_ID, + USER_TOKEN: process.env?.FACEBOOK_USER_TOKEN, + }, + SENTRY: { + DSN: process.env?.SENTRY_DSN, + }, + EVENT_EMITTER: { + MAX_LISTENERS: Number.parseInt(process.env?.EVENT_EMITTER_MAX_LISTENERS) || 50, + }, }; } } diff --git a/src/config/event.config.ts b/src/config/event.config.ts index 20cd1e401..ab9d05a88 100644 --- a/src/config/event.config.ts +++ b/src/config/event.config.ts @@ -1,10 +1,11 @@ +import { configService, EventEmitter as EventEmitterConfig } from '@config/env.config'; import EventEmitter2 from 'eventemitter2'; -const maxListeners = parseInt(process.env.EVENT_EMITTER_MAX_LISTENERS, 10) || 50; +const eventEmitterConfig = configService.get('EVENT_EMITTER'); export const eventEmitter = new EventEmitter2({ delimiter: '.', newListener: false, ignoreErrors: false, - maxListeners: maxListeners, + maxListeners: eventEmitterConfig.MAX_LISTENERS, }); diff --git a/src/main.ts b/src/main.ts index 5204b6983..f1f00ba9a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,8 +1,20 @@ +// Import this first from sentry instrument! +import '@utils/instrumentSentry'; + +// Now import other modules import { ProviderFiles } from '@api/provider/sessions'; import { PrismaRepository } from '@api/repository/repository.service'; import { HttpStatus, router } from '@api/routes/index.router'; import { eventManager, waMonitor } from '@api/server.module'; -import { Auth, configService, Cors, HttpServer, ProviderSession, Webhook } from '@config/env.config'; +import { + Auth, + configService, + Cors, + HttpServer, + ProviderSession, + Sentry as SentryConfig, + Webhook, +} from '@config/env.config'; import { onUnexpectedError } from '@config/error.config'; import { Logger } from '@config/logger.config'; import { ROOT_DIR } from '@config/path.config'; @@ -14,26 +26,13 @@ import cors from 'cors'; import express, { json, NextFunction, Request, Response, urlencoded } from 'express'; import { join } from 'path'; -function initWA() { - waMonitor.loadInstance(); +async function initWA() { + await waMonitor.loadInstance(); } async function bootstrap() { const logger = new Logger('SERVER'); const app = express(); - const dsn = process.env.SENTRY_DSN; - - if (dsn) { - logger.info('Sentry - ON'); - Sentry.init({ - dsn: dsn, - environment: process.env.NODE_ENV || 'development', - tracesSampleRate: 1.0, - profilesSampleRate: 1.0, - }); - - Sentry.setupExpressErrorHandler(app); - } let providerFiles: ProviderFiles = null; if (configService.get('PROVIDER').ENABLED) { @@ -137,13 +136,32 @@ async function bootstrap() { const httpServer = configService.get('SERVER'); ServerUP.app = app; - const server = ServerUP[httpServer.TYPE]; + let server = ServerUP[httpServer.TYPE]; + + if (server === null) { + logger.warn('SSL cert load failed — falling back to HTTP.'); + logger.info("Ensure 'SSL_CONF_PRIVKEY' and 'SSL_CONF_FULLCHAIN' env vars point to valid certificate files."); + + httpServer.TYPE = 'http'; + server = ServerUP[httpServer.TYPE]; + } eventManager.init(server); + const sentryConfig = configService.get('SENTRY'); + if (sentryConfig.DSN) { + logger.info('Sentry - ON'); + + // Add this after all routes, + // but before any and other error-handling middlewares are defined + Sentry.setupExpressErrorHandler(app); + } + server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT)); - initWA(); + initWA().catch((error) => { + logger.error('Error loading instances: ' + error); + }); onUnexpectedError(); } diff --git a/src/railway.json b/src/railway.json new file mode 100644 index 000000000..86f24dc7e --- /dev/null +++ b/src/railway.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://railway.com/railway.schema.json", + "build": { + "builder": "DOCKERFILE", + "dockerfilePath": "Dockerfile" + }, + "deploy": { + "runtime": "V2", + "numReplicas": 1, + "sleepApplication": false, + "multiRegionConfig": { + "us-east4-eqdc4a": { + "numReplicas": 1 + } + }, + "restartPolicyType": "ON_FAILURE", + "restartPolicyMaxRetries": 10 + } +} diff --git a/src/utils/createJid.ts b/src/utils/createJid.ts new file mode 100644 index 000000000..a680e821e --- /dev/null +++ b/src/utils/createJid.ts @@ -0,0 +1,71 @@ +// Check if the number is MX or AR +function formatMXOrARNumber(jid: string): string { + const countryCode = jid.substring(0, 2); + + if (Number(countryCode) === 52 || Number(countryCode) === 54) { + if (jid.length === 13) { + const number = countryCode + jid.substring(3); + return number; + } + + return jid; + } + return jid; +} + +// Check if the number is br +function formatBRNumber(jid: string) { + const regexp = new RegExp(/^(\d{2})(\d{2})\d{1}(\d{8})$/); + if (regexp.test(jid)) { + const match = regexp.exec(jid); + if (match && match[1] === '55') { + const joker = Number.parseInt(match[3][0]); + const ddd = Number.parseInt(match[2]); + if (joker < 7 || ddd < 31) { + return match[0]; + } + return match[1] + match[2] + match[3]; + } + return jid; + } else { + return jid; + } +} + +export function createJid(number: string): string { + number = number.replace(/:\d+/, ''); + + if (number.includes('@g.us') || number.includes('@s.whatsapp.net') || number.includes('@lid')) { + return number; + } + + if (number.includes('@broadcast')) { + return number; + } + + number = number + ?.replace(/\s/g, '') + .replace(/\+/g, '') + .replace(/\(/g, '') + .replace(/\)/g, '') + .split(':')[0] + .split('@')[0]; + + if (number.includes('-') && number.length >= 24) { + number = number.replace(/[^\d-]/g, ''); + return `${number}@g.us`; + } + + number = number.replace(/\D/g, ''); + + if (number.length >= 18) { + number = number.replace(/[^\d-]/g, ''); + return `${number}@g.us`; + } + + number = formatMXOrARNumber(number); + + number = formatBRNumber(number); + + return `${number}@s.whatsapp.net`; +} diff --git a/src/utils/errorResponse.ts b/src/utils/errorResponse.ts new file mode 100644 index 000000000..ee36ed22c --- /dev/null +++ b/src/utils/errorResponse.ts @@ -0,0 +1,47 @@ +import { HttpStatus } from '@api/routes/index.router'; + +export interface MetaErrorResponse { + status: number; + error: string; + message: string; + details: { + whatsapp_error: string; + whatsapp_code: string | number; + error_user_title: string; + error_user_msg: string; + error_type: string; + error_subcode: number | null; + fbtrace_id: string | null; + context: string; + type: string; + }; + timestamp: string; +} + +/** + * Creates standardized error response for Meta/WhatsApp API errors + */ +export function createMetaErrorResponse(error: any, context: string): MetaErrorResponse { + // Extract Meta/WhatsApp specific error fields + const metaError = error.template || error; + const errorUserTitle = metaError.error_user_title || metaError.message || 'Unknown error'; + const errorUserMsg = metaError.error_user_msg || metaError.message || 'Unknown error'; + + return { + status: HttpStatus.BAD_REQUEST, + error: 'Bad Request', + message: errorUserTitle, + details: { + whatsapp_error: errorUserMsg, + whatsapp_code: metaError.code || 'UNKNOWN_ERROR', + error_user_title: errorUserTitle, + error_user_msg: errorUserMsg, + error_type: metaError.type || 'UNKNOWN', + error_subcode: metaError.error_subcode || null, + fbtrace_id: metaError.fbtrace_id || null, + context, + type: 'whatsapp_api_error', + }, + timestamp: new Date().toISOString(), + }; +} diff --git a/src/utils/fetchLatestWaWebVersion.ts b/src/utils/fetchLatestWaWebVersion.ts new file mode 100644 index 000000000..6dcfb797e --- /dev/null +++ b/src/utils/fetchLatestWaWebVersion.ts @@ -0,0 +1,37 @@ +import axios, { AxiosRequestConfig } from 'axios'; +import { fetchLatestBaileysVersion, WAVersion } from 'baileys'; + +export const fetchLatestWaWebVersion = async (options: AxiosRequestConfig<{}>) => { + try { + const { data } = await axios.get('https://web.whatsapp.com/sw.js', { + ...options, + responseType: 'json', + }); + + const regex = /\\?"client_revision\\?":\s*(\d+)/; + const match = data.match(regex); + + if (!match?.[1]) { + return { + version: (await fetchLatestBaileysVersion()).version as WAVersion, + isLatest: false, + error: { + message: 'Could not find client revision in the fetched content', + }, + }; + } + + const clientRevision = match[1]; + + return { + version: [2, 3000, +clientRevision] as WAVersion, + isLatest: true, + }; + } catch (error) { + return { + version: (await fetchLatestBaileysVersion()).version as WAVersion, + isLatest: false, + error, + }; + } +}; diff --git a/src/utils/findBotByTrigger.ts b/src/utils/findBotByTrigger.ts index 1b8fcf3f8..eea5db823 100644 --- a/src/utils/findBotByTrigger.ts +++ b/src/utils/findBotByTrigger.ts @@ -1,21 +1,20 @@ import { advancedOperatorsSearch } from './advancedOperatorsSearch'; -export const findBotByTrigger = async ( - botRepository: any, - settingsRepository: any, - content: string, - instanceId: string, -) => { - // Check for triggerType 'all' - const findTriggerAll = await botRepository.findFirst({ +export const findBotByTrigger = async (botRepository: any, content: string, instanceId: string) => { + // Check for triggerType 'all' or 'none' (both should match any message) + const findTriggerAllOrNone = await botRepository.findFirst({ where: { enabled: true, - triggerType: 'all', + triggerType: { + in: ['all', 'none'], + }, instanceId: instanceId, }, }); - if (findTriggerAll) return findTriggerAll; + if (findTriggerAllOrNone) { + return findTriggerAllOrNone; + } const findTriggerAdvanced = await botRepository.findMany({ where: { @@ -41,7 +40,9 @@ export const findBotByTrigger = async ( }, }); - if (findTriggerEquals) return findTriggerEquals; + if (findTriggerEquals) { + return findTriggerEquals; + } // Check for regex match const findRegex = await botRepository.findMany({ diff --git a/src/utils/getConversationMessage.ts b/src/utils/getConversationMessage.ts index c1d93f58d..eca23b454 100644 --- a/src/utils/getConversationMessage.ts +++ b/src/utils/getConversationMessage.ts @@ -3,27 +3,34 @@ import { configService, S3 } from '@config/env.config'; const getTypeMessage = (msg: any) => { let mediaId: string; - if (configService.get('S3').ENABLE) mediaId = msg.message.mediaUrl; - else mediaId = msg.key.id; + if ( + configService.get('S3').ENABLE && + (configService.get('S3').SAVE_VIDEO || + (msg?.message?.videoMessage === undefined && + msg?.message?.viewOnceMessageV2?.message?.videoMessage === undefined)) + ) + mediaId = msg.message?.mediaUrl; + else mediaId = msg.key?.id; const types = { conversation: msg?.message?.conversation, extendedTextMessage: msg?.message?.extendedTextMessage?.text, contactMessage: msg?.message?.contactMessage?.displayName, - locationMessage: msg?.message?.locationMessage?.degreesLatitude, + locationMessage: msg?.message?.locationMessage?.degreesLatitude.toString(), viewOnceMessageV2: msg?.message?.viewOnceMessageV2?.message?.imageMessage?.url || msg?.message?.viewOnceMessageV2?.message?.videoMessage?.url || msg?.message?.viewOnceMessageV2?.message?.audioMessage?.url, - listResponseMessage: msg?.message?.listResponseMessage?.title, + listResponseMessage: msg?.message?.listResponseMessage?.title || msg?.listResponseMessage?.title, responseRowId: msg?.message?.listResponseMessage?.singleSelectReply?.selectedRowId, - templateButtonReplyMessage: msg?.message?.templateButtonReplyMessage?.selectedId, + templateButtonReplyMessage: + msg?.message?.templateButtonReplyMessage?.selectedId || msg?.message?.buttonsResponseMessage?.selectedButtonId, // Medias audioMessage: msg?.message?.speechToText ? msg?.message?.speechToText : msg?.message?.audioMessage - ? `audioMessage|${mediaId}` - : undefined, + ? `audioMessage|${mediaId}` + : undefined, imageMessage: msg?.message?.imageMessage ? `imageMessage|${mediaId}${msg?.message?.imageMessage?.caption ? `|${msg?.message?.imageMessage?.caption}` : ''}` : undefined, diff --git a/src/utils/i18n.ts b/src/utils/i18n.ts index b26a5ef03..1e2f8a1bd 100644 --- a/src/utils/i18n.ts +++ b/src/utils/i18n.ts @@ -12,8 +12,9 @@ const resources: any = {}; languages.forEach((language) => { const languagePath = path.join(translationsPath, `${language}.json`); if (fs.existsSync(languagePath)) { + const translationContent = fs.readFileSync(languagePath, 'utf8'); resources[language] = { - translation: require(languagePath), + translation: JSON.parse(translationContent), }; } }); diff --git a/src/utils/instrumentSentry.ts b/src/utils/instrumentSentry.ts new file mode 100644 index 000000000..a91eb7729 --- /dev/null +++ b/src/utils/instrumentSentry.ts @@ -0,0 +1,13 @@ +import { configService, Sentry as SentryConfig } from '@config/env.config'; +import * as Sentry from '@sentry/node'; + +const sentryConfig = configService.get('SENTRY'); + +if (sentryConfig.DSN) { + Sentry.init({ + dsn: sentryConfig.DSN, + environment: process.env.NODE_ENV || 'development', + tracesSampleRate: 1.0, + profilesSampleRate: 1.0, + }); +} diff --git a/src/utils/makeProxyAgent.ts b/src/utils/makeProxyAgent.ts index dcf560f6d..80fa4d856 100644 --- a/src/utils/makeProxyAgent.ts +++ b/src/utils/makeProxyAgent.ts @@ -1,4 +1,7 @@ +import { socksDispatcher } from 'fetch-socks'; import { HttpsProxyAgent } from 'https-proxy-agent'; +import { SocksProxyAgent } from 'socks-proxy-agent'; +import { ProxyAgent } from 'undici'; type Proxy = { host: string; @@ -8,9 +11,39 @@ type Proxy = { username?: string; }; -export function makeProxyAgent(proxy: Proxy | string) { +function selectProxyAgent(proxyUrl: string): HttpsProxyAgent | SocksProxyAgent { + const url = new URL(proxyUrl); + + // NOTE: The following constants are not used in the function but are defined for clarity. + // When a proxy URL is used to build the URL object, the protocol returned by procotol's property contains a `:` at + // the end so, we add the protocol constants without the `:` to avoid confusion. + const PROXY_HTTP_PROTOCOL = 'http:'; + const PROXY_SOCKS_PROTOCOL = 'socks:'; + const PROXY_SOCKS5_PROTOCOL = 'socks5:'; + + switch (url.protocol) { + case PROXY_HTTP_PROTOCOL: + return new HttpsProxyAgent(url); + case PROXY_SOCKS_PROTOCOL: + case PROXY_SOCKS5_PROTOCOL: { + let urlSocks = ''; + + if (url.username && url.password) { + urlSocks = `socks://${url.username}:${url.password}@${url.hostname}:${url.port}`; + } else { + urlSocks = `socks://${url.hostname}:${url.port}`; + } + + return new SocksProxyAgent(urlSocks); + } + default: + throw new Error(`Unsupported proxy protocol: ${url.protocol}`); + } +} + +export function makeProxyAgent(proxy: Proxy | string): HttpsProxyAgent | SocksProxyAgent { if (typeof proxy === 'string') { - return new HttpsProxyAgent(proxy); + return selectProxyAgent(proxy); } const { host, password, port, protocol, username } = proxy; @@ -19,5 +52,60 @@ export function makeProxyAgent(proxy: Proxy | string) { if (username && password) { proxyUrl = `${protocol}://${username}:${password}@${host}:${port}`; } - return new HttpsProxyAgent(proxyUrl); + + return selectProxyAgent(proxyUrl); +} + +export function makeProxyAgentUndici(proxy: Proxy | string): ProxyAgent { + let proxyUrl: string; + let protocol: string; + + if (typeof proxy === 'string') { + const url = new URL(proxy); + protocol = url.protocol.replace(':', ''); + proxyUrl = proxy; + } else { + const { host, password, port, protocol: proto, username } = proxy; + protocol = (proto || 'http').replace(':', ''); + + if (protocol === 'socks') { + protocol = 'socks5'; + } + + const auth = username && password ? `${username}:${password}@` : ''; + proxyUrl = `${protocol}://${auth}${host}:${port}`; + } + + protocol = protocol.toLowerCase(); + + const PROXY_HTTP_PROTOCOL = 'http'; + const PROXY_HTTPS_PROTOCOL = 'https'; + const PROXY_SOCKS4_PROTOCOL = 'socks4'; + const PROXY_SOCKS5_PROTOCOL = 'socks5'; + + switch (protocol) { + case PROXY_HTTP_PROTOCOL: + case PROXY_HTTPS_PROTOCOL: + return new ProxyAgent(proxyUrl); + + case PROXY_SOCKS4_PROTOCOL: + case PROXY_SOCKS5_PROTOCOL: { + let type: 4 | 5 = 5; + + if (PROXY_SOCKS4_PROTOCOL === protocol) type = 4; + + const url = new URL(proxyUrl); + + return socksDispatcher({ + type: type, + host: url.hostname, + port: Number(url.port), + userId: url.username || undefined, + password: url.password || undefined, + }); + } + + default: + throw new Error(`Unsupported proxy protocol: ${protocol}`); + } } diff --git a/src/utils/onWhatsappCache.ts b/src/utils/onWhatsappCache.ts index a77ac396c..08de0714e 100644 --- a/src/utils/onWhatsappCache.ts +++ b/src/utils/onWhatsappCache.ts @@ -1,7 +1,10 @@ import { prismaRepository } from '@api/server.module'; import { configService, Database } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import dayjs from 'dayjs'; +const logger = new Logger('OnWhatsappCache'); + function getAvailableNumbers(remoteJid: string) { const numbersAvailable: string[] = []; @@ -11,6 +14,11 @@ function getAvailableNumbers(remoteJid: string) { const [number, domain] = remoteJid.split('@'); + // TODO: Se já for @lid, retornar apenas ele mesmo SEM adicionar @domain novamente + if (domain === 'lid' || domain === 'g.us') { + return [remoteJid]; // Retorna direto para @lid e @g.us + } + // Brazilian numbers if (remoteJid.startsWith('55')) { const numberWithDigit = @@ -47,27 +55,128 @@ function getAvailableNumbers(remoteJid: string) { numbersAvailable.push(remoteJid); } + // TODO: Adiciona @domain apenas para números que não são @lid return numbersAvailable.map((number) => `${number}@${domain}`); } interface ISaveOnWhatsappCacheParams { remoteJid: string; + remoteJidAlt?: string; + lid?: 'lid' | undefined; } + +function normalizeJid(jid: string | null | undefined): string | null { + if (!jid) return null; + return jid.startsWith('+') ? jid.slice(1) : jid; +} + export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) { - if (configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { - const upsertsQuery = data.map((item) => { - const remoteJid = item.remoteJid.startsWith('+') ? item.remoteJid.slice(1) : item.remoteJid; - const numbersAvailable = getAvailableNumbers(remoteJid); - - return prismaRepository.isOnWhatsapp.upsert({ - create: { remoteJid: remoteJid, jidOptions: numbersAvailable.join(',') }, - update: { jidOptions: numbersAvailable.join(',') }, - where: { remoteJid: remoteJid }, + if (!configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { + return; + } + + // Processa todos os itens em paralelo para melhor performance + const processingPromises = data.map(async (item) => { + try { + const remoteJid = normalizeJid(item.remoteJid); + if (!remoteJid) { + logger.warn('[saveOnWhatsappCache] Item skipped, missing remoteJid.'); + return; + } + + const altJidNormalized = normalizeJid(item.remoteJidAlt); + const lidAltJid = altJidNormalized && altJidNormalized.includes('@lid') ? altJidNormalized : null; + + const baseJids = [remoteJid]; // Garante que o remoteJid esteja na lista inicial + if (lidAltJid) { + baseJids.push(lidAltJid); + } + + const expandedJids = baseJids.flatMap((jid) => getAvailableNumbers(jid)); + + // 1. Busca entrada por jidOptions e também remoteJid + // Às vezes acontece do remoteJid atual NÃO ESTAR no jidOptions ainda, ocasionando o erro: + // 'Unique constraint failed on the fields: (`remoteJid`)' + // Isso acontece principalmente em grupos que possuem o número do criador no ID (ex.: '559911223345-1234567890@g.us') + const existingRecord = await prismaRepository.isOnWhatsapp.findFirst({ + where: { + OR: [ + ...expandedJids.map((jid) => ({ jidOptions: { contains: jid } })), + { remoteJid: remoteJid }, // TODO: Descobrir o motivo que causa o remoteJid não estar (às vezes) incluso na lista de jidOptions + ], + }, }); - }); - await prismaRepository.$transaction(upsertsQuery); - } + logger.verbose( + `[saveOnWhatsappCache] Register exists for [${expandedJids.join(',')}]? => ${existingRecord ? existingRecord.remoteJid : 'Not found'}`, + ); + + // 2. Unifica todos os JIDs usando um Set para garantir valores únicos + const finalJidOptions = new Set(expandedJids); + + if (lidAltJid) { + finalJidOptions.add(lidAltJid); + } + + if (existingRecord?.jidOptions) { + existingRecord.jidOptions.split(',').forEach((jid) => finalJidOptions.add(jid)); + } + + // 3. Prepara o payload final + // Ordena os JIDs para garantir consistência na string final + const sortedJidOptions = [...finalJidOptions].sort(); + const newJidOptionsString = sortedJidOptions.join(','); + const newLid = item.lid === 'lid' || item.remoteJid?.includes('@lid') ? 'lid' : null; + + const dataPayload = { + remoteJid: remoteJid, + jidOptions: newJidOptionsString, + lid: newLid, + }; + + // 4. Decide entre Criar ou Atualizar + if (existingRecord) { + // Compara a string de JIDs ordenada existente com a nova + const existingJidOptionsString = existingRecord.jidOptions + ? existingRecord.jidOptions.split(',').sort().join(',') + : ''; + + const isDataSame = + existingRecord.remoteJid === dataPayload.remoteJid && + existingJidOptionsString === dataPayload.jidOptions && + existingRecord.lid === dataPayload.lid; + + if (isDataSame) { + logger.verbose(`[saveOnWhatsappCache] Data for ${remoteJid} is already up-to-date. Skipping update.`); + return; // Pula para o próximo item + } + + // Os dados são diferentes, então atualiza + logger.verbose( + `[saveOnWhatsappCache] Register exists, updating: remoteJid=${remoteJid}, jidOptions=${dataPayload.jidOptions}, lid=${dataPayload.lid}`, + ); + await prismaRepository.isOnWhatsapp.update({ + where: { id: existingRecord.id }, + data: dataPayload, + }); + } else { + // Cria nova entrada + logger.verbose( + `[saveOnWhatsappCache] Register does not exist, creating: remoteJid=${remoteJid}, jidOptions=${dataPayload.jidOptions}, lid=${dataPayload.lid}`, + ); + await prismaRepository.isOnWhatsapp.create({ + data: dataPayload, + }); + } + } catch (e) { + // Loga o erro mas não para a execução dos outros promises + logger.error(`[saveOnWhatsappCache] Error processing item for ${item.remoteJid}: `); + logger.error(e); + } + }); + + // Espera todas as operações paralelas terminarem + await Promise.allSettled(processingPromises); } export async function getOnWhatsappCache(remoteJids: string[]) { @@ -75,6 +184,7 @@ export async function getOnWhatsappCache(remoteJids: string[]) { remoteJid: string; number: string; jidOptions: string[]; + lid?: string; }[] = []; if (configService.get('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { @@ -93,6 +203,7 @@ export async function getOnWhatsappCache(remoteJids: string[]) { remoteJid: item.remoteJid, number: item.remoteJid.split('@')[0], jidOptions: item.jidOptions.split(','), + lid: item.lid, })); } diff --git a/src/utils/sendTelemetry.ts b/src/utils/sendTelemetry.ts index 037ca55d5..b2ebe05af 100644 --- a/src/utils/sendTelemetry.ts +++ b/src/utils/sendTelemetry.ts @@ -1,3 +1,4 @@ +import { configService, Telemetry } from '@config/env.config'; import axios from 'axios'; import fs from 'fs'; @@ -10,9 +11,9 @@ export interface TelemetryData { } export const sendTelemetry = async (route: string): Promise => { - const enabled = process.env.TELEMETRY_ENABLED === undefined || process.env.TELEMETRY_ENABLED === 'true'; + const telemetryConfig = configService.get('TELEMETRY'); - if (!enabled) { + if (!telemetryConfig.ENABLED) { return; } @@ -27,9 +28,7 @@ export const sendTelemetry = async (route: string): Promise => { }; const url = - process.env.TELEMETRY_URL && process.env.TELEMETRY_URL !== '' - ? process.env.TELEMETRY_URL - : 'https://log.evolution-api.com/telemetry'; + telemetryConfig.URL && telemetryConfig.URL !== '' ? telemetryConfig.URL : 'https://log.evolution-api.com/telemetry'; axios .post(url, telemetry) diff --git a/src/utils/use-multi-file-auth-state-prisma.ts b/src/utils/use-multi-file-auth-state-prisma.ts index 02f96f151..d09078023 100644 --- a/src/utils/use-multi-file-auth-state-prisma.ts +++ b/src/utils/use-multi-file-auth-state-prisma.ts @@ -1,24 +1,26 @@ import { prismaRepository } from '@api/server.module'; import { CacheService } from '@api/services/cache.service'; +import { CacheConf, configService } from '@config/env.config'; +import { Logger } from '@config/logger.config'; import { INSTANCE_DIR } from '@config/path.config'; import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys'; import fs from 'fs/promises'; import path from 'path'; -// const fixFileName = (file: string): string | undefined => { -// if (!file) { -// return undefined; -// } -// const replacedSlash = file.replace(/\//g, '__'); -// const replacedColon = replacedSlash.replace(/:/g, '-'); -// return replacedColon; -// }; +const fixFileName = (file: string): string | undefined => { + if (!file) { + return undefined; + } + const replacedSlash = file.replace(/\//g, '__'); + const replacedColon = replacedSlash.replace(/:/g, '-'); + return replacedColon; +}; export async function keyExists(sessionId: string): Promise { try { const key = await prismaRepository.session.findUnique({ where: { sessionId: sessionId } }); return !!key; - } catch (error) { + } catch { return false; } } @@ -37,7 +39,7 @@ export async function saveKey(sessionId: string, keyJson: any): Promise { where: { sessionId: sessionId }, data: { creds: JSON.stringify(keyJson) }, }); - } catch (error) { + } catch { return null; } } @@ -48,7 +50,7 @@ export async function getAuthKey(sessionId: string): Promise { if (!register) return null; const auth = await prismaRepository.session.findUnique({ where: { sessionId: sessionId } }); return JSON.parse(auth?.creds); - } catch (error) { + } catch { return null; } } @@ -58,19 +60,21 @@ async function deleteAuthKey(sessionId: string): Promise { const register = await keyExists(sessionId); if (!register) return; await prismaRepository.session.delete({ where: { sessionId: sessionId } }); - } catch (error) { + } catch { + return; + } +} + +async function fileExists(file: string): Promise { + try { + const stat = await fs.stat(file); + if (stat.isFile()) return true; + } catch { return; } } -// async function fileExists(file: string): Promise { -// try { -// const stat = await fs.stat(file); -// if (stat.isFile()) return true; -// } catch (error) { -// return; -// } -// } +const logger = new Logger('useMultiFileAuthStatePrisma'); export default async function useMultiFileAuthStatePrisma( sessionId: string, @@ -78,18 +82,23 @@ export default async function useMultiFileAuthStatePrisma( ): Promise<{ state: AuthenticationState; saveCreds: () => Promise; + removeCreds: () => Promise; }> { const localFolder = path.join(INSTANCE_DIR, sessionId); - // const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json'); + const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json'); await fs.mkdir(localFolder, { recursive: true }); async function writeData(data: any, key: string): Promise { const dataString = JSON.stringify(data, BufferJSON.replacer); + const cacheConfig = configService.get('CACHE'); if (key != 'creds') { - return await cache.hSet(sessionId, key, data); - // await fs.writeFile(localFile(key), dataString); - // return; + if (cacheConfig.REDIS.ENABLED) { + return await cache.hSet(sessionId, key, data); + } else { + await fs.writeFile(localFile(key), dataString); + return; + } } await saveKey(sessionId, dataString); return; @@ -98,35 +107,65 @@ export default async function useMultiFileAuthStatePrisma( async function readData(key: string): Promise { try { let rawData; + const cacheConfig = configService.get('CACHE'); if (key != 'creds') { - return await cache.hGet(sessionId, key); - // if (!(await fileExists(localFile(key)))) return null; - // rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' }); + if (cacheConfig.REDIS.ENABLED) { + return await cache.hGet(sessionId, key); + } else { + if (!(await fileExists(localFile(key)))) return null; + rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' }); + return JSON.parse(rawData, BufferJSON.reviver); + } } else { rawData = await getAuthKey(sessionId); } const parsedData = JSON.parse(rawData, BufferJSON.reviver); return parsedData; - } catch (error) { + } catch { return null; } } async function removeData(key: string): Promise { try { + const cacheConfig = configService.get('CACHE'); + if (key != 'creds') { - return await cache.hDelete(sessionId, key); - // await fs.unlink(localFile(key)); + if (cacheConfig.REDIS.ENABLED) { + return await cache.hDelete(sessionId, key); + } else { + await fs.unlink(localFile(key)); + } } else { await deleteAuthKey(sessionId); } - } catch (error) { + } catch { return; } } + async function removeCreds(): Promise { + const cacheConfig = configService.get('CACHE'); + + // Redis + try { + if (cacheConfig.REDIS.ENABLED) { + await cache.delete(sessionId); + logger.info({ action: 'redis.delete', sessionId }); + + return; + } + } catch (err) { + logger.warn({ action: 'redis.delete', sessionId, err }); + } + + logger.info({ action: 'auth.key.delete', sessionId }); + + await deleteAuthKey(sessionId); + } + let creds = await readData('creds'); if (!creds) { creds = initAuthCreds(); @@ -143,7 +182,7 @@ export default async function useMultiFileAuthStatePrisma( ids.map(async (id) => { let value = await readData(`${type}-${id}`); if (type === 'app-state-sync-key' && value) { - value = proto.Message.AppStateSyncKeyData.fromObject(value); + value = proto.Message.AppStateSyncKeyData.create(value); } data[id] = value; @@ -168,5 +207,7 @@ export default async function useMultiFileAuthStatePrisma( saveCreds: () => { return writeData(creds, 'creds'); }, + + removeCreds, }; } diff --git a/src/utils/use-multi-file-auth-state-provider-files.ts b/src/utils/use-multi-file-auth-state-provider-files.ts index 4dfa2fb25..eecc3100e 100644 --- a/src/utils/use-multi-file-auth-state-provider-files.ts +++ b/src/utils/use-multi-file-auth-state-provider-files.ts @@ -39,7 +39,11 @@ import { Logger } from '@config/logger.config'; import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys'; import { isNotEmpty } from 'class-validator'; -export type AuthState = { state: AuthenticationState; saveCreds: () => Promise }; +export type AuthState = { + state: AuthenticationState; + saveCreds: () => Promise; + removeCreds: () => Promise; +}; export class AuthStateProvider { constructor(private readonly providerFiles: ProviderFiles) {} @@ -86,6 +90,18 @@ export class AuthStateProvider { return response; }; + const removeCreds = async () => { + const [response, error] = await this.providerFiles.removeSession(instance); + if (error) { + // this.logger.error(['removeData', error?.message, error?.stack]); + return; + } + + logger.info({ action: 'remove.session', instance, response }); + + return; + }; + const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds(); return { @@ -100,7 +116,7 @@ export class AuthStateProvider { ids.map(async (id) => { let value = await readData(`${type}-${id}`); if (type === 'app-state-sync-key' && value) { - value = proto.Message.AppStateSyncKeyData.fromObject(value); + value = proto.Message.AppStateSyncKeyData.create(value); } data[id] = value; @@ -126,6 +142,10 @@ export class AuthStateProvider { saveCreds: async () => { return await writeData(creds, 'creds'); }, + + removeCreds, }; } } + +const logger = new Logger('useMultiFileAuthStatePrisma'); diff --git a/src/utils/use-multi-file-auth-state-redis-db.ts b/src/utils/use-multi-file-auth-state-redis-db.ts index 837f80924..e0981c700 100644 --- a/src/utils/use-multi-file-auth-state-redis-db.ts +++ b/src/utils/use-multi-file-auth-state-redis-db.ts @@ -8,6 +8,7 @@ export async function useMultiFileAuthStateRedisDb( ): Promise<{ state: AuthenticationState; saveCreds: () => Promise; + removeCreds: () => Promise; }> { const logger = new Logger('useMultiFileAuthStateRedisDb'); @@ -36,6 +37,16 @@ export async function useMultiFileAuthStateRedisDb( } }; + async function removeCreds(): Promise { + try { + logger.warn({ action: 'redis.delete', instanceName }); + + return await cache.delete(instanceName); + } catch { + return; + } + } + const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds(); return { @@ -50,7 +61,7 @@ export async function useMultiFileAuthStateRedisDb( ids.map(async (id) => { let value = await readData(`${type}-${id}`); if (type === 'app-state-sync-key' && value) { - value = proto.Message.AppStateSyncKeyData.fromObject(value); + value = proto.Message.AppStateSyncKeyData.create(value); } data[id] = value; @@ -76,5 +87,7 @@ export async function useMultiFileAuthStateRedisDb( saveCreds: async () => { return await writeData(creds, 'creds'); }, + + removeCreds, }; } diff --git a/src/validate/business.schema.ts b/src/validate/business.schema.ts new file mode 100644 index 000000000..91ad17b20 --- /dev/null +++ b/src/validate/business.schema.ts @@ -0,0 +1,17 @@ +import { JSONSchema7 } from 'json-schema'; + +export const catalogSchema: JSONSchema7 = { + type: 'object', + properties: { + number: { type: 'string' }, + limit: { type: 'number' }, + }, +}; + +export const collectionsSchema: JSONSchema7 = { + type: 'object', + properties: { + number: { type: 'string' }, + limit: { type: 'number' }, + }, +}; diff --git a/src/validate/chat.schema.ts b/src/validate/chat.schema.ts index dba279959..7dae44539 100644 --- a/src/validate/chat.schema.ts +++ b/src/validate/chat.schema.ts @@ -195,8 +195,9 @@ export const contactValidateSchema: JSONSchema7 = { _id: { type: 'string', minLength: 1 }, pushName: { type: 'string', minLength: 1 }, id: { type: 'string', minLength: 1 }, + remoteJid: { type: 'string', minLength: 1 }, }, - ...isNotEmpty('_id', 'id', 'pushName'), + ...isNotEmpty('_id', 'id', 'pushName', 'remoteJid'), }, }, }; diff --git a/src/validate/instance.schema.ts b/src/validate/instance.schema.ts index de5be2b9c..a0553b666 100644 --- a/src/validate/instance.schema.ts +++ b/src/validate/instance.schema.ts @@ -43,6 +43,7 @@ export const instanceSchema: JSONSchema7 = { readMessages: { type: 'boolean' }, readStatus: { type: 'boolean' }, syncFullHistory: { type: 'boolean' }, + wavoipToken: { type: 'string' }, // Proxy proxyHost: { type: 'string' }, proxyPort: { type: 'string' }, @@ -67,6 +68,7 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -103,6 +105,44 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', + 'CONTACTS_SET', + 'CONTACTS_UPSERT', + 'CONTACTS_UPDATE', + 'PRESENCE_UPDATE', + 'CHATS_SET', + 'CHATS_UPSERT', + 'CHATS_UPDATE', + 'CHATS_DELETE', + 'GROUPS_UPSERT', + 'GROUP_UPDATE', + 'GROUP_PARTICIPANTS_UPDATE', + 'CONNECTION_UPDATE', + 'LABELS_EDIT', + 'LABELS_ASSOCIATION', + 'CALL', + 'TYPEBOT_START', + 'TYPEBOT_CHANGE_STATUS', + ], + }, + }, + // NATS + natsEnabled: { type: 'boolean' }, + natsEvents: { + type: 'array', + minItems: 0, + items: { + type: 'string', + enum: [ + 'APPLICATION_STARTUP', + 'QRCODE_UPDATED', + 'MESSAGES_SET', + 'MESSAGES_UPSERT', + 'MESSAGES_EDITED', + 'MESSAGES_UPDATE', + 'MESSAGES_DELETE', + 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', @@ -139,6 +179,7 @@ export const instanceSchema: JSONSchema7 = { 'MESSAGES_UPDATE', 'MESSAGES_DELETE', 'SEND_MESSAGE', + 'SEND_MESSAGE_UPDATE', 'CONTACTS_SET', 'CONTACTS_UPSERT', 'CONTACTS_UPDATE', diff --git a/src/validate/settings.schema.ts b/src/validate/settings.schema.ts index b5c056010..95a0e9c96 100644 --- a/src/validate/settings.schema.ts +++ b/src/validate/settings.schema.ts @@ -31,6 +31,7 @@ export const settingsSchema: JSONSchema7 = { readMessages: { type: 'boolean' }, readStatus: { type: 'boolean' }, syncFullHistory: { type: 'boolean' }, + wavoipToken: { type: 'string' }, }, required: ['rejectCall', 'groupsIgnore', 'alwaysOnline', 'readMessages', 'readStatus', 'syncFullHistory'], ...isNotEmpty('rejectCall', 'groupsIgnore', 'alwaysOnline', 'readMessages', 'readStatus', 'syncFullHistory'), diff --git a/src/validate/templateDelete.schema.ts b/src/validate/templateDelete.schema.ts new file mode 100644 index 000000000..70b3aefff --- /dev/null +++ b/src/validate/templateDelete.schema.ts @@ -0,0 +1,32 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties: Record = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + } as JSONSchema7; +}; + +export const templateDeleteSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + name: { type: 'string' }, + hsmId: { type: 'string' }, + }, + required: ['name'], + ...isNotEmpty('name'), +}; diff --git a/src/validate/templateEdit.schema.ts b/src/validate/templateEdit.schema.ts new file mode 100644 index 000000000..0b03e32d5 --- /dev/null +++ b/src/validate/templateEdit.schema.ts @@ -0,0 +1,35 @@ +import { JSONSchema7 } from 'json-schema'; +import { v4 } from 'uuid'; + +const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => { + const properties: Record = {}; + propertyNames.forEach( + (property) => + (properties[property] = { + minLength: 1, + description: `The "${property}" cannot be empty`, + }), + ); + return { + if: { + propertyNames: { + enum: [...propertyNames], + }, + }, + then: { properties }, + } as JSONSchema7; +}; + +export const templateEditSchema: JSONSchema7 = { + $id: v4(), + type: 'object', + properties: { + templateId: { type: 'string' }, + category: { type: 'string', enum: ['AUTHENTICATION', 'MARKETING', 'UTILITY'] }, + allowCategoryChange: { type: 'boolean' }, + ttl: { type: 'number' }, + components: { type: 'array' }, + }, + required: ['templateId'], + ...isNotEmpty('templateId'), +}; diff --git a/src/validate/validate.schema.ts b/src/validate/validate.schema.ts index cf3d7828c..69e0090d8 100644 --- a/src/validate/validate.schema.ts +++ b/src/validate/validate.schema.ts @@ -1,4 +1,5 @@ // Integrations Schema +export * from './business.schema'; export * from './chat.schema'; export * from './group.schema'; export * from './instance.schema'; @@ -7,5 +8,7 @@ export * from './message.schema'; export * from './proxy.schema'; export * from './settings.schema'; export * from './template.schema'; +export * from './templateDelete.schema'; +export * from './templateEdit.schema'; export * from '@api/integrations/chatbot/chatbot.schema'; export * from '@api/integrations/event/event.schema'; diff --git a/tsconfig.json b/tsconfig.json index be16fc49b..af814134a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,7 +4,7 @@ "emitDecoratorMetadata": true, "declaration": true, "target": "es2020", - "module": "commonjs", + "module": "CommonJS", "rootDir": "./", "resolveJsonModule": true, "removeComments": true, @@ -26,7 +26,8 @@ "@libs/*": ["./src/libs/*"], "@utils/*": ["./src/utils/*"], "@validate/*": ["./src/validate/*"] - } + }, + "moduleResolution": "Node" }, "exclude": ["node_modules", "./test", "./dist", "./prisma"], "include": [ diff --git a/tsup.config.ts b/tsup.config.ts index 2450b52f2..f09ecd877 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -15,5 +15,6 @@ export default defineConfig({ }, loader: { '.json': 'file', + '.yml': 'file', }, });