Evolution API / Evolution Go is an open-source WhatsApp integration API
Go baileyscloud-apievo-apievo-goevolutionevolution-apievolution-gogolangwhatsappwhatsapp-botwhatsmeow
release: v0.6.1
Davidson Gomes877eef7f0779
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..8acf18f--- /dev/null+++ b/.dockerignore@@ -0,0 +1,48 @@+# Git+.git+.gitignore++# Documentation+README.md+# docs/ - Mantido porque docs/docs.go é necessário para o build (gerado pelo swagger)+docs/wiki/++# Logs+logs/++# IDE+.vscode/+.idea/++# OS+.DS_Store+Thumbs.db++# Build artifacts+server+build/++# Docker+Dockerfile+.dockerignore+docker/++# Scripts+*.sh+Makefile++# Test files+*_test.go+*.test++# Manager/dist é necessário - serve arquivos estáticos do frontend React+# Não excluir - precisa estar na imagem final para ser acessado via /manager++# Keep these important files/folders for build:+# - whatsmeow/ (nossa versão local modificada)+# - go.mod, go.sum (dependências)+# - pkg/, cmd/ (código fonte necessário para compilar)+# - docs/docs.go (gerado pelo swagger, necessário para build)++# IMPORTANT: O código-fonte (pkg/, cmd/, etc.) é necessário no stage de build+# mas NÃO é copiado para a imagem final - apenas o executável compilado vai.\ No newline at end of filediff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..831e431--- /dev/null+++ b/.env.example@@ -0,0 +1,29 @@+SERVER_PORT=8080++POSTGRES_AUTH_DB=postgresql://postgres:root@localhost:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:root@localhost:5432/evogo_users?sslmode=disable+DATABASE_SAVE_MESSAGES=false+CLIENT_NAME=evolution++GLOBAL_API_KEY=429683C4C977415CAAFCCE10F7D57E11++WADEBUG=DEBUG+LOGTYPE=console+WEBHOOKFILES=true++CONNECT_ON_STARTUP=true++OS_NAME=Evolution GO++AMQP_URL=amqp://admin:admin@localhost:5672/default+AMQP_GLOBAL_ENABLED=false++WEBHOOK_URL=https://webhook.site/2e6af2fa-6b04-497f-b4a1-13a905728d83++# Minio Configuration+MINIO_ENABLED=true+MINIO_ENDPOINT=localhost:9000+MINIO_ACCESS_KEY=minioadmin+MINIO_SECRET_KEY=minioadmin+MINIO_BUCKET=evolution-media+MINIO_USE_SSL=false\ No newline at end of filediff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.ymlnew file mode 100644index 0000000..852fdb5--- /dev/null+++ b/.github/workflows/publish_docker_image.yml@@ -0,0 +1,55 @@+name: Build and Publish Docker Image++on:+ push:+ branches:+ - main+ tags:+ - "*.*.*"++jobs:+ build_deploy:+ name: Build and Deploy+ runs-on: ubuntu-latest+ permissions:+ contents: read+ packages: write+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Docker meta+ id: meta+ uses: docker/metadata-action@v5+ with:+ images: evoapicloud/evolution-go+ tags: |+ type=ref,event=branch+ type=semver,pattern={{version}}+ type=raw,value=latest,enable={{is_default_branch}}++ - name: Set up QEMU+ uses: docker/setup-qemu-action@v3++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@v3++ - name: Login to Docker Hub+ uses: docker/login-action@v3+ with:+ username: ${{ secrets.DOCKER_USERNAME }}+ password: ${{ secrets.DOCKER_PASSWORD }}++ - name: Build and push+ id: docker_build+ uses: docker/build-push-action@v5+ with:+ platforms: linux/amd64,linux/arm64+ push: true+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha+ cache-to: type=gha,mode=max++ - name: Image digest+ run: echo ${{ steps.docker_build.outputs.digest }}\ No newline at end of filediff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..587b9ae--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+.env+logs/*+build/+*.prof+coverage.*+.air.toml+.idea/+.vscode/+.DS_Store+.cursorrulesdiff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..031fa45--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,245 @@+# Evolution GO - Changelog++## v0.6.1++### 🆕 New Features+- **Group invite info endpoint** — `GET /group/invite-info` to get group details from invite link+- **Enhanced media sending** — GIF playback, video stickers, and transparent sticker support++### 🐛 Bug Fixes+- **Admin revoke** — Allow deleting messages from others in groups (admin revoke)++### 🔧 Improvements+- **Version management** — Reads version from `VERSION` file with ldflags fallback+- **CORS global middleware** — Applied before all routes+- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default)+- **CI/CD cleanup** — Removed `develop` branch trigger and `homolog` tag from Docker workflow+- **README updated** — New links, documentation, and hosting info++## v0.6.0++### 🆕 New Features+- **Version from VERSION file** — Reads version from `VERSION` file at startup instead of hardcoded value++### 🔧 Improvements+- **Makefile compatibility** — Fixed `$(shell)` syntax for GNU Make 3.81 (macOS default)++## v0.5.4++### 🔧 Improvements+- **Update whatsmeow lib**++## v0.5.3++**Docker:** `evoapicloud/evolution-go:0.5.3`++### 🔧 Improvements++- **Update context handling in service methods**+ - Refactored multiple service methods across various packages to include `context.Background()` as the first argument in client calls. This change ensures that all client interactions are properly context-aware, allowing for better cancellation and timeout management.+ - Updated methods in `call_service.go`, `community_service.go`, `group_service.go`, `message_service.go`, `newsletter_service.go`, `send_service.go`, `user_service.go`, and `whatsmeow.go` to enhance consistency and reliability in handling requests.+ - This adjustment improves the overall robustness of the API by ensuring that all client calls can leverage context for better control over execution flow and resource management.++## v0.5.2++**Docker:** `evoapicloud/evolution-go:0.5.2`++### 🆕 New Features+- **SetProxy Endpoint**: New endpoint `POST /instance/proxy/{instanceId}` to configure proxy for instances+ - Support for proxy with/without authentication+ - Validation of required fields (host, port)+ - Automatic cache update via reconnection+ - Integrated Swagger documentation++### 🔧 Improvements+- **CheckUser Fallback Logic**: Implemented intelligent fallback logic+ - If `formatJid=true` returns `IsInWhatsapp=false`, automatically retries with `formatJid=false`+ - Significant improvement in valid user detection+ - Added `RemoteJID` field to use WhatsApp-validated JID+- **LID/WhatsApp JID Swap**: Automatic handling of special cases+ - When `Sender` comes as `@lid` and `SenderAlt` comes as `@s.whatsapp.net`+ - Automatic inversion: `Sender` and `Chat` receive `@s.whatsapp.net`, `SenderAlt` receives `@lid`+ - Detailed logs for tracking swaps++### 🐛 Bug Fixes+- **SendMessage**: Standardization of WhatsApp-validated `remoteJID` usage+- **User Validation**: Improvement in phone number validation and formatting++---++## v0.5.1++**Docker:** `evoapicloud/evolution-go:0.5.1`++### 🔧 Improvements+- **Instance Deletion**: Enhance instance deletion and media storage path resolution+- **Media Storage**: Improvements in media storage and path resolution++---++## v0.5.0++**Docker:** `evoapicloud/evolution-go:0.5.0`++### 🔧 Improvements+- **Media Storage**: Enhance media storage and logging in Whatsmeow event handling+- **Retry Logic**: Implement retry logic for client connection and message sending+- **Media Handling**: Enhance media handling in event processing++---++## v0.4.9++**Docker:** `evoapicloud/evolution-go:0.4.9`++### 🔧 Improvements+- **Connection Handling**: Add instance update test scenarios and improve connection handling+- **FormatJid Field**: Update FormatJid field to pointer type for better handling in message structures+- **Dependencies**: Update dependencies and fix presence handling in Whatsmeow integration++---++## v0.4.8++**Docker:** `evoapicloud/evolution-go:0.4.8`++### 🔧 Improvements+- **Audio Duration**: Improve audio duration parsing in convertAudioToOpusWithDuration function++---++## v0.4.7++**Docker:** `evoapicloud/evolution-go:0.4.7`++### 🔧 Improvements+- **Phone Number Formatting**: Improve phone number formatting and validation in user service+- **Brazilian/Portuguese Numbers**: Update Brazilian and Portuguese number formatting in utils++### 🆕 New Features+- **Media Handling**: Enhance media handling in event processing++---++## v0.4.6++**Docker:** `evoapicloud/evolution-go:0.4.6`++### 🆕 New Features+- **User Existence Check**: Add user existence check configuration and JID validation middleware++---++## v0.4.5++**Docker:** `evoapicloud/evolution-go:0.4.5`++### 🔧 Improvements+- **Dependencies**: Update dependencies and enhance audio conversion functionality++---++## v0.4.4++**Docker:** `evoapicloud/evolution-go:0.4.4`++### 🆕 New Features+- **CLAUDE.md**: Add CLAUDE.md for project documentation and enhance RabbitMQ connection handling++---++## v0.4.3++**Docker:** `evoapicloud/evolution-go:0.4.3`++### 🔧 Improvements+- **PostgreSQL Connection**: Fix in PostgreSQL connection configuration for session auth+ - Controlled configuration of pool, idle, etc.+ - Adjustment on top of whatsmeow lib+- **User Endpoints**: Fix in 'User Info' and 'Check User' endpoints+ - Now return with contact's LID information++---++## v0.3.0++### 🆕 New Features+- **Own Message Reactions**: Additional 'fromMe' parameter using Chat id+- **CreatedAt Field**: CreatedAt field added to instances table++---++## v0.2.0++### 🆕 New Features+- **Advanced Settings**: Advanced configurations in instance creation+ - `alwaysOnline` (still to be implemented)+ - `rejectCall` - Automatically reject calls+ - `msgRejectCall` - Call rejection message+ - `readMessages` - Automatically mark messages as read+ - `ignoreGroups` - Ignore group messages+ - `ignoreStatus` - Ignore status messages+- **Advanced Settings Routes**: New routes for get and update of advanced settings+- **QR Code Control**: `QRCODE_MAX_COUNT` variable to control how many QR codes to generate before timeout+- **AMQP Events**: `AMQP_SPECIFIC_EVENTS` variable to individually select which events to receive in RabbitMQ++### 🔧 Improvements+- **Reconnect Endpoint**: Fix in reconnect endpoint+- **Sender Info**: `Sender` and `SenderAlt` no longer come with session id, only the id++### 🐛 Bug Fixes+- **QR Code Generation**: Fix to not generate QR code automatically after disconnection or logout++---++## v0.1.0++### 🆕 Initial Features+- Base implementation of Evolution API in Go+- WhatsApp integration via whatsmeow+- Instance system+- Basic message sending endpoints+- Webhook support+- RabbitMQ and NATS integration+- Authentication system+- Swagger documentation++---++## 📋 Migration Notes++### v0.5.2+- The new `SetProxy` endpoint requires admin permissions (`AuthAdmin`)+- The `CheckUser` fallback logic is automatic and transparent+- LID/WhatsApp JID handling is automatic++### v0.4.3+- Check PostgreSQL connection settings if using postgres auth++### v0.2.0+- Review advanced settings configurations if necessary+- Configure `QRCODE_MAX_COUNT` if you want to limit QR codes+- Configure `AMQP_SPECIFIC_EVENTS` for specific RabbitMQ events++---++## 🔗 Useful Links++- **Docker Hub**: `evoapicloud/evolution-go`+- **Documentation**: Swagger available at `/swagger/`+- **GitHub**: [Evolution API Go](https://github.com/EvolutionAPI/evolution-go)++---++## 🤝 Contributing++To contribute to the project:+1. Fork the repository+2. Create a branch for your feature+3. Commit your changes+4. Open a Pull Request++---++*Last updated: October 2025*+diff --git a/COMMANDS.md b/COMMANDS.mdnew file mode 100644index 0000000..4da3244--- /dev/null+++ b/COMMANDS.md@@ -0,0 +1,265 @@+# 🚀 Guia Rápido de Comandos++Comandos mais usados no dia a dia de desenvolvimento do Evolution GO.++## 📋 Comandos Essenciais++### Desenvolvimento++```bash+# Ver todos os comandos disponíveis+make help++# Rodar em modo desenvolvimento+make dev++# Rodar com hot reload (recarrega automaticamente ao salvar)+make watch+```++### Build e Instalação++```bash+# Compilar a aplicação+make build++# Compilar para todas as plataformas (Linux, Windows, macOS)+make build-all++# Instalar no GOPATH+make install+```++### Testes++```bash+# Rodar todos os testes+make test++# Rodar testes com relatório de cobertura+make test-coverage++# Rodar testes com verificação de race conditions+make test-race++# Rodar benchmarks+make bench+```++### Qualidade de Código++```bash+# Formatar código+make fmt++# Executar linter+make lint++# Executar go vet+make vet++# Executar todas as verificações (fmt + vet + lint + test)+make check+```++### Docker++```bash+# Build da imagem Docker+make docker-build++# Rodar container Docker+make docker-run++# Iniciar todos os serviços com docker-compose+make docker-compose-up++# Parar todos os serviços+make docker-compose-down++# Ver logs do docker-compose+make docker-compose-logs+```++### Banco de Dados++```bash+# Executar migrations+make migrate-up++# Reverter migrations+make migrate-down+```++### Documentação++```bash+# Gerar documentação Swagger+make swagger++# Abrir documentação local+make docs+```++### Dependências++```bash+# Instalar dependências+make deps++# Atualizar dependências+make deps-update++# Limpar dependências não utilizadas+make deps-clean+```++### Limpeza++```bash+# Remover arquivos de build+make clean++# Limpeza completa (incluindo cache do Go)+make clean-all+```++## 🎯 Workflows Comuns++### Setup Inicial++```bash+# 1. Clone o repositório+git clone https://git.evoai.app/Evolution/evolution-go.git+cd evolution-go++# 2. Setup completo do ambiente+make setup++# 3. Configure o .env+cp .env.example .env+# Edite o .env com suas configurações++# 4. Rode em modo desenvolvimento+make dev+```++### Desenvolvimento Diário++```bash+# Rodar com hot reload+make watch++# Em outro terminal, rodar testes em watch mode+# (requer: go install github.com/cespare/reflex@latest)+reflex -r '\.go$' -s -- make test+```++### Antes de Fazer Commit++```bash+# Executar todas as verificações+make check++# Se tudo passar, commit e push+git add .+git commit -m "feat: sua feature"+git push+```++### Preparar para Deploy++```bash+# 1. Rodar todos os testes+make test++# 2. Build da imagem Docker+make docker-build++# 3. Testar localmente+make docker-run++# 4. Se tudo ok, fazer tag e push+docker tag evolution-go:latest seu-registry/evolution-go:v1.0.0+docker push seu-registry/evolution-go:v1.0.0+```++### Debug e Profiling++```bash+# Ver status da aplicação+make status++# Ver logs em tempo real+make logs++# Profile de CPU (aplicação deve estar rodando)+make profile-cpu++# Profile de memória (aplicação deve estar rodando)+make profile-mem++# Ver informações de versão+make version+```++## 🔧 Ferramentas Opcionais++Instale estas ferramentas para habilitar recursos adicionais:++```bash+# Hot reload+go install github.com/cosmtrek/air@latest++# Linter+go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest++# Swagger generator+go install github.com/swaggo/swag/cmd/swag@latest++# Watch mode para testes+go install github.com/cespare/reflex@latest+```++## 💡 Dicas++1. **Use `make help`** sempre que esquecer um comando+2. **Use `make watch`** durante desenvolvimento para hot reload automático+3. **Use `make check`** antes de fazer commit+4. **Use `make setup`** em uma nova máquina para configurar tudo de uma vez+5. **Configure seu IDE** para rodar `make fmt` ao salvar arquivos++## 📚 Documentação Completa++Para documentação completa da API e guias detalhados:++- **[Documentação Oficial](./docs/wiki/README.md)** - Guias, tutoriais e referência+- **[API Swagger](http://localhost:4000/swagger/index.html)** - Documentação interativa (quando servidor estiver rodando)++## ❓ Problemas Comuns++### "make: command not found"+- **macOS**: `xcode-select --install`+- **Ubuntu/Debian**: `sudo apt-get install build-essential`+- **Windows**: Use WSL ou instale Make para Windows++### "air: command not found" ao usar `make watch`+```bash+go install github.com/cosmtrek/air@latest+```++### "golangci-lint: command not found" ao usar `make lint`+```bash+go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest+```++### Porta 4000 já em uso+```bash+# Mude a porta no .env+SERVER_PORT=8080+```++---++**Dica Final**: Rode `make help` para ver a lista completa e atualizada de comandos!+diff --git a/Dockerfile b/Dockerfilenew file mode 100644index 0000000..8ad0e7a--- /dev/null+++ b/Dockerfile@@ -0,0 +1,33 @@+FROM golang:1.25.0-alpine AS build++RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev++WORKDIR /build++# Copiar apenas arquivos de dependências primeiro para cachear o download+COPY go.mod go.sum ./++# Copiar whatsmeow-lib que é uma dependência local+COPY whatsmeow-lib/ ./whatsmeow-lib/++# Agora fazer download das dependências (com replace funcionando)+RUN go mod download++# Copiar o restante do código+COPY . .++ARG VERSION=dev+RUN CGO_ENABLED=1 go build -ldflags "-X main.version=${VERSION}" -o server ./cmd/evolution-go++FROM alpine:3.19.1 AS final++RUN apk update && apk add --no-cache tzdata ffmpeg libjpeg-turbo libwebp++WORKDIR /app++COPY --from=build /build/server .+COPY --from=build /build/manager/dist ./manager/dist++ENV TZ=America/Sao_Paulo++ENTRYPOINT ["/app/server"]diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..2eb13cb--- /dev/null+++ b/LICENSE@@ -0,0 +1,222 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (which shall not include communications that are solely written+ by copyright holders to be excluded from the License).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based upon (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and derivative works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control+ systems, and issue tracking systems that are managed by, or on behalf+ of, the Licensor for the purpose of discussing and improving the Work,+ but excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to use, reproduce, modify, merge, publish,+ distribute, sublicense, and/or sell copies of the Work, and to+ permit persons to whom the Work is furnished to do so, subject to+ the following conditions:++ The above copyright notice and this permission notice shall be+ included in all copies or substantial portions of the Work.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright notice to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Support. You may choose to offer, and to+ charge a fee for, warranty, support, indemnity or other liability+ obligations and/or rights consistent with this License. However, in+ accepting such obligations, You may act only on Your own behalf and+ on Your sole responsibility, not on behalf of any other Contributor,+ and only if You agree to indemnify, defend, and hold each Contributor+ harmless for any liability incurred by, or claims asserted against,+ such Contributor by reason of your accepting any such warranty or support.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same page as the copyright notice for easier identification within+ third-party archives.++ Copyright 2025 Evolution API++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+++ADDITIONAL CONDITIONS:++1. LOGO and copyright information: In the process of using Evolution Go API's+ frontend components, you may not remove or modify the LOGO or copyright+ information in the Evolution API console or applications. This restriction+ is inapplicable to uses of Evolution Go API that do not involve its frontend+ components.++2. Usage Notification Requirement: If Evolution Go 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 Go 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 [email protected] to inquire about licensing matters.diff --git a/Makefile b/Makefilenew file mode 100644index 0000000..1134d2d--- /dev/null+++ b/Makefile@@ -0,0 +1,268 @@+.PHONY: help dev run build test clean swagger deps docker-build docker-run install setup migrate-up migrate-down logs++# Configurações+APP_NAME=evolution-go+MAIN_PATH=cmd/evolution-go/main.go+BUILD_DIR=build+GO=go+VERSION=$(shell grep -om1 "v[0-9].*" CHANGELOG.md)+LDFLAGS=-ldflags "-X main.version=$(VERSION)"+GOFLAGS=-v++# Cores para output+GREEN=\033[0;32m+YELLOW=\033[0;33m+RED=\033[0;31m+NC=\033[0m # No Color++##@ Ajuda++help: ## Exibe esta mensagem de ajuda+ @echo "$(GREEN)Evolution GO - Makefile$(NC)"+ @echo ""+ @awk 'BEGIN {FS = ":.*##"; printf "\nUso:\n make $(YELLOW)<target>$(NC)\n"} /^[a-zA-Z_-]+:.*?##/ { printf " $(GREEN)%-15s$(NC) %s\n", $$1, $$2 } /^##@/ { printf "\n$(YELLOW)%s$(NC)\n", substr($$0, 5) } ' $(MAKEFILE_LIST)++##@ Desenvolvimento++dev: ## Roda a aplicação em modo desenvolvimento+ @echo "$(GREEN)🚀 Rodando Evolution GO em modo desenvolvimento...$(NC)"+ $(GO) run $(LDFLAGS) $(MAIN_PATH) -dev++run: ## Roda a aplicação em modo produção+ @echo "$(GREEN)🚀 Rodando Evolution GO...$(NC)"+ $(GO) run $(MAIN_PATH)++watch: ## Roda a aplicação com hot reload (requer air)+ @if command -v air > /dev/null; then \+ echo "$(GREEN)🔥 Rodando com hot reload...$(NC)"; \+ air; \+ else \+ echo "$(RED)❌ Air não instalado. Instale com: go install github.com/cosmtrek/air@latest$(NC)"; \+ exit 1; \+ fi++##@ Build++build: ## Compila a aplicação+ @echo "$(GREEN)🔨 Compilando $(APP_NAME)...$(NC)"+ @mkdir -p $(BUILD_DIR)+ $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME) $(MAIN_PATH)+ @echo "$(GREEN)✅ Build completo: $(BUILD_DIR)/$(APP_NAME)$(NC)"++build-linux: ## Compila para Linux+ @echo "$(GREEN)🔨 Compilando para Linux...$(NC)"+ @mkdir -p $(BUILD_DIR)+ GOOS=linux GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-linux-amd64 $(MAIN_PATH)+ @echo "$(GREEN)✅ Build Linux completo$(NC)"++build-windows: ## Compila para Windows+ @echo "$(GREEN)🔨 Compilando para Windows...$(NC)"+ @mkdir -p $(BUILD_DIR)+ GOOS=windows GOARCH=amd64 $(GO) build $(GOFLAGS) $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-windows-amd64.exe $(MAIN_PATH)+ @echo "$(GREEN)✅ Build Windows completo$(NC)"++build-all: build build-linux build-windows ## Compila para todas as plataformas+ @echo "$(GREEN)✅ Todos os builds completos$(NC)"++install: build ## Compila e instala no GOPATH+ @echo "$(GREEN)📦 Instalando $(APP_NAME)...$(NC)"+ $(GO) install $(MAIN_PATH)+ @echo "$(GREEN)✅ Instalado com sucesso$(NC)"++##@ Testes++test: ## Roda todos os testes+ @echo "$(GREEN)🧪 Rodando testes...$(NC)"+ $(GO) test -v ./...++test-coverage: ## Roda testes com cobertura+ @echo "$(GREEN)🧪 Rodando testes com cobertura...$(NC)"+ $(GO) test -v -coverprofile=coverage.out ./...+ $(GO) tool cover -html=coverage.out -o coverage.html+ @echo "$(GREEN)✅ Cobertura gerada: coverage.html$(NC)"++test-race: ## Roda testes verificando race conditions+ @echo "$(GREEN)🧪 Rodando testes com race detector...$(NC)"+ $(GO) test -race -v ./...++bench: ## Roda benchmarks+ @echo "$(GREEN)⚡ Rodando benchmarks...$(NC)"+ $(GO) test -bench=. -benchmem ./...++##@ Dependências++deps: ## Instala dependências+ @echo "$(GREEN)📦 Instalando dependências...$(NC)"+ $(GO) mod download+ $(GO) mod verify+ @echo "$(GREEN)✅ Dependências instaladas$(NC)"++deps-update: ## Atualiza dependências+ @echo "$(GREEN)📦 Atualizando dependências...$(NC)"+ $(GO) get -u ./...+ $(GO) mod tidy+ @echo "$(GREEN)✅ Dependências atualizadas$(NC)"++deps-clean: ## Limpa dependências não utilizadas+ @echo "$(GREEN)🧹 Limpando dependências...$(NC)"+ $(GO) mod tidy+ @echo "$(GREEN)✅ Dependências limpas$(NC)"++deps-reset: ## Limpa cache e reinstala dependências (força uso do código local)+ @echo "$(GREEN)🔄 Resetando dependências e cache...$(NC)"+ @echo "$(YELLOW)Limpeza de cache e módulos...$(NC)"+ $(GO) clean -cache -modcache -i -r+ @echo "$(YELLOW)Download de módulos...$(NC)"+ $(GO) mod download+ @echo "$(YELLOW)Organizando módulos...$(NC)"+ $(GO) mod tidy+ @echo "$(GREEN)✅ Dependências resetadas e atualizadas$(NC)"++##@ Documentação++swagger: ## Gera documentação Swagger+ @echo "$(GREEN)📚 Gerando documentação Swagger...$(NC)"+ @if command -v swag > /dev/null; then \+ swag init -g $(MAIN_PATH) -o ./docs; \+ echo "$(GREEN)✅ Swagger gerado com sucesso$(NC)"; \+ else \+ echo "$(RED)❌ Swag não instalado. Instale com: go install github.com/swaggo/swag/cmd/swag@latest$(NC)"; \+ exit 1; \+ fi++docs: ## Abre a documentação local+ @echo "$(GREEN)📖 Abrindo documentação...$(NC)"+ @if [ -f "docs/wiki/README.md" ]; then \+ echo "Documentação disponível em: docs/wiki/README.md"; \+ else \+ echo "$(RED)❌ Documentação não encontrada$(NC)"; \+ fi++##@ Database++migrate-up: ## Executa migrations do banco de dados+ @echo "$(GREEN)🗃️ Executando migrations...$(NC)"+ @if [ -d "migrations" ]; then \+ $(GO) run $(MAIN_PATH) migrate up; \+ else \+ echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \+ fi++migrate-down: ## Reverte migrations do banco de dados+ @echo "$(YELLOW)⚠️ Revertendo migrations...$(NC)"+ @if [ -d "migrations" ]; then \+ $(GO) run $(MAIN_PATH) migrate down; \+ else \+ echo "$(YELLOW)⚠️ Diretório migrations não encontrado$(NC)"; \+ fi++##@ Docker++docker-build: ## Build da imagem Docker+ @echo "$(GREEN)🐳 Construindo imagem Docker...$(NC)"+ docker build --build-arg VERSION=$(VERSION) -t $(APP_NAME):latest .+ @echo "$(GREEN)✅ Imagem Docker construída$(NC)"++docker-run: ## Roda container Docker+ @echo "$(GREEN)🐳 Iniciando container...$(NC)"+ docker run -p 4000:4000 --env-file .env $(APP_NAME):latest++docker-compose-up: ## Sobe todos os serviços com docker-compose+ @echo "$(GREEN)🐳 Iniciando serviços com docker-compose...$(NC)"+ docker-compose up -d++docker-compose-down: ## Para todos os serviços do docker-compose+ @echo "$(YELLOW)🐳 Parando serviços...$(NC)"+ docker-compose down++docker-compose-logs: ## Exibe logs do docker-compose+ docker-compose logs -f++##@ Linting e Formatação++fmt: ## Formata o código+ @echo "$(GREEN)✨ Formatando código...$(NC)"+ $(GO) fmt ./...+ @echo "$(GREEN)✅ Código formatado$(NC)"++lint: ## Executa linter (requer golangci-lint)+ @echo "$(GREEN)🔍 Executando linter...$(NC)"+ @if command -v golangci-lint > /dev/null; then \+ golangci-lint run ./...; \+ echo "$(GREEN)✅ Lint completo$(NC)"; \+ else \+ echo "$(RED)❌ golangci-lint não instalado. Instale com: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest$(NC)"; \+ exit 1; \+ fi++vet: ## Executa go vet+ @echo "$(GREEN)🔍 Executando go vet...$(NC)"+ $(GO) vet ./...+ @echo "$(GREEN)✅ Vet completo$(NC)"++check: fmt vet lint test ## Executa todas as verificações++##@ Limpeza++clean: ## Remove arquivos de build+ @echo "$(YELLOW)🧹 Limpando arquivos de build...$(NC)"+ @rm -rf $(BUILD_DIR)+ @rm -f coverage.out coverage.html+ @echo "$(GREEN)✅ Limpeza completa$(NC)"++clean-all: clean ## Remove arquivos de build e cache+ @echo "$(YELLOW)🧹 Limpeza completa (incluindo cache)...$(NC)"+ $(GO) clean -cache -testcache -modcache+ @echo "$(GREEN)✅ Limpeza completa$(NC)"++##@ Utilitários++setup: deps swagger ## Setup completo do ambiente de desenvolvimento+ @echo "$(GREEN)🎉 Setup completo!$(NC)"+ @echo ""+ @echo "Para começar a desenvolver, rode:"+ @echo " $(YELLOW)make dev$(NC)"+ @echo ""+ @echo "Outros comandos úteis:"+ @echo " $(YELLOW)make help$(NC) - Ver todos os comandos"+ @echo " $(YELLOW)make test$(NC) - Rodar testes"+ @echo " $(YELLOW)make build$(NC) - Compilar a aplicação"++logs: ## Exibe logs da aplicação (se estiver rodando)+ @echo "$(GREEN)📋 Exibindo logs...$(NC)"+ @if [ -f "logs/app.log" ]; then \+ tail -f logs/app.log; \+ else \+ echo "$(YELLOW)⚠️ Arquivo de log não encontrado$(NC)"; \+ fi++version: ## Exibe versão do Go e dependências+ @echo "$(GREEN)📌 Versões:$(NC)"+ @$(GO) version+ @echo ""+ @echo "$(GREEN)Dependências principais:$(NC)"+ @$(GO) list -m all | grep -E '(whatsmeow|postgres|minio)'++status: ## Verifica status da aplicação+ @echo "$(GREEN)🔍 Verificando status...$(NC)"+ @curl -s http://localhost:4000/health || echo "$(RED)❌ Aplicação não está rodando$(NC)"++##@ Desenvolvimento Avançado++profile-cpu: ## Profile de CPU (requer aplicação rodando)+ @echo "$(GREEN)📊 Capturando profile de CPU...$(NC)"+ curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof+ $(GO) tool pprof -http=:8080 cpu.prof++profile-mem: ## Profile de memória (requer aplicação rodando)+ @echo "$(GREEN)📊 Capturando profile de memória...$(NC)"+ curl http://localhost:4000/debug/pprof/heap > mem.prof+ $(GO) tool pprof -http=:8080 mem.prof++generate: ## Roda go generate+ @echo "$(GREEN)⚙️ Executando go generate...$(NC)"+ $(GO) generate ./...++mod-graph: ## Exibe gráfico de dependências+ @echo "$(GREEN)📊 Gráfico de dependências:$(NC)"+ $(GO) mod graphdiff --git a/README.md b/README.mdnew file mode 100644index 0000000..bc89966--- /dev/null+++ b/README.md@@ -0,0 +1,224 @@+<h1 align="center">Evolution Go</h1>++<div align="center">++[](https://hub.docker.com/r/evoapicloud/evolution-go)+[](./LICENSE)+[](https://golang.org/)+[](https://github.com/EvolutionAPI/evolution-go/stargazers)+[](https://docs.evolutionfoundation.com.br)++</div>++<div align="center"><img src="./public/images/cover.png" width="400"></div>++## About++Evolution Go is a high-performance WhatsApp API built in Go, part of the [Evolution](https://evolutionfoundation.com.br/) ecosystem. It provides a robust, lightweight solution for WhatsApp integration using the [whatsmeow](https://github.com/tulir/whatsmeow) library.++## Features++- **High Performance** — Built with Go for minimal resource usage+- **RESTful API** — Clean, well-documented REST endpoints with Swagger+- **Real-time Events** — WebSocket, Webhook, AMQP/RabbitMQ and NATS support+- **Media Support** — Images, videos, audio, documents with MinIO/S3 storage+- **Message Storage** — Optional PostgreSQL persistence+- **QR Code Pairing** — Built-in QR code generation for device linking+- **License Management** — Built-in licensing with registration, activation, and heartbeat+- **Docker Ready** — Production-ready Docker configuration++## Quick Start++### Docker (Recommended)++```bash+git clone https://github.com/EvolutionAPI/evolution-go.git+cd evolution-go+make docker-build+make docker-run+```++### Local Development++```bash+git clone https://github.com/EvolutionAPI/evolution-go.git+cd evolution-go++# Clone whatsmeow dependency+git clone [email protected]:EvolutionAPI/whatsmeow.git whatsmeow-lib++# Setup, configure and run+make setup+cp .env.example .env+make dev+```++> Run `make help` to see all available commands. See [COMMANDS.md](./COMMANDS.md) for detailed workflows.++## Configuration++Create a `.env` file:++```env+# Server+SERVER_PORT=8080+CLIENT_NAME=evolution++# Security+GLOBAL_API_KEY=your-secure-api-key-here++# Database+POSTGRES_AUTH_DB=postgresql://postgres:password@localhost:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:password@localhost:5432/evogo_users?sslmode=disable+DATABASE_SAVE_MESSAGES=false++# Logging+WADEBUG=DEBUG+LOGTYPE=console++# Optional+# AMQP_URL=amqp://guest:guest@localhost:5672/+# NATS_URL=nats://localhost:4222+# WEBHOOK_URL=https://your-webhook-url.com/webhook+# MINIO_ENABLED=true+# MINIO_ENDPOINT=localhost:9000+# MINIO_ACCESS_KEY=minioadmin+# MINIO_SECRET_KEY=minioadmin+```++| Variable | Description | Default |+|----------|-------------|---------|+| `SERVER_PORT` | Server port | `8080` |+| `CLIENT_NAME` | Client identifier | `evolution` |+| `GLOBAL_API_KEY` | API authentication key | **Required** |+| `DATABASE_SAVE_MESSAGES` | Enable message storage | `false` |+| `WADEBUG` | WhatsApp debug level | `INFO` |++## License Activation++Evolution Go requires a license to operate. On first run:++1. Start the server — API endpoints return `503` until activated+2. Open the **Manager** at `http://localhost:8080/manager/login`+3. Enter your API URL and `GLOBAL_API_KEY`+4. Complete the license registration flow+5. Once activated, the API is fully operational++The license status persists in the database (`runtime_configs` table). Heartbeats are sent periodically to maintain activation.++## API Documentation++Swagger UI available at:++```+http://localhost:8080/swagger/index.html+```++### Key Endpoints++| Method | Endpoint | Description |+|--------|----------|-------------|+| `POST` | `/instance/create` | Create WhatsApp instance |+| `GET` | `/instance/{name}/qrcode` | Get QR code for pairing |+| `POST` | `/message/sendText` | Send text message |+| `POST` | `/message/sendMedia` | Send media message |+| `GET` | `/instance/{name}/status` | Get instance status |+| `DELETE` | `/instance/{name}` | Delete instance |++## Project Structure++```+evolution-go/+├── cmd/evolution-go/ # Application entry point+├── pkg/+│ ├── core/ # License management & middleware+│ ├── instance/ # Instance management+│ ├── message/ # Message handling+│ ├── sendMessage/ # Message sending+│ ├── routes/ # HTTP routes+│ ├── middleware/ # Auth & validation middleware+│ ├── config/ # Configuration+│ ├── events/ # Event producers (AMQP, NATS, Webhook, WS)+│ └── storage/ # Media storage (MinIO)+├── whatsmeow-lib/ # WhatsApp protocol library+├── docs/ # Swagger documentation+├── Dockerfile+├── Makefile+└── VERSION+```++## Technology Stack++| Component | Technology |+|-----------|-----------|+| Language | Go 1.24+ |+| HTTP Framework | Gin |+| WhatsApp | [whatsmeow](https://github.com/tulir/whatsmeow) |+| Database | PostgreSQL |+| ORM | GORM |+| Message Queue | RabbitMQ, NATS |+| Object Storage | MinIO/S3 |+| Documentation | Swagger/OpenAPI |+| Container | Docker |++## Documentation & Support++| Resource | Link |+|----------|------|+| Website | [evolutionfoundation.com.br](https://evolutionfoundation.com.br/) |+| Documentation | [docs.evolutionfoundation.com.br](https://docs.evolutionfoundation.com.br/) |+| Community | [evolutionfoundation.com.br/community](https://evolutionfoundation.com.br/community) |+| WhatsApp Support | [+55 31 7503-8350](https://wa.me/553175038350) |+| GitHub Issues | [evolution-go/issues](https://github.com/EvolutionAPI/evolution-go/issues) |++## Hosting++Deploy Evolution Go with optimized infrastructure:++| Product | Link |+|---------|------|+| Evolution Go VPS | [Hostgator - Evo Go](https://www.hostgator.com.br/52579-144-3-55.html) |+| Evolution API VPS | [Hostgator - Evo API](https://www.hostgator.com.br/servidor-vps/hospedagem-evo-api/lp-afiliado) |++## Contributing++1. Fork the repository+2. Create your feature branch (`git checkout -b feature/amazing-feature`)+3. Commit your changes (`git commit -m 'Add some amazing feature'`)+4. Push to the branch (`git push origin feature/amazing-feature`)+5. Open a Pull Request++## Security++For security concerns, please email: [email protected]++## License++Evolution Go is licensed under the Apache License 2.0, with the following additional conditions:++1. **Logo and copyright**: You may not remove or modify the logo or copyright information in the Evolution console or applications when using frontend components.++2. **Usage notification**: If Evolution Go is used as part of any project (including closed-source), a clear notification that Evolution Go is being utilized must be visible to system administrators.++Please contact [email protected] for licensing inquiries. Full license details at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0).++## Acknowledgments++- [whatsmeow](https://github.com/tulir/whatsmeow) by [tulir](https://github.com/tulir)+- [Evolution API](https://github.com/EvolutionAPI/evolution-api)++## Telemetry++Evolution Go collects anonymous telemetry data (routes used, API version) to improve the service. No sensitive or personal data is collected.++---++<div align="center">++**Evolution Go** — High-Performance WhatsApp API++Made with ❤️ by the [Evolution Team](https://evolutionfoundation.com.br/)++© 2025 Evolution Foundation++</div>diff --git a/VERSION b/VERSIONnew file mode 100644index 0000000..ee6cdce--- /dev/null+++ b/VERSION@@ -0,0 +1 @@+0.6.1diff --git a/cmd/evolution-go/main.go b/cmd/evolution-go/main.gonew file mode 100644index 0000000..3eccf86--- /dev/null+++ b/cmd/evolution-go/main.go@@ -0,0 +1,443 @@+package main++import (+ "context"+ "database/sql"+ "flag"+ "fmt"+ "log"+ "net/http"+ "os"+ "os/signal"+ "strings"+ "path/filepath"+ "syscall"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/gomessguii/logger"+ "github.com/joho/godotenv"+ "go.mau.fi/whatsmeow"+ "gorm.io/gorm"+ _ "modernc.org/sqlite"++ call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"+ call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"+ chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"+ chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"+ community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"+ community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"+ config "github.com/EvolutionAPI/evolution-go/pkg/config"+ "github.com/EvolutionAPI/evolution-go/pkg/core"+ producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"+ nats_producer "github.com/EvolutionAPI/evolution-go/pkg/events/nats"+ rabbitmq_producer "github.com/EvolutionAPI/evolution-go/pkg/events/rabbitmq"+ webhook_producer "github.com/EvolutionAPI/evolution-go/pkg/events/webhook"+ websocket_producer "github.com/EvolutionAPI/evolution-go/pkg/events/websocket"+ group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"+ group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"+ instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"+ instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"+ label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"+ label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"+ label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"+ label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"+ message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"+ message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"+ message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"+ auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"+ newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"+ newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"+ poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"+ routes "github.com/EvolutionAPI/evolution-go/pkg/routes"+ send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"+ send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"+ server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"+ storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"+ minio_storage "github.com/EvolutionAPI/evolution-go/pkg/storage/minio"+ "github.com/EvolutionAPI/evolution-go/pkg/telemetry"+ user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"+ user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ amqp "github.com/rabbitmq/amqp091-go"+)++var devMode = flag.Bool("dev", false, "Enable development mode")++var version = "dev"++func init() {+ if version == "dev" {+ if v, err := os.ReadFile("VERSION"); err == nil {+ version = strings.TrimSpace(string(v))+ }+ }+}++func setupRouter(db *gorm.DB, authDB *sql.DB, sqliteDB *sql.DB, config *config.Config, conn *amqp.Connection, exPath string, runtimeCtx *core.RuntimeContext) *gin.Engine {+ killChannel := make(map[string](chan bool))+ clientPointer := make(map[string]*whatsmeow.Client)++ loggerWrapper := logger_wrapper.NewLoggerManager(config)++ var rabbitmqProducer producer_interfaces.Producer+ if conn != nil {+ logger.LogInfo("RabbitMQ enabled")+ rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(+ conn,+ config.AmqpGlobalEnabled,+ config.AmqpGlobalEvents,+ config.AmqpSpecificEvents,+ config.AmqpUrl,+ loggerWrapper,+ )+ } else {+ // Even if initial connection failed, pass the URL so reconnection can work+ rabbitmqProducer = rabbitmq_producer.NewRabbitMQProducer(+ nil,+ config.AmqpGlobalEnabled,+ config.AmqpGlobalEvents,+ config.AmqpSpecificEvents,+ config.AmqpUrl, // Keep the URL for reconnection attempts+ loggerWrapper,+ )+ }++ var natsProducer producer_interfaces.Producer+ if config.NatsUrl != "" {+ logger.LogInfo("NATS enabled")+ natsProducer = nats_producer.NewNatsProducer(+ config.NatsUrl,+ config.NatsGlobalEnabled,+ config.NatsGlobalEvents,+ loggerWrapper,+ )+ } else {+ natsProducer = nats_producer.NewNatsProducer(+ "",+ false,+ nil,+ loggerWrapper,+ )+ }++ webhookProducer := webhook_producer.NewWebhookProducer(config.WebhookUrl, loggerWrapper)+ websocketProducer := websocket_producer.NewWebsocketProducer(loggerWrapper)++ // Cria filas globais se o RabbitMQ global estiver habilitado+ if config.AmqpGlobalEnabled && conn != nil {+ logger.LogInfo("Creating global RabbitMQ queues...")+ if err := rabbitmqProducer.CreateGlobalQueues(); err != nil {+ logger.LogError("Failed to create global RabbitMQ queues: %v", err)+ } else {+ logger.LogInfo("Global RabbitMQ queues created successfully")+ }+ }++ var mediaStorage storage_interfaces.MediaStorage+ var err error+ if config.MinioEnabled {+ mediaStorage, err = minio_storage.NewMinioMediaStorage(+ config.MinioEndpoint,+ config.MinioAccessKey,+ config.MinioSecretKey,+ config.MinioBucket,+ config.MinioRegion,+ config.MinioUseSSL,+ )+ if err != nil {+ log.Fatal(err)+ }+ }++ instanceRepository := instance_repository.NewInstanceRepository(db)+ messageRepository := message_repository.NewMessageRepository(db)+ labelRepository := label_repository.NewLabelRepository(db)++ whatsmeowService := whatsmeow_service.NewWhatsmeowService(+ instanceRepository,+ authDB,+ message_repository.NewMessageRepository(db),+ labelRepository,+ config,+ killChannel,+ clientPointer,+ rabbitmqProducer,+ webhookProducer,+ websocketProducer,+ sqliteDB,+ exPath,+ mediaStorage,+ natsProducer,+ loggerWrapper,+ )+ instanceService := instance_service.NewInstanceService(+ instanceRepository,+ killChannel,+ clientPointer,+ whatsmeowService,+ config,+ loggerWrapper,+ )+ sendMessageService := send_service.NewSendService(clientPointer, whatsmeowService, config, loggerWrapper)+ userService := user_service.NewUserService(clientPointer, whatsmeowService, loggerWrapper)+ messageService := message_service.NewMessageService(clientPointer, messageRepository, whatsmeowService, loggerWrapper)+ chatService := chat_service.NewChatService(clientPointer, whatsmeowService, loggerWrapper)+ groupService := group_service.NewGroupService(clientPointer, whatsmeowService, loggerWrapper)+ callService := call_service.NewCallService(clientPointer, whatsmeowService, loggerWrapper)+ communityService := community_service.NewCommunityService(clientPointer, whatsmeowService, loggerWrapper)+ labelService := label_service.NewLabelService(clientPointer, whatsmeowService, labelRepository, loggerWrapper)+ newsletterService := newsletter_service.NewNewsletterService(clientPointer, whatsmeowService, loggerWrapper)++ // NOVO: PollHandler usando PollService já inicializado no whatsmeowService (evita dupla inicialização)+ pollHandler := poll_handler.NewPollHandler(whatsmeowService.GetPollService(), loggerWrapper)++ telemetry := telemetry.NewTelemetryService()++ r := gin.Default()++ // CORS middleware — must be before everything else+ r.Use(func(c *gin.Context) {+ c.Writer.Header().Set("Access-Control-Allow-Origin", "*")+ c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")+ c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")+ c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey")+ c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")+ if c.Request.Method == "OPTIONS" {+ c.AbortWithStatus(200)+ return+ }+ c.Next()+ })++ r.Use(telemetry.TelemetryMiddleware())++ r.Use(core.GateMiddleware(runtimeCtx))++ // License routes (always accessible, even without license)+ core.LicenseRoutes(r, runtimeCtx)++ routes.NewRouter(+ auth_middleware.NewMiddleware(config, instanceService),+ instance_handler.NewInstanceHandler(instanceService, config),+ user_handler.NewUserHandler(userService),+ send_handler.NewSendHandler(sendMessageService),+ message_handler.NewMessageHandler(messageService),+ chat_handler.NewChatHandler(chatService),+ group_handler.NewGroupHandler(groupService),+ call_handler.NewCallHandler(callService),+ community_handler.NewCommunityHandler(communityService),+ label_handler.NewLabelHandler(labelService),+ newsletter_handler.NewNewsletterHandler(newsletterService),+ pollHandler,+ server_handler.NewServerHandler(),+ ).AssignRoutes(r)++ if config.ConnectOnStartup {+ go whatsmeowService.ConnectOnStartup(config.ClientName)+ }++ r.GET("/ws", func(c *gin.Context) {+ token := c.Query("token")+ instanceId := c.Query("instanceId")++ if token != config.GlobalApiKey {+ logger.LogError("Token inválido: %s", token)+ c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido"})+ return+ }++ websocket_producer.ServeWs(c.Writer, c.Request, instanceId, websocketProducer)+ })++ return r+}++func migrate(db *gorm.DB) {+ err := db.AutoMigrate(&instance_model.Instance{}, &message_model.Message{}, &label_model.Label{})++ if err != nil {+ log.Fatal(err)+ }+}++func initAuthDB(config *config.Config) (*sql.DB, string, error) {+ if config.PostgresAuthDB != "" {+ return nil, "", nil+ }++ ex, err := os.Executable()+ if err != nil {+ panic(err)+ }+ exPath := filepath.Dir(ex)++ dbDirectory := exPath + "/dbdata"+ _, err = os.Stat(dbDirectory)+ if os.IsNotExist(err) {+ errDir := os.MkdirAll(dbDirectory, 0751)+ if errDir != nil {+ panic("Could not create dbdata directory")+ }+ }++ db, err := sql.Open("sqlite", exPath+"/dbdata/users.db?_pragma=foreign_keys(1)&_busy_timeout=3000")+ if err != nil {+ return nil, "", err+ }++ return db, exPath, nil+}++func initPostgresAuthDB(config *config.Config) (*sql.DB, error) {+ if config.PostgresAuthDB == "" {+ return nil, nil+ }++ if err := config.EnsureDBExists(config.PostgresAuthDB); err != nil {+ logger.LogWarn("Auto-setup auth DB failed (will try connecting anyway): %v", err)+ }++ db, err := sql.Open("postgres", config.PostgresAuthDB)+ if err != nil {+ return nil, fmt.Errorf("erro ao conectar ao banco AUTH PostgreSQL: %v", err)+ }++ // Configurar pool de conexões para evitar conexões ociosas não fechadas+ db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente+ db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool+ db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts+ db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto++ err = db.Ping()+ if err != nil {+ return nil, fmt.Errorf("erro ao pingar banco AUTH PostgreSQL: %v", err)+ }++ logger.LogInfo("Conectado ao banco AUTH PostgreSQL com pool configurado")+ return db, nil+}++// @title Evolution GO+// @version 1.0+// @description Evolution GO - whatsmeow+func main() {+ flag.Parse()+ if *devMode {+ err := godotenv.Load(".env")+ if err != nil {+ log.Fatal(err)+ }+ }++ cfg := config.Load()++ logger.LogInfo("Starting Evolution GO version %s", version)++ startTime := time.Now()++ db, err := cfg.CreateUsersDB()+ if err != nil {+ log.Fatal(err)+ }++ // Inicializar PostgreSQL AUTH+ authDB, err := initPostgresAuthDB(cfg)+ if err != nil {+ log.Fatal(err)+ }+ if authDB != nil {+ defer authDB.Close()+ }++ // Manter inicialização do SQLite+ sqliteDB, exPath, err := initAuthDB(cfg)+ if err != nil {+ log.Fatal(err)+ }+ if sqliteDB != nil {+ defer sqliteDB.Close()+ }++ migrate(db)++ // Initialize core DB + license runtime+ core.SetDB(db)+ if err := core.MigrateDB(); err != nil {+ log.Fatal("Failed to migrate runtime_configs: ", err)+ }+ tier := "evolution-go"+ runtimeCtx := core.InitializeRuntime(tier, version, cfg.GlobalApiKey)++ var conn *amqp.Connection++ if cfg.AmqpUrl != "" {+ logger.LogInfo("Attempting to connect to RabbitMQ...")++ // Create connection with heartbeat to prevent timeouts+ amqpConfig := amqp.Config{+ Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds+ Locale: "en_US",+ }++ conn, err = amqp.DialConfig(cfg.AmqpUrl, amqpConfig)+ if err != nil {+ logger.LogError("Failed to connect to RabbitMQ, err: %v", err)+ logger.LogInfo("RabbitMQ producer will be created with reconnection capability")+ } else {+ logger.LogInfo("Successfully connected to RabbitMQ with heartbeat enabled")+ defer func(conn *amqp.Connection) {+ err := conn.Close()+ if err != nil {+ logger.LogError("Failed to close RabbitMQ connection, err: %v", err)+ }+ }(conn)+ }+ } else {+ logger.LogInfo("RabbitMQ URL not configured, skipping RabbitMQ connection")+ }++ r := setupRouter(db, authDB, sqliteDB, cfg, conn, exPath, runtimeCtx)++ // Graceful shutdown with heartbeat+ heartbeatCtx, heartbeatCancel := context.WithCancel(context.Background())+ defer heartbeatCancel()++ core.StartHeartbeat(heartbeatCtx, runtimeCtx, startTime)++ srv := &http.Server{+ Addr: ":" + os.Getenv("SERVER_PORT"),+ Handler: r,+ }++ quit := make(chan os.Signal, 1)+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)++ go func() {+ logger.LogInfo("Iniciando servidor na porta %s", os.Getenv("SERVER_PORT"))+ if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {+ log.Fatalf("server error: %v", err)+ }+ }()++ <-quit+ logger.LogInfo("[SHUTDOWN] Signal received, shutting down...")++ // Stop heartbeat loop+ heartbeatCancel()++ core.Shutdown(runtimeCtx)++ shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer shutdownCancel()++ if err := srv.Shutdown(shutdownCtx); err != nil {+ logger.LogError("[SHUTDOWN] Server forced to shutdown: %v", err)+ }++ logger.LogInfo("[SHUTDOWN] Server exited")+}diff --git a/docker/examples/.env.example b/docker/examples/.env.examplenew file mode 100644index 0000000..a72c0b4--- /dev/null+++ b/docker/examples/.env.example@@ -0,0 +1,128 @@+# Evolution GO - Configuração de Ambiente+# Copie este arquivo para .env e ajuste conforme necessário++# ========================================+# CONFIGURAÇÕES OBRIGATÓRIAS+# ========================================++# Porta do servidor+SERVER_PORT=4000++# Nome do cliente/instância+CLIENT_NAME=evolution++# Chave de API (OBRIGATÓRIO - Use uma chave forte e única)+GLOBAL_API_KEY=sua-chave-api-segura-aqui-uuid-recomendado++# ========================================+# BANCO DE DADOS+# ========================================++# PostgreSQL (RECOMENDADO para produção)+POSTGRES_AUTH_DB=postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable++# Salvar mensagens no banco de dados+DATABASE_SAVE_MESSAGES=false++# ========================================+# LOGS E DEBUG+# ========================================++# Nível de debug do WhatsApp (INFO, DEBUG, ERROR)+WADEBUG=INFO++# Tipo de log (console, file)+LOGTYPE=console++# Diretório de logs+LOG_DIRECTORY=/app/logs++# Tamanho máximo do arquivo de log em MB+LOG_MAX_SIZE=100++# Número máximo de arquivos de backup+LOG_MAX_BACKUPS=5++# Dias de retenção dos logs+LOG_MAX_AGE=30++# Comprimir logs antigos+LOG_COMPRESS=true++# ========================================+# CONEXÃO+# ========================================++# Conectar automaticamente ao iniciar+CONNECT_ON_STARTUP=false++# Enviar arquivos via webhook+WEBHOOKFILES=true++# Nome do sistema operacional+OS_NAME=Linux++# ========================================+# EVENTOS E WEBHOOKS+# ========================================++# URL do webhook para receber eventos+WEBHOOK_URL=++# RabbitMQ+AMQP_URL=+AMQP_GLOBAL_ENABLED=false+AMQP_GLOBAL_EVENTS=+AMQP_SPECIFIC_EVENTS=++# NATS+NATS_URL=+NATS_GLOBAL_ENABLED=false+NATS_GLOBAL_EVENTS=++# Ignorar eventos de grupos+EVENT_IGNORE_GROUP=false++# Ignorar eventos de status+EVENT_IGNORE_STATUS=true++# ========================================+# ARMAZENAMENTO DE MÍDIA (MinIO/S3)+# ========================================++MINIO_ENABLED=false+MINIO_ENDPOINT=+MINIO_ACCESS_KEY=+MINIO_SECRET_KEY=+MINIO_BUCKET=+MINIO_USE_SSL=false+MINIO_REGION=++# ========================================+# PROXY (Opcional)+# ========================================++PROXY_HOST=+PROXY_PORT=+PROXY_USERNAME=+PROXY_PASSWORD=++# ========================================+# RECURSOS ADICIONAIS+# ========================================++# API de conversão de áudio+API_AUDIO_CONVERTER=+API_AUDIO_CONVERTER_KEY=++# Número máximo de tentativas de QR Code+QRCODE_MAX_COUNT=5++# Verificar se o usuário existe antes de enviar mensagem+CHECK_USER_EXISTS=true++# Versão do WhatsApp (opcional - deixe vazio para usar a padrão)+WHATSAPP_VERSION_MAJOR=+WHATSAPP_VERSION_MINOR=+WHATSAPP_VERSION_PATCH=diff --git a/docker/examples/docker-compose.full.yml b/docker/examples/docker-compose.full.ymlnew file mode 100644index 0000000..31c36f7--- /dev/null+++ b/docker/examples/docker-compose.full.yml@@ -0,0 +1,144 @@+version: '3.8'++services:+ evolution-go:+ image: evoapicloud/evolution-go:latest+ container_name: evolution-go+ restart: unless-stopped+ ports:+ - "4000:4000"+ environment:+ # Servidor+ SERVER_PORT: 4000+ CLIENT_NAME: "evolution"++ # Segurança+ GLOBAL_API_KEY: "sua-chave-api-segura-aqui"++ # Banco de Dados PostgreSQL+ POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"+ POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"+ DATABASE_SAVE_MESSAGES: "true"++ # Logs e Debug+ WADEBUG: "DEBUG"+ LOGTYPE: "console"+ LOG_DIRECTORY: "/app/logs"+ LOG_MAX_SIZE: "100"+ LOG_MAX_BACKUPS: "5"+ LOG_MAX_AGE: "30"+ LOG_COMPRESS: "true"++ # Conexão+ CONNECT_ON_STARTUP: "false"+ WEBHOOKFILES: "true"++ # Sistema+ OS_NAME: "Linux"++ # Webhook+ WEBHOOK_URL: "https://seu-webhook.com/endpoint"++ # RabbitMQ+ AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default"+ AMQP_GLOBAL_ENABLED: "true"+ AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update"+ AMQP_SPECIFIC_EVENTS: ""++ # NATS+ NATS_URL: "nats://nats:4222"+ NATS_GLOBAL_ENABLED: "false"+ NATS_GLOBAL_EVENTS: ""++ # MinIO+ MINIO_ENABLED: "true"+ MINIO_ENDPOINT: "minio:9000"+ MINIO_ACCESS_KEY: "minioadmin"+ MINIO_SECRET_KEY: "minioadmin"+ MINIO_BUCKET: "evolution-media"+ MINIO_USE_SSL: "false"+ MINIO_REGION: "us-east-1"++ # Eventos+ EVENT_IGNORE_GROUP: "false"+ EVENT_IGNORE_STATUS: "true"++ # QR Code+ QRCODE_MAX_COUNT: "5"++ # Verificação de Usuário+ CHECK_USER_EXISTS: "true"++ volumes:+ - evolution_data:/app/dbdata+ - evolution_logs:/app/logs+ networks:+ - evolution_network+ depends_on:+ - postgres+ - rabbitmq+ - minio++ postgres:+ image: postgres:15-alpine+ container_name: evolution-postgres+ restart: unless-stopped+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: postgres+ ports:+ - "5432:5432"+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql+ networks:+ - evolution_network++ rabbitmq:+ image: rabbitmq:3-management-alpine+ container_name: evolution-rabbitmq+ restart: unless-stopped+ environment:+ RABBITMQ_DEFAULT_USER: admin+ RABBITMQ_DEFAULT_PASS: admin+ RABBITMQ_DEFAULT_VHOST: default+ ports:+ - "5672:5672"+ - "15672:15672"+ volumes:+ - rabbitmq_data:/var/lib/rabbitmq+ networks:+ - evolution_network++ minio:+ image: minio/minio:latest+ container_name: evolution-minio+ restart: unless-stopped+ command: server /data --console-address ":9001"+ environment:+ MINIO_ROOT_USER: minioadmin+ MINIO_ROOT_PASSWORD: minioadmin+ ports:+ - "9000:9000"+ - "9001:9001"+ volumes:+ - minio_data:/data+ networks:+ - evolution_network++volumes:+ evolution_data:+ driver: local+ evolution_logs:+ driver: local+ postgres_data:+ driver: local+ rabbitmq_data:+ driver: local+ minio_data:+ driver: local++networks:+ evolution_network:+ driver: bridgediff --git a/docker/examples/docker-compose.swarm.yml b/docker/examples/docker-compose.swarm.ymlnew file mode 100644index 0000000..b764f28--- /dev/null+++ b/docker/examples/docker-compose.swarm.yml@@ -0,0 +1,102 @@+version: '3.8'++services:+ evolution_go:+ image: evoapicloud/evolution-go:latest+ networks:+ - network_public+ environment:+ # Servidor+ SERVER_PORT: 4000+ CLIENT_NAME: "evolution"++ # Segurança (OBRIGATÓRIO)+ GLOBAL_API_KEY: "sua-chave-api-segura-aqui"++ # Banco de Dados PostgreSQL (RECOMENDADO)+ POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable"+ POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable"+ DATABASE_SAVE_MESSAGES: "false"++ # Logs e Debug+ WADEBUG: "INFO"+ LOGTYPE: "console"+ LOG_DIRECTORY: "/app/logs"+ LOG_MAX_SIZE: "100"+ LOG_MAX_BACKUPS: "5"+ LOG_MAX_AGE: "30"+ LOG_COMPRESS: "true"++ # Conexão+ CONNECT_ON_STARTUP: "true"+ WEBHOOKFILES: "true"++ # Sistema+ OS_NAME: "Linux"++ # Conversor de Áudio (Opcional)+ API_AUDIO_CONVERTER: ""+ API_AUDIO_CONVERTER_KEY: ""++ # Proxy (Opcional)+ PROXY_HOST: ""+ PROXY_PORT: ""+ PROXY_USERNAME: ""+ PROXY_PASSWORD: ""++ # RabbitMQ (Opcional)+ AMQP_URL: ""+ AMQP_GLOBAL_ENABLED: "false"+ AMQP_GLOBAL_EVENTS: ""++ # NATS (Opcional)+ NATS_URL: ""+ NATS_GLOBAL_ENABLED: "false"++ # Eventos+ EVENT_IGNORE_GROUP: "false"+ EVENT_IGNORE_STATUS: "true"++ # MinIO/S3 (Opcional)+ MINIO_ENABLED: "false"+ MINIO_ENDPOINT: ""+ MINIO_ACCESS_KEY: ""+ MINIO_SECRET_KEY: ""+ MINIO_BUCKET: ""+ MINIO_USE_SSL: "false"++ volumes:+ - evolution_go_data:/app/dbdata+ - evolution_go_logs:/app/logs++ deploy:+ replicas: 1+ placement:+ constraints:+ - node.role == manager+ restart_policy:+ condition: on-failure+ delay: 5s+ max_attempts: 3+ labels:+ # Traefik Labels (ajuste conforme necessário)+ - traefik.enable=true+ - traefik.http.routers.evolution_go.rule=Host(`evolution.seudominio.com`)+ - traefik.http.routers.evolution_go.entrypoints=websecure+ - traefik.http.routers.evolution_go.tls.certresolver=letsencryptresolver+ - traefik.http.routers.evolution_go.service=evolution_go+ - traefik.http.services.evolution_go.loadbalancer.server.port=4000+ - traefik.http.services.evolution_go.loadbalancer.passHostHeader=true++volumes:+ evolution_go_data:+ external: true+ name: evolution_go_data+ evolution_go_logs:+ external: true+ name: evolution_go_logs++networks:+ network_public:+ external: true+ name: network_publicdiff --git a/docker/examples/docker-compose.yml b/docker/examples/docker-compose.ymlnew file mode 100644index 0000000..2714e16--- /dev/null+++ b/docker/examples/docker-compose.yml@@ -0,0 +1,96 @@+version: '3.8'++services:+ evolution-go:+ image: evoapicloud/evolution-go:latest+ container_name: evolution-go+ restart: unless-stopped+ ports:+ - "4000:4000"+ environment:+ # Servidor+ SERVER_PORT: 4000+ CLIENT_NAME: "evolution"++ # Segurança (OBRIGATÓRIO)+ GLOBAL_API_KEY: "sua-chave-api-segura-aqui"++ # Banco de Dados PostgreSQL (RECOMENDADO)+ POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"+ POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"+ DATABASE_SAVE_MESSAGES: "false"++ # Logs e Debug+ WADEBUG: "INFO"+ LOGTYPE: "console"+ LOG_DIRECTORY: "/app/logs"+ LOG_MAX_SIZE: "100"+ LOG_MAX_BACKUPS: "5"+ LOG_MAX_AGE: "30"+ LOG_COMPRESS: "true"++ # Conexão+ CONNECT_ON_STARTUP: "false"+ WEBHOOKFILES: "true"++ # Sistema+ OS_NAME: "Linux"++ # Eventos (Opcionais)+ WEBHOOK_URL: ""+ AMQP_URL: ""+ AMQP_GLOBAL_ENABLED: "false"+ NATS_URL: ""+ NATS_GLOBAL_ENABLED: "false"++ # Armazenamento de Mídia (Opcional)+ MINIO_ENABLED: "false"++ # Proxy (Opcional)+ PROXY_HOST: ""+ PROXY_PORT: ""+ PROXY_USERNAME: ""+ PROXY_PASSWORD: ""++ # Eventos+ EVENT_IGNORE_GROUP: "false"+ EVENT_IGNORE_STATUS: "true"++ # QR Code+ QRCODE_MAX_COUNT: "5"++ volumes:+ - evolution_data:/app/dbdata+ - evolution_logs:/app/logs+ networks:+ - evolution_network+ depends_on:+ - postgres++ postgres:+ image: postgres:15-alpine+ container_name: evolution-postgres+ restart: unless-stopped+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: postgres+ ports:+ - "5432:5432"+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql+ networks:+ - evolution_network++volumes:+ evolution_data:+ driver: local+ evolution_logs:+ driver: local+ postgres_data:+ driver: local++networks:+ evolution_network:+ driver: bridgediff --git a/docker/examples/init-db.sql b/docker/examples/init-db.sqlnew file mode 100644index 0000000..b623573--- /dev/null+++ b/docker/examples/init-db.sql@@ -0,0 +1,10 @@+-- Script de inicialização dos bancos de dados Evolution GO++-- Criar database para autenticação+CREATE DATABASE evogo_auth;++-- Criar database para dados de usuários+CREATE DATABASE evogo_users;++-- Mensagem de confirmação+SELECT 'Databases evogo_auth e evogo_users criados com sucesso!' as message;diff --git a/docs/docs.go b/docs/docs.gonew file mode 100644index 0000000..0843d82--- /dev/null+++ b/docs/docs.go@@ -0,0 +1,3299 @@+// Package docs Code generated by swaggo/swag. DO NOT EDIT+package docs++import "github.com/swaggo/swag"++const docTemplate = `{+ "schemes": {{ marshal .Schemes }},+ "swagger": "2.0",+ "info": {+ "description": "{{escape .Description}}",+ "title": "{{.Title}}",+ "contact": {},+ "version": "{{.Version}}"+ },+ "host": "{{.Host}}",+ "basePath": "{{.BasePath}}",+ "paths": {+ "/chat/archive": {+ "post": {+ "description": "Archive a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Archive a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/mute": {+ "post": {+ "description": "Mute a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Mute a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/pin": {+ "post": {+ "description": "Pin a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Pin a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/unpin": {+ "post": {+ "description": "Unpin a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Unpin a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/add": {+ "post": {+ "description": "Add participant to community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Add participant to community",+ "parameters": [+ {+ "description": "Participant data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/create": {+ "post": {+ "description": "Create community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Create community",+ "parameters": [+ {+ "description": "Community data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/remove": {+ "post": {+ "description": "Remove participant from community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Remove participant from community",+ "parameters": [+ {+ "description": "Participant data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/create": {+ "post": {+ "description": "Create group",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Create group",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/info": {+ "post": {+ "description": "Get group info",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get group info",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/invitelink": {+ "post": {+ "description": "Get group invite link",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get group invite link",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/join": {+ "post": {+ "description": "Join group link",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Join group link",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/list": {+ "get": {+ "description": "List groups",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "List groups",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/myall": {+ "get": {+ "description": "Get my groups",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get my groups",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/name": {+ "post": {+ "description": "Set group name",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Set group name",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/participant": {+ "post": {+ "description": "Update participant",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Update participant",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/photo": {+ "post": {+ "description": "Set group photo",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Set group photo",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/all": {+ "get": {+ "description": "Get all instances",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get all instances",+ "responses": {+ "200": {+ "description": "All instances",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/connect": {+ "post": {+ "description": "Connect to instance with the provided data",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Connect to instance",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Instance connected successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/create": {+ "post": {+ "description": "Creates a new instance with the provided data",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Create a new instance",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Instance created successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/delete/{instanceId}": {+ "delete": {+ "description": "Delete instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Delete instance",+ "parameters": [+ {+ "type": "string",+ "description": "Instance Id",+ "name": "instanceId",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Instance deleted successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/disconnect": {+ "post": {+ "description": "Disconnect from instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Disconnect from instance",+ "responses": {+ "200": {+ "description": "Instance disconnected successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/logout": {+ "delete": {+ "description": "Logout from instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Logout from instance",+ "responses": {+ "200": {+ "description": "Instance logged out successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/pair": {+ "post": {+ "description": "Request pairing code",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Request pairing code",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Pairing code",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/proxy/{instanceId}": {+ "delete": {+ "description": "Delete proxy",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Delete proxy",+ "parameters": [+ {+ "type": "string",+ "description": "Instance id",+ "name": "instanceId",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Proxy deleted successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/qr": {+ "get": {+ "description": "Get instance QR code",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get instance QR code",+ "responses": {+ "200": {+ "description": "Instance QR code",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/status": {+ "get": {+ "description": "Get instance status",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get instance status",+ "responses": {+ "200": {+ "description": "Instance status",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/chat": {+ "post": {+ "description": "Add label to chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Add label to chat",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/edit": {+ "post": {+ "description": "Edit label",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Edit label",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/message": {+ "post": {+ "description": "Add label to message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Add label to message",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/delete": {+ "post": {+ "description": "Delete a message for everyone",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Delete a message for everyone",+ "parameters": [+ {+ "description": "Delete a message for everyone",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/downloadimage": {+ "post": {+ "description": "Download an image",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Download an image",+ "parameters": [+ {+ "description": "Download an image",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/edit": {+ "post": {+ "description": "Edit a message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Edit a message",+ "parameters": [+ {+ "description": "Edit a message",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/markread": {+ "post": {+ "description": "Mark a message as read",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Mark a message as read",+ "parameters": [+ {+ "description": "Mark a message as read",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/presence": {+ "post": {+ "description": "Set chat presence",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Set chat presence",+ "parameters": [+ {+ "description": "Set chat presence",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/react": {+ "post": {+ "description": "React a message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "React a message",+ "parameters": [+ {+ "description": "React a message",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/status": {+ "post": {+ "description": "Get message status",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Get message status",+ "parameters": [+ {+ "description": "Get message status",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/create": {+ "post": {+ "description": "Create newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Create newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/info": {+ "post": {+ "description": "Get newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/link": {+ "post": {+ "description": "Get newsletter invite",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter invite",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/list": {+ "get": {+ "description": "List newsletters",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "List newsletters",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/messages": {+ "post": {+ "description": "Get newsletter messages",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter messages",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/subscribe": {+ "post": {+ "description": "Subscribe newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Subscribe newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/contact": {+ "post": {+ "description": "Send a contact message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a contact message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/link": {+ "post": {+ "description": "Send a link message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a link message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/location": {+ "post": {+ "description": "Send a location message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a location message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/media": {+ "post": {+ "description": "Send a media message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a media message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/poll": {+ "post": {+ "description": "Send a poll message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a poll message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/sticker": {+ "post": {+ "description": "Send a sticker message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a sticker message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/text": {+ "post": {+ "description": "Send a text message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a text message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/unlabel/chat": {+ "post": {+ "description": "Remove label from chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Remove label from chat",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/unlabel/message": {+ "post": {+ "description": "Remove label from message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Remove label from message",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/avatar": {+ "post": {+ "description": "Get a user's avatar",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's avatar",+ "parameters": [+ {+ "description": "Avatar data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/block": {+ "post": {+ "description": "Block a contact",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Block a contact",+ "parameters": [+ {+ "description": "Block data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/blocklist": {+ "get": {+ "description": "Get a user's block list",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's block list",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/check": {+ "post": {+ "description": "Check a user",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Check a user",+ "parameters": [+ {+ "description": "User data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/contacts": {+ "get": {+ "description": "Get a user's contacts",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's contacts",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/info": {+ "post": {+ "description": "Get a user",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user",+ "parameters": [+ {+ "description": "User data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/privacy": {+ "get": {+ "description": "Get a user's privacy settings",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's privacy settings",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/profile": {+ "post": {+ "description": "Set a user's profile picture",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Set a user's profile picture",+ "parameters": [+ {+ "description": "Profile picture data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/unblock": {+ "post": {+ "description": "Unblock a contact",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Unblock a contact",+ "parameters": [+ {+ "description": "Block data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ }+ },+ "definitions": {+ "gin.H": {+ "type": "object",+ "additionalProperties": {}+ },+ "github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct": {+ "type": "object",+ "properties": {+ "communityJid": {+ "type": "string"+ },+ "groupJid": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct": {+ "type": "object",+ "properties": {+ "communityName": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct": {+ "type": "object",+ "properties": {+ "action": {+ "$ref": "#/definitions/whatsmeow.ParticipantChange"+ },+ "groupJid": {+ "$ref": "#/definitions/types.JID"+ },+ "participants": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct": {+ "type": "object",+ "properties": {+ "groupName": {+ "type": "string"+ },+ "participants": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "reset": {+ "type": "boolean"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "image": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct": {+ "type": "object",+ "properties": {+ "immediate": {+ "type": "boolean"+ },+ "phone": {+ "type": "string"+ },+ "subscribe": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "webhookUrl": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "proxy": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig"+ },+ "token": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct": {+ "type": "object",+ "properties": {+ "phone": {+ "type": "string"+ },+ "subscribe": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig": {+ "type": "object",+ "properties": {+ "address": {+ "type": "string"+ },+ "password": {+ "type": "string"+ },+ "port": {+ "type": "string"+ },+ "username": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "type": "string"+ },+ "labelId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct": {+ "type": "object",+ "properties": {+ "color": {+ "type": "integer"+ },+ "deleted": {+ "type": "boolean"+ },+ "labelId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "type": "string"+ },+ "labelId": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct": {+ "type": "object",+ "properties": {+ "isAudio": {+ "type": "boolean"+ },+ "number": {+ "type": "string"+ },+ "state": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct": {+ "type": "object",+ "properties": {+ "directPath": {+ "type": "string"+ },+ "fileEncSHA256": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "fileLength": {+ "type": "integer"+ },+ "fileSHA256": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "mediaKey": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "mimetype": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "number": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "reaction": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct": {+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct": {+ "type": "object",+ "properties": {+ "before_id": {+ "type": "integer"+ },+ "count": {+ "type": "integer"+ },+ "jid": {+ "$ref": "#/definitions/types.JID"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "$ref": "#/definitions/types.JID"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "vcard": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "description": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "imgUrl": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "text": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct": {+ "type": "object",+ "properties": {+ "address": {+ "type": "string"+ },+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "latitude": {+ "type": "number"+ },+ "longitude": {+ "type": "number"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct": {+ "type": "object",+ "properties": {+ "caption": {+ "type": "string"+ },+ "delay": {+ "type": "integer"+ },+ "filename": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "type": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "maxAnswer": {+ "type": "integer"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "options": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "question": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct": {+ "type": "object",+ "properties": {+ "messageId": {+ "type": "string"+ },+ "participant": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "sticker": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "text": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "string"+ },+ "preview": {+ "type": "boolean"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct": {+ "type": "object",+ "properties": {+ "image": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct": {+ "type": "object",+ "properties": {+ "fullName": {+ "type": "string"+ },+ "organization": {+ "type": "string"+ },+ "phone": {+ "type": "string"+ }+ }+ },+ "types.JID": {+ "type": "object",+ "properties": {+ "device": {+ "type": "integer"+ },+ "integrator": {+ "type": "integer"+ },+ "rawAgent": {+ "type": "integer"+ },+ "server": {+ "type": "string"+ },+ "user": {+ "type": "string"+ }+ }+ },+ "whatsmeow.ParticipantChange": {+ "type": "string",+ "enum": [+ "add",+ "remove",+ "promote",+ "demote"+ ],+ "x-enum-varnames": [+ "ParticipantChangeAdd",+ "ParticipantChangeRemove",+ "ParticipantChangePromote",+ "ParticipantChangeDemote"+ ]+ }+ }+}`++// SwaggerInfo holds exported Swagger Info so clients can modify it+var SwaggerInfo = &swag.Spec{+ Version: "1.0",+ Host: "",+ BasePath: "",+ Schemes: []string{},+ Title: "Evolution GO",+ Description: "Evolution GO - whatsmeow",+ InfoInstanceName: "swagger",+ SwaggerTemplate: docTemplate,+ LeftDelim: "{{",+ RightDelim: "}}",+}++func init() {+ swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)+}diff --git a/docs/swagger.json b/docs/swagger.jsonnew file mode 100644index 0000000..b264746--- /dev/null+++ b/docs/swagger.json@@ -0,0 +1,3273 @@+{+ "swagger": "2.0",+ "info": {+ "description": "Evolution GO - whatsmeow",+ "title": "Evolution GO",+ "contact": {},+ "version": "1.0"+ },+ "paths": {+ "/chat/archive": {+ "post": {+ "description": "Archive a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Archive a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/mute": {+ "post": {+ "description": "Mute a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Mute a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/pin": {+ "post": {+ "description": "Pin a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Pin a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/chat/unpin": {+ "post": {+ "description": "Unpin a chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Chat"+ ],+ "summary": "Unpin a chat",+ "parameters": [+ {+ "description": "Chat",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/add": {+ "post": {+ "description": "Add participant to community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Add participant to community",+ "parameters": [+ {+ "description": "Participant data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/create": {+ "post": {+ "description": "Create community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Create community",+ "parameters": [+ {+ "description": "Community data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/community/remove": {+ "post": {+ "description": "Remove participant from community",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Community"+ ],+ "summary": "Remove participant from community",+ "parameters": [+ {+ "description": "Participant data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/create": {+ "post": {+ "description": "Create group",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Create group",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/info": {+ "post": {+ "description": "Get group info",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get group info",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/invitelink": {+ "post": {+ "description": "Get group invite link",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get group invite link",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/join": {+ "post": {+ "description": "Join group link",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Join group link",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/list": {+ "get": {+ "description": "List groups",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "List groups",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/myall": {+ "get": {+ "description": "Get my groups",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Get my groups",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/name": {+ "post": {+ "description": "Set group name",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Set group name",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/participant": {+ "post": {+ "description": "Update participant",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Update participant",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/group/photo": {+ "post": {+ "description": "Set group photo",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Group"+ ],+ "summary": "Set group photo",+ "parameters": [+ {+ "description": "Group data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/all": {+ "get": {+ "description": "Get all instances",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get all instances",+ "responses": {+ "200": {+ "description": "All instances",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/connect": {+ "post": {+ "description": "Connect to instance with the provided data",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Connect to instance",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Instance connected successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/create": {+ "post": {+ "description": "Creates a new instance with the provided data",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Create a new instance",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Instance created successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/delete/{instanceId}": {+ "delete": {+ "description": "Delete instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Delete instance",+ "parameters": [+ {+ "type": "string",+ "description": "Instance Id",+ "name": "instanceId",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Instance deleted successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/disconnect": {+ "post": {+ "description": "Disconnect from instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Disconnect from instance",+ "responses": {+ "200": {+ "description": "Instance disconnected successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/logout": {+ "delete": {+ "description": "Logout from instance",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Logout from instance",+ "responses": {+ "200": {+ "description": "Instance logged out successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/pair": {+ "post": {+ "description": "Request pairing code",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Request pairing code",+ "parameters": [+ {+ "description": "Instance data",+ "name": "instance",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Pairing code",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/proxy/{instanceId}": {+ "delete": {+ "description": "Delete proxy",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Delete proxy",+ "parameters": [+ {+ "type": "string",+ "description": "Instance id",+ "name": "instanceId",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "200": {+ "description": "Proxy deleted successfully",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/qr": {+ "get": {+ "description": "Get instance QR code",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get instance QR code",+ "responses": {+ "200": {+ "description": "Instance QR code",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/instance/status": {+ "get": {+ "description": "Get instance status",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Instance"+ ],+ "summary": "Get instance status",+ "responses": {+ "200": {+ "description": "Instance status",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/chat": {+ "post": {+ "description": "Add label to chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Add label to chat",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/edit": {+ "post": {+ "description": "Edit label",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Edit label",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/label/message": {+ "post": {+ "description": "Add label to message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Add label to message",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/delete": {+ "post": {+ "description": "Delete a message for everyone",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Delete a message for everyone",+ "parameters": [+ {+ "description": "Delete a message for everyone",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/downloadimage": {+ "post": {+ "description": "Download an image",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Download an image",+ "parameters": [+ {+ "description": "Download an image",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/edit": {+ "post": {+ "description": "Edit a message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Edit a message",+ "parameters": [+ {+ "description": "Edit a message",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/markread": {+ "post": {+ "description": "Mark a message as read",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Mark a message as read",+ "parameters": [+ {+ "description": "Mark a message as read",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/presence": {+ "post": {+ "description": "Set chat presence",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Set chat presence",+ "parameters": [+ {+ "description": "Set chat presence",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/react": {+ "post": {+ "description": "React a message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "React a message",+ "parameters": [+ {+ "description": "React a message",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/message/status": {+ "post": {+ "description": "Get message status",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Message"+ ],+ "summary": "Get message status",+ "parameters": [+ {+ "description": "Get message status",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/create": {+ "post": {+ "description": "Create newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Create newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/info": {+ "post": {+ "description": "Get newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/link": {+ "post": {+ "description": "Get newsletter invite",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter invite",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/list": {+ "get": {+ "description": "List newsletters",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "List newsletters",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/messages": {+ "post": {+ "description": "Get newsletter messages",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Get newsletter messages",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/newsletter/subscribe": {+ "post": {+ "description": "Subscribe newsletter",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Newsletter"+ ],+ "summary": "Subscribe newsletter",+ "parameters": [+ {+ "description": "Newsletter data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/contact": {+ "post": {+ "description": "Send a contact message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a contact message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/link": {+ "post": {+ "description": "Send a link message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a link message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/location": {+ "post": {+ "description": "Send a location message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a location message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/media": {+ "post": {+ "description": "Send a media message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a media message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/poll": {+ "post": {+ "description": "Send a poll message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a poll message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/sticker": {+ "post": {+ "description": "Send a sticker message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a sticker message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/send/text": {+ "post": {+ "description": "Send a text message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Send Message"+ ],+ "summary": "Send a text message",+ "parameters": [+ {+ "description": "Message data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/unlabel/chat": {+ "post": {+ "description": "Remove label from chat",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Remove label from chat",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/unlabel/message": {+ "post": {+ "description": "Remove label from message",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Label"+ ],+ "summary": "Remove label from message",+ "parameters": [+ {+ "description": "Label data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/avatar": {+ "post": {+ "description": "Get a user's avatar",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's avatar",+ "parameters": [+ {+ "description": "Avatar data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/block": {+ "post": {+ "description": "Block a contact",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Block a contact",+ "parameters": [+ {+ "description": "Block data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/blocklist": {+ "get": {+ "description": "Get a user's block list",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's block list",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/check": {+ "post": {+ "description": "Check a user",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Check a user",+ "parameters": [+ {+ "description": "User data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/contacts": {+ "get": {+ "description": "Get a user's contacts",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's contacts",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/info": {+ "post": {+ "description": "Get a user",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user",+ "parameters": [+ {+ "description": "User data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/privacy": {+ "get": {+ "description": "Get a user's privacy settings",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Get a user's privacy settings",+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/profile": {+ "post": {+ "description": "Set a user's profile picture",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Set a user's profile picture",+ "parameters": [+ {+ "description": "Profile picture data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ },+ "/user/unblock": {+ "post": {+ "description": "Unblock a contact",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "User"+ ],+ "summary": "Unblock a contact",+ "parameters": [+ {+ "description": "Block data",+ "name": "message",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "success",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "400": {+ "description": "Error on validation",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ },+ "500": {+ "description": "Internal server error",+ "schema": {+ "$ref": "#/definitions/gin.H"+ }+ }+ }+ }+ }+ },+ "definitions": {+ "gin.H": {+ "type": "object",+ "additionalProperties": {}+ },+ "github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct": {+ "type": "object",+ "properties": {+ "communityJid": {+ "type": "string"+ },+ "groupJid": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct": {+ "type": "object",+ "properties": {+ "communityName": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct": {+ "type": "object",+ "properties": {+ "action": {+ "$ref": "#/definitions/whatsmeow.ParticipantChange"+ },+ "groupJid": {+ "$ref": "#/definitions/types.JID"+ },+ "participants": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct": {+ "type": "object",+ "properties": {+ "groupName": {+ "type": "string"+ },+ "participants": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "reset": {+ "type": "boolean"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct": {+ "type": "object",+ "properties": {+ "groupJid": {+ "type": "string"+ },+ "image": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct": {+ "type": "object",+ "properties": {+ "immediate": {+ "type": "boolean"+ },+ "phone": {+ "type": "string"+ },+ "subscribe": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "webhookUrl": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "proxy": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig"+ },+ "token": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct": {+ "type": "object",+ "properties": {+ "phone": {+ "type": "string"+ },+ "subscribe": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig": {+ "type": "object",+ "properties": {+ "address": {+ "type": "string"+ },+ "password": {+ "type": "string"+ },+ "port": {+ "type": "string"+ },+ "username": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "type": "string"+ },+ "labelId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct": {+ "type": "object",+ "properties": {+ "color": {+ "type": "integer"+ },+ "deleted": {+ "type": "boolean"+ },+ "labelId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "type": "string"+ },+ "labelId": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct": {+ "type": "object",+ "properties": {+ "isAudio": {+ "type": "boolean"+ },+ "number": {+ "type": "string"+ },+ "state": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct": {+ "type": "object",+ "properties": {+ "directPath": {+ "type": "string"+ },+ "fileEncSHA256": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "fileLength": {+ "type": "integer"+ },+ "fileSHA256": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "mediaKey": {+ "type": "array",+ "items": {+ "type": "integer"+ }+ },+ "mimetype": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ },+ "message": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "number": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct": {+ "type": "object",+ "properties": {+ "chat": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "reaction": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct": {+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct": {+ "type": "object",+ "properties": {+ "before_id": {+ "type": "integer"+ },+ "count": {+ "type": "integer"+ },+ "jid": {+ "$ref": "#/definitions/types.JID"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct": {+ "type": "object",+ "properties": {+ "jid": {+ "$ref": "#/definitions/types.JID"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "vcard": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "description": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "imgUrl": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "text": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct": {+ "type": "object",+ "properties": {+ "address": {+ "type": "string"+ },+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "latitude": {+ "type": "number"+ },+ "longitude": {+ "type": "number"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct": {+ "type": "object",+ "properties": {+ "caption": {+ "type": "string"+ },+ "delay": {+ "type": "integer"+ },+ "filename": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "type": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "maxAnswer": {+ "type": "integer"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "options": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "question": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct": {+ "type": "object",+ "properties": {+ "messageId": {+ "type": "string"+ },+ "participant": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "sticker": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct": {+ "type": "object",+ "properties": {+ "delay": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "mentionAll": {+ "type": "boolean"+ },+ "mentionedJid": {+ "type": "string"+ },+ "number": {+ "type": "string"+ },+ "quoted": {+ "$ref": "#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct"+ },+ "text": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct": {+ "type": "object",+ "properties": {+ "number": {+ "type": "string"+ },+ "preview": {+ "type": "boolean"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct": {+ "type": "object",+ "properties": {+ "image": {+ "type": "string"+ }+ }+ },+ "github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct": {+ "type": "object",+ "properties": {+ "fullName": {+ "type": "string"+ },+ "organization": {+ "type": "string"+ },+ "phone": {+ "type": "string"+ }+ }+ },+ "types.JID": {+ "type": "object",+ "properties": {+ "device": {+ "type": "integer"+ },+ "integrator": {+ "type": "integer"+ },+ "rawAgent": {+ "type": "integer"+ },+ "server": {+ "type": "string"+ },+ "user": {+ "type": "string"+ }+ }+ },+ "whatsmeow.ParticipantChange": {+ "type": "string",+ "enum": [+ "add",+ "remove",+ "promote",+ "demote"+ ],+ "x-enum-varnames": [+ "ParticipantChangeAdd",+ "ParticipantChangeRemove",+ "ParticipantChangePromote",+ "ParticipantChangeDemote"+ ]+ }+ }+}\ No newline at end of filediff --git a/docs/swagger.yaml b/docs/swagger.yamlnew file mode 100644index 0000000..ed07f1f--- /dev/null+++ b/docs/swagger.yaml@@ -0,0 +1,2134 @@+definitions:+ gin.H:+ additionalProperties: {}+ type: object+ github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct:+ properties:+ chat:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct:+ properties:+ communityJid:+ type: string+ groupJid:+ items:+ type: string+ type: array+ type: object+ github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct:+ properties:+ communityName:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct:+ properties:+ action:+ $ref: '#/definitions/whatsmeow.ParticipantChange'+ groupJid:+ $ref: '#/definitions/types.JID'+ participants:+ items:+ type: string+ type: array+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct:+ properties:+ groupName:+ type: string+ participants:+ items:+ type: string+ type: array+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct:+ properties:+ groupJid:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct:+ properties:+ groupJid:+ type: string+ reset:+ type: boolean+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct:+ properties:+ code:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct:+ properties:+ groupJid:+ type: string+ name:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct:+ properties:+ groupJid:+ type: string+ image:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct:+ properties:+ immediate:+ type: boolean+ phone:+ type: string+ subscribe:+ items:+ type: string+ type: array+ webhookUrl:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct:+ properties:+ name:+ type: string+ proxy:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig'+ token:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct:+ properties:+ phone:+ type: string+ subscribe:+ items:+ type: string+ type: array+ type: object+ github_com_Zapbox-API_evolution-go_pkg_instance_service.ProxyConfig:+ properties:+ address:+ type: string+ password:+ type: string+ port:+ type: string+ username:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct:+ properties:+ jid:+ type: string+ labelId:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct:+ properties:+ color:+ type: integer+ deleted:+ type: boolean+ labelId:+ type: string+ name:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct:+ properties:+ jid:+ type: string+ labelId:+ type: string+ messageId:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct:+ properties:+ isAudio:+ type: boolean+ number:+ type: string+ state:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct:+ properties:+ directPath:+ type: string+ fileEncSHA256:+ items:+ type: integer+ type: array+ fileLength:+ type: integer+ fileSHA256:+ items:+ type: integer+ type: array+ mediaKey:+ items:+ type: integer+ type: array+ mimetype:+ type: string+ url:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct:+ properties:+ chat:+ type: string+ message:+ type: string+ messageId:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct:+ properties:+ id:+ items:+ type: string+ type: array+ number:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct:+ properties:+ id:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct:+ properties:+ chat:+ type: string+ messageId:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct:+ properties:+ id:+ type: string+ number:+ type: string+ reaction:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct:+ properties:+ description:+ type: string+ name:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct:+ properties:+ key:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct:+ properties:+ before_id:+ type: integer+ count:+ type: integer+ jid:+ $ref: '#/definitions/types.JID'+ type: object+ github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct:+ properties:+ jid:+ $ref: '#/definitions/types.JID'+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct:+ properties:+ delay:+ type: integer+ id:+ type: string+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ vcard:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct'+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct:+ properties:+ delay:+ type: integer+ description:+ type: string+ id:+ type: string+ imgUrl:+ type: string+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ text:+ type: string+ title:+ type: string+ url:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct:+ properties:+ address:+ type: string+ delay:+ type: integer+ id:+ type: string+ latitude:+ type: number+ longitude:+ type: number+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ name:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct:+ properties:+ caption:+ type: string+ delay:+ type: integer+ filename:+ type: string+ id:+ type: string+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ type:+ type: string+ url:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct:+ properties:+ delay:+ type: integer+ id:+ type: string+ maxAnswer:+ type: integer+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ options:+ items:+ type: string+ type: array+ question:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct:+ properties:+ messageId:+ type: string+ participant:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct:+ properties:+ delay:+ type: integer+ id:+ type: string+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ sticker:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct:+ properties:+ delay:+ type: integer+ id:+ type: string+ mentionAll:+ type: boolean+ mentionedJid:+ type: string+ number:+ type: string+ quoted:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.QuotedStruct'+ text:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct:+ properties:+ number:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct:+ properties:+ number:+ items:+ type: string+ type: array+ type: object+ github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct:+ properties:+ number:+ type: string+ preview:+ type: boolean+ type: object+ github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct:+ properties:+ image:+ type: string+ type: object+ github_com_Zapbox-API_evolution-go_pkg_utils.VCardStruct:+ properties:+ fullName:+ type: string+ organization:+ type: string+ phone:+ type: string+ type: object+ types.JID:+ properties:+ device:+ type: integer+ integrator:+ type: integer+ rawAgent:+ type: integer+ server:+ type: string+ user:+ type: string+ type: object+ whatsmeow.ParticipantChange:+ enum:+ - add+ - remove+ - promote+ - demote+ type: string+ x-enum-varnames:+ - ParticipantChangeAdd+ - ParticipantChangeRemove+ - ParticipantChangePromote+ - ParticipantChangeDemote+info:+ contact: {}+ description: Evolution GO - whatsmeow+ title: Evolution GO+ version: "1.0"+paths:+ /chat/archive:+ post:+ consumes:+ - application/json+ description: Archive a chat+ parameters:+ - description: Chat+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Archive a chat+ tags:+ - Chat+ /chat/mute:+ post:+ consumes:+ - application/json+ description: Mute a chat+ parameters:+ - description: Chat+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Mute a chat+ tags:+ - Chat+ /chat/pin:+ post:+ consumes:+ - application/json+ description: Pin a chat+ parameters:+ - description: Chat+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Pin a chat+ tags:+ - Chat+ /chat/unpin:+ post:+ consumes:+ - application/json+ description: Unpin a chat+ parameters:+ - description: Chat+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_chat_service.BodyStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Unpin a chat+ tags:+ - Chat+ /community/add:+ post:+ consumes:+ - application/json+ description: Add participant to community+ parameters:+ - description: Participant data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Add participant to community+ tags:+ - Community+ /community/create:+ post:+ consumes:+ - application/json+ description: Create community+ parameters:+ - description: Community data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.CreateCommunityStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Create community+ tags:+ - Community+ /community/remove:+ post:+ consumes:+ - application/json+ description: Remove participant from community+ parameters:+ - description: Participant data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_community_service.AddParticipantStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Remove participant from community+ tags:+ - Community+ /group/create:+ post:+ consumes:+ - application/json+ description: Create group+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.CreateGroupStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Create group+ tags:+ - Group+ /group/info:+ post:+ consumes:+ - application/json+ description: Get group info+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInfoStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get group info+ tags:+ - Group+ /group/invitelink:+ post:+ consumes:+ - application/json+ description: Get group invite link+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.GetGroupInviteLinkStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get group invite link+ tags:+ - Group+ /group/join:+ post:+ consumes:+ - application/json+ description: Join group link+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.JoinGroupStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Join group link+ tags:+ - Group+ /group/list:+ get:+ consumes:+ - application/json+ description: List groups+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: List groups+ tags:+ - Group+ /group/myall:+ get:+ consumes:+ - application/json+ description: Get my groups+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get my groups+ tags:+ - Group+ /group/name:+ post:+ consumes:+ - application/json+ description: Set group name+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupNameStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Set group name+ tags:+ - Group+ /group/participant:+ post:+ consumes:+ - application/json+ description: Update participant+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.AddParticipantStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Update participant+ tags:+ - Group+ /group/photo:+ post:+ consumes:+ - application/json+ description: Set group photo+ parameters:+ - description: Group data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_group_service.SetGroupPhotoStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Set group photo+ tags:+ - Group+ /instance/all:+ get:+ consumes:+ - application/json+ description: Get all instances+ produces:+ - application/json+ responses:+ "200":+ description: All instances+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get all instances+ tags:+ - Instance+ /instance/connect:+ post:+ consumes:+ - application/json+ description: Connect to instance with the provided data+ parameters:+ - description: Instance data+ in: body+ name: instance+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.ConnectStruct'+ produces:+ - application/json+ responses:+ "200":+ description: Instance connected successfully+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Connect to instance+ tags:+ - Instance+ /instance/create:+ post:+ consumes:+ - application/json+ description: Creates a new instance with the provided data+ parameters:+ - description: Instance data+ in: body+ name: instance+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.CreateStruct'+ produces:+ - application/json+ responses:+ "200":+ description: Instance created successfully+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Create a new instance+ tags:+ - Instance+ /instance/delete/{instanceId}:+ delete:+ consumes:+ - application/json+ description: Delete instance+ parameters:+ - description: Instance Id+ in: path+ name: instanceId+ required: true+ type: string+ produces:+ - application/json+ responses:+ "200":+ description: Instance deleted successfully+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Delete instance+ tags:+ - Instance+ /instance/disconnect:+ post:+ consumes:+ - application/json+ description: Disconnect from instance+ produces:+ - application/json+ responses:+ "200":+ description: Instance disconnected successfully+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Disconnect from instance+ tags:+ - Instance+ /instance/logout:+ delete:+ consumes:+ - application/json+ description: Logout from instance+ produces:+ - application/json+ responses:+ "200":+ description: Instance logged out successfully+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Logout from instance+ tags:+ - Instance+ /instance/pair:+ post:+ consumes:+ - application/json+ description: Request pairing code+ parameters:+ - description: Instance data+ in: body+ name: instance+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_instance_service.PairStruct'+ produces:+ - application/json+ responses:+ "200":+ description: Pairing code+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Request pairing code+ tags:+ - Instance+ /instance/proxy/{instanceId}:+ delete:+ consumes:+ - application/json+ description: Delete proxy+ parameters:+ - description: Instance id+ in: path+ name: instanceId+ required: true+ type: string+ produces:+ - application/json+ responses:+ "200":+ description: Proxy deleted successfully+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Delete proxy+ tags:+ - Instance+ /instance/qr:+ get:+ consumes:+ - application/json+ description: Get instance QR code+ produces:+ - application/json+ responses:+ "200":+ description: Instance QR code+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get instance QR code+ tags:+ - Instance+ /instance/status:+ get:+ consumes:+ - application/json+ description: Get instance status+ produces:+ - application/json+ responses:+ "200":+ description: Instance status+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get instance status+ tags:+ - Instance+ /label/chat:+ post:+ consumes:+ - application/json+ description: Add label to chat+ parameters:+ - description: Label data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Add label to chat+ tags:+ - Label+ /label/edit:+ post:+ consumes:+ - application/json+ description: Edit label+ parameters:+ - description: Label data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.EditLabelStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Edit label+ tags:+ - Label+ /label/message:+ post:+ consumes:+ - application/json+ description: Add label to message+ parameters:+ - description: Label data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Add label to message+ tags:+ - Label+ /message/delete:+ post:+ consumes:+ - application/json+ description: Delete a message for everyone+ parameters:+ - description: Delete a message for everyone+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Delete a message for everyone+ tags:+ - Message+ /message/downloadimage:+ post:+ consumes:+ - application/json+ description: Download an image+ parameters:+ - description: Download an image+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.DownloadImageStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Download an image+ tags:+ - Message+ /message/edit:+ post:+ consumes:+ - application/json+ description: Edit a message+ parameters:+ - description: Edit a message+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.EditMessageStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Edit a message+ tags:+ - Message+ /message/markread:+ post:+ consumes:+ - application/json+ description: Mark a message as read+ parameters:+ - description: Mark a message as read+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MarkReadStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Mark a message as read+ tags:+ - Message+ /message/presence:+ post:+ consumes:+ - application/json+ description: Set chat presence+ parameters:+ - description: Set chat presence+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ChatPresenceStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Set chat presence+ tags:+ - Message+ /message/react:+ post:+ consumes:+ - application/json+ description: React a message+ parameters:+ - description: React a message+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.ReactStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: React a message+ tags:+ - Message+ /message/status:+ post:+ consumes:+ - application/json+ description: Get message status+ parameters:+ - description: Get message status+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_message_service.MessageStatusStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get message status+ tags:+ - Message+ /newsletter/create:+ post:+ consumes:+ - application/json+ description: Create newsletter+ parameters:+ - description: Newsletter data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.CreateNewsletterStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Create newsletter+ tags:+ - Newsletter+ /newsletter/info:+ post:+ consumes:+ - application/json+ description: Get newsletter+ parameters:+ - description: Newsletter data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get newsletter+ tags:+ - Newsletter+ /newsletter/link:+ post:+ consumes:+ - application/json+ description: Get newsletter invite+ parameters:+ - description: Newsletter data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterInviteStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get newsletter invite+ tags:+ - Newsletter+ /newsletter/list:+ get:+ consumes:+ - application/json+ description: List newsletters+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: List newsletters+ tags:+ - Newsletter+ /newsletter/messages:+ post:+ consumes:+ - application/json+ description: Get newsletter messages+ parameters:+ - description: Newsletter data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterMessagesStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get newsletter messages+ tags:+ - Newsletter+ /newsletter/subscribe:+ post:+ consumes:+ - application/json+ description: Subscribe newsletter+ parameters:+ - description: Newsletter data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_newsletter_service.GetNewsletterStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Subscribe newsletter+ tags:+ - Newsletter+ /send/contact:+ post:+ consumes:+ - application/json+ description: Send a contact message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.ContactStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a contact message+ tags:+ - Send Message+ /send/link:+ post:+ consumes:+ - application/json+ description: Send a link message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LinkStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a link message+ tags:+ - Send Message+ /send/location:+ post:+ consumes:+ - application/json+ description: Send a location message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.LocationStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a location message+ tags:+ - Send Message+ /send/media:+ post:+ consumes:+ - application/json+ description: Send a media message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.MediaStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a media message+ tags:+ - Send Message+ /send/poll:+ post:+ consumes:+ - application/json+ description: Send a poll message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.PollStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a poll message+ tags:+ - Send Message+ /send/sticker:+ post:+ consumes:+ - application/json+ description: Send a sticker message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.StickerStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a sticker message+ tags:+ - Send Message+ /send/text:+ post:+ consumes:+ - application/json+ description: Send a text message+ parameters:+ - description: Message data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_sendMessage_service.TextStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Send a text message+ tags:+ - Send Message+ /unlabel/chat:+ post:+ consumes:+ - application/json+ description: Remove label from chat+ parameters:+ - description: Label data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.ChatLabelStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Remove label from chat+ tags:+ - Label+ /unlabel/message:+ post:+ consumes:+ - application/json+ description: Remove label from message+ parameters:+ - description: Label data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_label_service.MessageLabelStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Remove label from message+ tags:+ - Label+ /user/avatar:+ post:+ consumes:+ - application/json+ description: Get a user's avatar+ parameters:+ - description: Avatar data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.GetAvatarStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get a user's avatar+ tags:+ - User+ /user/block:+ post:+ consumes:+ - application/json+ description: Block a contact+ parameters:+ - description: Block data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Block a contact+ tags:+ - User+ /user/blocklist:+ get:+ consumes:+ - application/json+ description: Get a user's block list+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get a user's block list+ tags:+ - User+ /user/check:+ post:+ consumes:+ - application/json+ description: Check a user+ parameters:+ - description: User data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Check a user+ tags:+ - User+ /user/contacts:+ get:+ consumes:+ - application/json+ description: Get a user's contacts+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get a user's contacts+ tags:+ - User+ /user/info:+ post:+ consumes:+ - application/json+ description: Get a user+ parameters:+ - description: User data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.CheckUserStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get a user+ tags:+ - User+ /user/privacy:+ get:+ consumes:+ - application/json+ description: Get a user's privacy settings+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Get a user's privacy settings+ tags:+ - User+ /user/profile:+ post:+ consumes:+ - application/json+ description: Set a user's profile picture+ parameters:+ - description: Profile picture data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.SetProfilePictureStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Set a user's profile picture+ tags:+ - User+ /user/unblock:+ post:+ consumes:+ - application/json+ description: Unblock a contact+ parameters:+ - description: Block data+ in: body+ name: message+ required: true+ schema:+ $ref: '#/definitions/github_com_Zapbox-API_evolution-go_pkg_user_service.BlockStruct'+ produces:+ - application/json+ responses:+ "200":+ description: success+ schema:+ $ref: '#/definitions/gin.H'+ "400":+ description: Error on validation+ schema:+ $ref: '#/definitions/gin.H'+ "500":+ description: Internal server error+ schema:+ $ref: '#/definitions/gin.H'+ summary: Unblock a contact+ tags:+ - User+swagger: "2.0"diff --git a/docs/wiki/README.md b/docs/wiki/README.mdnew file mode 100644index 0000000..6894dd4--- /dev/null+++ b/docs/wiki/README.md@@ -0,0 +1,171 @@+<div align="center">++# 📚 Documentação Evolution GO++**Gateway de API WhatsApp de alta performance desenvolvido em Go**++[]()+[]()+[]()++</div>++---++Bem-vindo à documentação oficial do Evolution GO! Aqui você encontrará guias completos, referências de API e melhores práticas para integrar o WhatsApp às suas aplicações de forma profissional e escalável.++## 🚀 Começo Rápido++**Primeira vez aqui?** Siga este caminho:++1. 📖 [**Introdução**](./fundamentos/introduction.md) - Entenda o que é o Evolution GO+2. 🔧 [**Instalação**](./fundamentos/installation.md) - Configure em 5 minutos+3. ⚡ [**Quickstart**](./fundamentos/quickstart.md) - Envie sua primeira mensagem+4. 📡 [**Visão Geral da API**](./guias-api/api-overview.md) - Conheça os endpoints disponíveis++## 📖 O que você quer fazer?++### Enviar Mensagens+- [Enviar texto, imagens e documentos](./guias-api/api-messages.md)+- [Criar enquetes interativas](./guias-api/api-messages.md#enviar-enquete)+- [Enviar localizações e contatos](./guias-api/api-messages.md#enviar-localização)++### Gerenciar Instâncias+- [Criar e conectar instâncias](./guias-api/api-instances.md)+- [Autenticação via QR Code](./recursos-avancados/qrcode-connection.md)+- [Gerenciar múltiplas contas](./conceitos-core/instances.md)++### Automatizar Workflows+- [Receber eventos via Webhook](./recursos-avancados/events-system.md)+- [Integrar com RabbitMQ/NATS](./recursos-avancados/events-system.md)+- [Armazenar mídias automaticamente](./recursos-avancados/media-storage.md)++### Deploy em Produção+- [Deploy com Docker](./deploy-producao/docker-deployment.md)+- [Segurança e compliance](./deploy-producao/security.md)+- [Escalabilidade](./conceitos-core/architecture.md)++---++## 📚 Documentação Completa++### 🎯 Fundamentos++Documentação essencial para começar a usar o Evolution GO.++| Documento | Descrição |+|-----------|-----------|+| [**Introdução**](./fundamentos/introduction.md) | O que é o Evolution GO, recursos e casos de uso |+| [**Instalação**](./fundamentos/installation.md) | Guia completo de instalação (Docker, Local, Swarm) |+| [**Configuração**](./fundamentos/configuration.md) | Variáveis de ambiente e configurações |+| [**Quickstart**](./fundamentos/quickstart.md) | Tutorial prático: primeira instância em minutos |++### 🏗️ Conceitos Core++Entenda como o Evolution GO funciona por dentro.++| Documento | Descrição |+|-----------|-----------|+| [**Arquitetura**](./conceitos-core/architecture.md) | Arquitetura em camadas, componentes e fluxos |+| [**Instâncias**](./conceitos-core/instances.md) | Como funcionam as instâncias WhatsApp |+| [**Autenticação**](./conceitos-core/authentication.md) | API Keys, tokens e segurança |+| [**Banco de Dados**](./conceitos-core/database.md) | Estrutura dual: evogo_auth + evogo_users |++### 📡 API Reference++Referência completa de todos os endpoints disponíveis.++| API | Endpoints | Descrição |+|-----|-----------|-----------|+| [**Overview**](./guias-api/api-overview.md) | - | Visão geral da API REST |+| [**Instâncias**](./guias-api/api-instances.md) | 16 | Criar, conectar, gerenciar instâncias |+| [**Mensagens**](./guias-api/api-messages.md) | 16 | Enviar texto, mídia, enquetes, stickers |+| [**Usuários**](./guias-api/api-user.md) | 13 | Perfil, contatos, privacidade, bloqueio |+| [**Grupos**](./guias-api/api-groups.md) | 11 | Criar e administrar grupos |+| [**Chats**](./guias-api/api-chats.md) | 7 | Pin, archive, mute, histórico |+| [**Labels**](./guias-api/api-labels.md) | 6 | Etiquetar chats e mensagens |+| [**Chamadas**](./guias-api/api-call.md) | 1 | Rejeitar chamadas recebidas |+| [**Comunidades**](./guias-api/api-community.md) | 3 | Criar e gerenciar comunidades |+| [**Newsletters**](./guias-api/api-newsletter.md) | 6 | Canais do WhatsApp |+| [**Webhooks**](./guias-api/api-webhooks.md) | - | Configurar eventos em tempo real |++### 🚀 Recursos Avançados++Funcionalidades avançadas para casos de uso complexos.++| Documento | Descrição |+|-----------|-----------|+| [**Sistema de Eventos**](./recursos-avancados/events-system.md) | Webhooks, RabbitMQ, NATS, WebSocket |+| [**Armazenamento de Mídia**](./recursos-avancados/media-storage.md) | MinIO/S3, presigned URLs |+| [**Conexão QR Code**](./recursos-avancados/qrcode-connection.md) | Fluxo de autenticação detalhado |+| [**Multi-Device**](./recursos-avancados/multi-device.md) | Protocolo Multi-Device do WhatsApp |++### 🐳 Deploy e Produção++Guias para colocar o Evolution GO em produção.++| Documento | Descrição |+|-----------|-----------|+| [**Deploy com Docker**](./deploy-producao/docker-deployment.md) | Docker Compose, Swarm, Kubernetes |+| [**Segurança**](./deploy-producao/security.md) | SSL/TLS, API Keys, Firewall, Hardening |++### 💻 Desenvolvimento++Para desenvolvedores que querem contribuir ou personalizar.++| Documento | Descrição |+|-----------|-----------|+| [**Guia de Desenvolvimento**](./desenvolvimento/development-guide.md) | Setup do ambiente de desenvolvimento |+| [**Como Contribuir**](./desenvolvimento/contributing.md) | Padrões de código e processo de PR |+| [**Debugging**](./desenvolvimento/debugging.md) | Troubleshooting e profiling |++### 📖 Referência Técnica++Consulta rápida para desenvolvedores.++| Documento | Descrição |+|-----------|-----------|+| [**API Reference**](./referencia/api-reference.md) | Todos os 79 endpoints em uma página |+| [**Environment Variables**](./referencia/environment-variables.md) | Lista completa de variáveis de ambiente |+| [**Error Codes**](./referencia/error-codes.md) | Códigos HTTP e erros da aplicação |+| [**FAQ**](./referencia/faq.md) | Perguntas frequentes e soluções |++---++## 💡 Precisa de Ajuda?++### 📖 Recursos de Aprendizado+- **Novo no Evolution GO?** Comece pelo [Quickstart](./fundamentos/quickstart.md)+- **Dúvidas frequentes?** Confira o [FAQ](./referencia/faq.md)+- **Problemas técnicos?** Veja o guia de [Debugging](./desenvolvimento/debugging.md)++### 🔗 Links Importantes+- 🌐 [Repositório Oficial](https://git.evoai.app/Evolution/evolution-go)+- 📚 [Biblioteca Whatsmeow](https://github.com/tulir/whatsmeow)+- 🔧 [API Swagger](http://localhost:4000/swagger/index.html) (quando servidor estiver rodando)+- 🐛 [Reportar Issues](https://git.evoai.app/Evolution/evolution-go/issues)++### 💬 Suporte+- **Issues técnicos**: Abra uma issue no repositório+- **Dúvidas sobre API**: Consulte a [Referência da API](./referencia/api-reference.md)+- **Erros e códigos**: Veja [Códigos de Erro](./referencia/error-codes.md)++## 🎯 Recursos Principais++- ✅ **79 endpoints** REST documentados+- ✅ **Multi-instância** - Gerencie múltiplas contas WhatsApp+- ✅ **Multi-device** - Suporte WhatsApp Multi-Device nativo+- ✅ **Eventos em tempo real** - Webhooks, RabbitMQ, NATS, WebSocket+- ✅ **Armazenamento de mídia** - MinIO/S3 integrado+- ✅ **Alta performance** - Desenvolvido em Go+- ✅ **Docker ready** - Deploy fácil em produção++---++<div align="center">++**Mantido por EvoAI Services** • **Versão da Documentação: 1.0.0**++[⬆️ Voltar ao topo](#-documentação-evolution-go)++</div>diff --git a/docs/wiki/conceitos-core/architecture.md b/docs/wiki/conceitos-core/architecture.mdnew file mode 100644index 0000000..bc9b765--- /dev/null+++ b/docs/wiki/conceitos-core/architecture.md@@ -0,0 +1,540 @@+# Arquitetura++Como o Evolution GO está organizado por dentro - explicado de forma simples.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Arquitetura em 3 Camadas](#arquitetura-em-3-camadas)+- [Componentes Principais](#componentes-principais)+- [Como Funciona uma Requisição](#como-funciona-uma-requisição)+- [Organização de Pastas](#organização-de-pastas)+- [Tecnologias Usadas](#tecnologias-usadas)++---++## Visão Geral++O Evolution GO é organizado em **3 camadas** separadas. Pense nisso como uma lanchonete:++1. **Atendente** (Handler) - Recebe seu pedido+2. **Cozinha** (Service) - Prepara o pedido+3. **Estoque** (Repository) - Busca os ingredientes++Cada parte tem uma função específica e não faz o trabalho das outras.++### Por que Separar?++**Vantagens**:+- **Organização**: Cada coisa no seu lugar+- **Manutenção**: Fácil de encontrar e corrigir problemas+- **Testes**: Pode testar cada parte separadamente+- **Escalabilidade**: Fácil de crescer e adicionar funcionalidades++---++## Arquitetura em 3 Camadas++### Camada 1: Handler (Atendente)++**O que faz**: Recebe requisições HTTP e responde ao cliente.++**Responsabilidades**:+- Receber dados do cliente (JSON, formulários)+- Validar se os dados estão corretos+- Chamar o Service para fazer o trabalho+- Devolver a resposta (sucesso ou erro)++**Analogia**: Como o atendente de um restaurante+- Recebe seu pedido+- Anota tudo certinho+- Passa para a cozinha+- Traz sua comida quando fica pronta++**Exemplo do mundo real**:+```+Cliente: "Quero enviar uma mensagem para o número 11999999999"+Handler: "Ok, deixa eu passar isso para o Service..."+Service: "Mensagem enviada!"+Handler: "Pronto, sua mensagem foi enviada!"+```++### Camada 2: Service (Cozinha)++**O que faz**: Implementa a lógica de negócio - onde acontece a "mágica".++**Responsabilidades**:+- Aplicar regras de negócio+- Coordenar entre diferentes partes do sistema+- Validar dados complexos+- Gerenciar transações+- Decidir o que fazer++**Analogia**: Como a cozinha do restaurante+- Recebe o pedido do atendente+- Prepara a comida seguindo a receita+- Coordena entre fogão, forno, geladeira+- Entrega o prato pronto++**Exemplo do mundo real**:+```+Service recebe: "Enviar mensagem para 11999999999"++Service faz:+1. Busca a instância do WhatsApp+2. Verifica se está conectada+3. Formata o número corretamente+4. Monta a mensagem+5. Envia via WhatsApp+6. Salva no banco de dados+7. Avisa o webhook (se tiver)+8. Retorna "Sucesso!"+```++### Camada 3: Repository (Estoque)++**O que faz**: Gerencia os dados do banco de dados.++**Responsabilidades**:+- Salvar dados no banco+- Buscar dados do banco+- Atualizar dados existentes+- Deletar dados++**Analogia**: Como o estoque do restaurante+- Guarda os ingredientes+- Entrega quando a cozinha pede+- Recebe novos ingredientes+- Organiza tudo++**Exemplo do mundo real**:+```+Service: "Preciso das informações da instância 'vendas'"+Repository: "Deixa eu buscar no banco... Aqui está!"++Service: "Salva essa mensagem no banco"+Repository: "Ok, salvei!"+```++---++## Componentes Principais++### 1. Whatsmeow Service++**O que é**: O componente que faz a conexão com o WhatsApp.++**Analogia**: É o "telefone" do sistema. Cada instância tem seu próprio "telefone" para falar com o WhatsApp.++**Funções**:+- Conectar ao WhatsApp+- Manter a conexão ativa+- Enviar mensagens+- Receber mensagens+- Gerenciar sessões++### 2. Event Producer++**O que é**: Componente que avisa outros sistemas quando algo acontece.++**Analogia**: Como um carteiro que entrega notificações.++**Tipos de notificação**:+- **Webhook**: Envia para uma URL sua+- **RabbitMQ**: Envia para fila de mensagens+- **WebSocket**: Envia em tempo real+- **NATS**: Envia para sistema de eventos++**Exemplos de eventos**:+- "Nova mensagem recebida!"+- "QR Code gerado!"+- "Cliente desconectou!"++### 3. Storage Service++**O que é**: Componente que guarda arquivos (fotos, vídeos, áudios).++**Opções**:+- **MinIO/S3**: Para produção (servidor na nuvem)+- **Local**: Para desenvolvimento (pasta no computador)++**Analogia**: Como um HD externo onde ficam salvos os arquivos.++### 4. Config Service++**O que é**: Componente que carrega as configurações do sistema.++**O que configura**:+- Porta do servidor+- Conexão com banco de dados+- API Keys+- URLs de webhooks+- Configurações do WhatsApp++**Analogia**: Como as "regras da casa" - tudo que precisa ser configurado fica aqui.++---++## Como Funciona uma Requisição++### Exemplo: Enviar uma Mensagem de Texto++```+1. VOCÊ+ │+ │ POST /send/text+ │ {"number": "11999999999", "text": "Olá!"}+ │+ ▼+2. HANDLER (Atendente)+ │+ │ "Recebeu um pedido, vou validar..."+ │ ✓ JSON está correto+ │ ✓ Campos obrigatórios presentes+ │+ ▼+3. SERVICE (Cozinha)+ │+ │ "Vou preparar o envio da mensagem..."+ │ 1. Buscar cliente WhatsApp+ │ 2. Verificar se está conectado+ │ 3. Formatar número (11999999999 → [email protected])+ │ 4. Montar mensagem+ │+ ▼+4. WHATSAPP+ │+ │ "Enviando mensagem..."+ │ ✓ Mensagem enviada+ │ Retorna ID: msg_123456+ │+ ▼+5. SERVICE (continuação)+ │+ │ "Mensagem enviada! Agora vou registrar..."+ │ → Salvar no banco via REPOSITORY+ │ → Avisar webhook via EVENT PRODUCER+ │+ ▼+6. HANDLER (continuação)+ │+ │ "Tudo certo! Vou responder o cliente..."+ │+ ▼+7. VOCÊ+ │+ │ Recebe resposta:+ │ {"status": "success", "messageId": "msg_123456"}+```++### Tempo Total++Tudo isso acontece em menos de 1 segundo! ⚡++---++## Organização de Pastas++### Estrutura Simplificada++```+evolution-go/+│+├── cmd/+│ └── evolution-go/+│ └── main.go ← Arquivo principal (inicia tudo)+│+├── pkg/ ← Código principal+│ │+│ ├── instance/ ← Gerenciar instâncias+│ │ ├── handler/ ← Recebe requisições HTTP+│ │ ├── service/ ← Lógica de negócio+│ │ ├── repository/ ← Acesso ao banco+│ │ └── model/ ← Estrutura de dados+│ │+│ ├── message/ ← Gerenciar mensagens+│ │ ├── handler/+│ │ ├── service/+│ │ ├── repository/+│ │ └── model/+│ │+│ ├── group/ ← Gerenciar grupos+│ ├── user/ ← Gerenciar usuários+│ ├── chat/ ← Gerenciar chats+│ │+│ ├── whatsmeow/ ← Conexão WhatsApp+│ ├── events/ ← Sistema de eventos+│ ├── storage/ ← Armazenar arquivos+│ └── config/ ← Configurações+│+├── docs/ ← Documentação+├── logs/ ← Arquivos de log+└── .env ← Configurações (senhas, chaves)+```++### Padrão de Organização++Cada funcionalidade tem a mesma estrutura:++```+funcionalidade/+├── handler/ ← Recebe requisições+├── service/ ← Processa lógica+├── repository/ ← Acessa banco+└── model/ ← Define estruturas+```++**Exemplo**: Para enviar mensagens, você tem:+- `message/handler/` - Recebe a requisição+- `message/service/` - Prepara e envia+- `message/repository/` - Salva no banco+- `message/model/` - Define como é uma mensagem++---++## Tecnologias Usadas++### Framework Web++**Gin** - Framework HTTP para Go+- Rápido e leve+- Fácil de usar+- Gerencia rotas e middlewares++**O que faz**: Recebe requisições HTTP e encaminha para os handlers.++### Cliente WhatsApp++**Whatsmeow** - Biblioteca oficial+- Implementa protocolo do WhatsApp Web+- Multi-dispositivo+- Criptografia ponta-a-ponta++**O que faz**: Conversa com os servidores do WhatsApp.++### Banco de Dados++**GORM** - ORM (Mapeador Objeto-Relacional)+- Facilita trabalhar com banco de dados+- Suporta PostgreSQL e SQLite+- Migrations automáticas++**O que faz**: Converte dados entre o código e o banco de dados.++### Filas de Mensagem++**RabbitMQ** - Sistema de filas+**NATS** - Sistema de eventos+- Entregam notificações de forma confiável+- Processamento assíncrono++**O que fazem**: Avisam outros sistemas quando algo acontece.++### Armazenamento de Arquivos++**MinIO** - Storage compatível com S3+- Armazena fotos, vídeos, áudios+- Escalável++**O que faz**: Guarda arquivos de mídia enviados/recebidos.++### Utilitários++**QRCode** - Gera QR Codes+**UUID** - Gera IDs únicos+**WebSocket** - Comunicação em tempo real+**Zap Logger** - Logs estruturados++---++## Ciclo de Vida de uma Instância++### Estados++```+1. CRIADA+ ↓+ (usuário cria via API)+ ↓+2. DESCONECTADA+ ↓+ (usuário conecta)+ ↓+3. CONECTANDO+ ↓+ (gera QR Code)+ ↓+4. AGUARDANDO SCAN+ ↓+ (usuário escaneia QR no celular)+ ↓+5. ABERTA/CONECTADA+ ↓+ (pode enviar/receber mensagens)+ ↓+ (se desconectar)+ ↓+6. DESCONECTADA+ ↓+ (pode reconectar sem QR)+ ↓+5. ABERTA/CONECTADA+```++### Ações Possíveis++| Estado | O que Pode Fazer |+|--------|------------------|+| **Criada** | Conectar, Deletar |+| **Desconectada** | Conectar, Reconectar, Deletar |+| **Conectando** | Aguardar, Cancelar |+| **Aguardando QR** | Escanear QR, Timeout |+| **Aberta** | Enviar mensagens, Desconectar, Logout |++---++## Segurança++### 1. Autenticação++Todas as requisições precisam de API Key:+- Administrador: API Key Global+- Instância: Token específico++### 2. Isolamento++Cada instância é completamente isolada:+- Não pode acessar dados de outras instâncias+- Tem seu próprio cliente WhatsApp+- Sessão separada no banco++### 3. Validação++Todos os dados são validados antes de processar:+- Formato de número de telefone+- Tamanho de mensagens+- Tipos de arquivo permitidos++### 4. Criptografia++WhatsApp usa criptografia ponta-a-ponta:+- Mensagens criptografadas automaticamente+- Chaves guardadas de forma segura+- Ninguém pode interceptar++---++## Escalabilidade++### Horizontal (Mais Servidores)++Pode ter múltiplas cópias do Evolution GO:++```+ ┌─────────────────┐+ │ Load Balancer │+ └────────┬─────────┘+ │+ ┌───────────┼───────────┐+ │ │ │+ ┌────▼───┐ ┌───▼────┐ ┌───▼────┐+ │Server 1│ │Server 2│ │Server 3│+ └────┬───┘ └───┬────┘ └───┬────┘+ │ │ │+ └──────────┼───────────┘+ │+ ┌──────▼──────┐+ │ PostgreSQL │+ └─────────────┘+```++**Vantagens**:+- Suporta mais usuários+- Se um servidor cair, outros continuam+- Distribuição de carga++### Vertical (Servidor Mais Potente)++Melhorar o servidor existente:+- Mais CPU+- Mais RAM+- Mais espaço em disco++**Quando usar**:+- Até ~100 instâncias: Vertical+- Mais de 100: Horizontal++---++## Resumo Visual++### Fluxo Completo++```+ REQUISIÇÃO+ ↓+ ┌────────┐+ │Handler │ ← Valida dados+ └───┬────┘+ ↓+ ┌────────┐+ │Service │ ← Aplica lógica+ └───┬────┘+ ↓+ ┌────────────┐+ │Repository │ ← Salva/busca dados+ └───┬────────┘+ ↓+ ┌────────┐+ │Database│+ └────────┘+```++### Componentes Interconectados++```+┌──────────────────────────────────┐+│ Evolution GO Server │+├──────────────────────────────────┤+│ │+│ ┌────────┐ ┌───────────┐ │+│ │Handler │─────>│ Service │ │+│ └────────┘ └─────┬─────┘ │+│ │ │+│ ┌──────────────┼────────┐│+│ │ │ ││+│ ┌────▼───┐ ┌────▼────┐ ││+│ │Whatsapp│ │Repository ││+│ │Service │ └────┬────┘ ││+│ └────┬───┘ │ ││+└─────────┼─────────────┼────────┘│+ │ │+ ┌───▼────┐ ┌───▼───┐+ │WhatsApp│ │ DB │+ │Servers │ │ │+ └────────┘ └───────┘+```++---++## Resumo Rápido++| Conceito | Explicação Simples |+|----------|-------------------|+| **Handler** | Atendente - recebe pedidos |+| **Service** | Cozinha - prepara tudo |+| **Repository** | Estoque - guarda dados |+| **Whatsmeow** | Telefone - fala com WhatsApp |+| **Events** | Carteiro - avisa outros sistemas |+| **Storage** | HD - guarda arquivos |++**Lembre-se**:+- 📱 Cada camada tem uma função específica+- 🔄 Requisição passa por todas as camadas+- 🏗️ Organização facilita manutenção+- 🚀 Pode escalar horizontal ou verticalmente+- 🔒 Segurança em todas as camadas++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/conceitos-core/authentication.md b/docs/wiki/conceitos-core/authentication.mdnew file mode 100644index 0000000..86464c6--- /dev/null+++ b/docs/wiki/conceitos-core/authentication.md@@ -0,0 +1,452 @@+# Autenticação++Sistema de autenticação do Evolution GO usando chaves de acesso (API Keys).++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Dois Tipos de Chave](#dois-tipos-de-chave)+- [API Key Global](#api-key-global)+- [Token de Instância](#token-de-instância)+- [Como Usar](#como-usar)+- [Fluxos de Autenticação](#fluxos-de-autenticação)+- [Segurança](#segurança)++---++## Visão Geral++O Evolution GO usa **chaves de acesso** (API Keys) para proteger sua API. Pense nisso como senhas especiais que você precisa enviar em cada requisição.++### Como Funciona++Imagine um prédio com dois tipos de chave:+- **Chave Master (Admin)**: Abre todas as portas, permite criar/deletar salas+- **Chave Individual (Instância)**: Abre apenas uma sala específica++É assim que funciona a autenticação no Evolution GO!++**Importante**: Não usamos login/senha tradicional, JWT ou cookies. Apenas chaves simples!++---++## Dois Tipos de Chave++### 1. API Key Global (Admin)++**O que é**: A chave mestre do sistema. Quem tem essa chave controla tudo.++**Para que serve**:+- Criar novas instâncias do WhatsApp+- Deletar instâncias existentes+- Ver todas as instâncias do sistema+- Gerenciar configurações globais++**Como usar**:+```+Envie no header da requisição:+apikey: sua-chave-global-aqui+```++**Exemplo prático**:+```bash+# Criar uma instância nova+POST /instance/create+Header: apikey: minha-chave-master-123+```++### 2. Token de Instância++**O que é**: A chave individual de cada WhatsApp conectado.++**Para que serve**:+- Enviar mensagens+- Criar grupos+- Gerenciar contatos+- Todas as operações do WhatsApp dessa instância++**Como usar**:+```+Envie no header da requisição:+apikey: token-da-sua-instancia+```++**Exemplo prático**:+```bash+# Enviar uma mensagem+POST /send/text+Header: apikey: token-vendas-123+```++---++## API Key Global++### Configurando++A API Key Global é definida como uma variável de ambiente:++```env+GLOBAL_API_KEY=minha-chave-super-secreta+```++### Gerando uma Chave Segura++**Recomendado** (Linux/Mac):+```bash+# Gera uma chave aleatória forte+openssl rand -base64 32+```++Resultado exemplo:+```+dGhpc2lzYXNlY3VyZWtleXRoYXRpc3Zlcnlsb25nYW5kc2VjdXJl+```++**Não use chaves óbvias**:+- ❌ `123456`+- ❌ `admin`+- ❌ `minha-senha`++### Onde é Usado++**Endpoints que precisam da API Key Global**:+- Criar instância: `POST /instance/create`+- Deletar instância: `DELETE /instance/delete/:id`+- Listar todas: `GET /instance/all`+- Ver informações: `GET /instance/info/:id`+- Configurar proxy: `POST /instance/proxy/:id`+- Ver logs: `GET /instance/logs/:id`++---++## Token de Instância++### O que é++Cada instância do WhatsApp tem seu próprio token único. É como o CPF da instância - identifica ela no sistema.++### Como Obter++**Opção 1: Sistema gera automaticamente**+```json+POST /instance/create+{+ "name": "vendas"+}++Resposta:+{+ "id": "abc-123",+ "name": "vendas",+ "token": "token-gerado-automaticamente-xyz789"+}+```++**Opção 2: Você define o token**+```json+POST /instance/create+{+ "name": "vendas",+ "token": "meu-token-customizado-vendas"+}+```++⚠️ **Atenção**: O token deve ser único no sistema!++### Onde é Usado++**Endpoints que precisam do Token de Instância**:++**Mensagens**:+- Enviar texto: `POST /send/text`+- Enviar mídia: `POST /send/media`+- Enviar áudio: `POST /send/audio`+- Reagir: `POST /message/react`+- Marcar como lida: `POST /message/markread`++**Grupos**:+- Listar grupos: `GET /group/list`+- Criar grupo: `POST /group/create`+- Adicionar participante: `POST /group/participant`+- Sair do grupo: `POST /group/leave`++**Usuários**:+- Ver informações: `POST /user/info`+- Bloquear: `POST /user/block`+- Desbloquear: `POST /user/unblock`+- Ver contatos: `GET /user/contacts`++---++## Como Usar++### Formato do Header HTTP++Todas as requisições devem incluir o header `apikey`:++```+apikey: sua-chave-aqui+```++**NÃO use**:+```+❌ Authorization: Bearer sua-chave+❌ apikey: Bearer sua-chave+```++### Exemplos Práticos++**1. Criando uma instância (usa API Key Global)**:+```bash+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: minha-chave-global" \+ -d '{"name": "vendas", "token": "token-vendas"}'+```++**2. Enviando mensagem (usa Token da Instância)**:+```bash+curl -X POST http://localhost:4000/send/text \+ -H "Content-Type: application/json" \+ -H "apikey: token-vendas" \+ -d '{+ "number": "5511999999999",+ "text": "Olá!"+ }'+```++**3. Com JavaScript**:+```javascript+fetch('http://localhost:4000/send/text', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'apikey': 'token-vendas'+ },+ body: JSON.stringify({+ number: '5511999999999',+ text: 'Olá!'+ })+});+```++---++## Fluxos de Autenticação++### Fluxo 1: Criar Instância++```+1. Você ─────> API+ POST /instance/create+ apikey: CHAVE-GLOBAL++2. API verifica ─────> ✓ Chave Global OK++3. API cria instância ─────> Banco de Dados++4. API retorna ─────> Você+ {+ "name": "vendas",+ "token": "token-vendas-123"+ }+```++### Fluxo 2: Enviar Mensagem++```+1. Você ─────> API+ POST /send/text+ apikey: token-vendas-123++2. API busca ─────> Banco de Dados+ "Qual instância tem esse token?"++3. Banco responde ─────> API+ "É a instância 'vendas'"++4. API envia mensagem ─────> WhatsApp++5. API retorna ─────> Você+ {"status": "success"}+```++### Fluxo 3: Chave Inválida++```+1. Você ─────> API+ POST /send/text+ apikey: token-errado++2. API busca ─────> Banco de Dados+ "Qual instância tem esse token?"++3. Banco responde ─────> API+ "Token não encontrado!"++4. API retorna ERRO ─────> Você+ 401 Unauthorized+ {"error": "not authorized"}+```++---++## Segurança++### 1. Protegendo a API Key Global++**❌ NUNCA faça isso**:+- Compartilhar no Slack, email ou WhatsApp+- Salvar em arquivos públicos no GitHub+- Usar valores óbvios como "admin" ou "123456"+- Colocar no código-fonte++**✅ SEMPRE faça isso**:+- Salvar em arquivo `.env` (e adicionar ao `.gitignore`)+- Usar gerenciadores de secrets (Vault, AWS Secrets)+- Gerar chaves fortes (32+ caracteres aleatórios)+- Rotacionar periodicamente (trocar a chave)++### 2. Protegendo Tokens de Instância++**❌ NUNCA faça isso**:+- Colocar tokens na URL (`?token=...`)+- Salvar tokens em logs+- Expor tokens em páginas públicas++**✅ SEMPRE faça isso**:+- Enviar apenas via header HTTP+- Usar HTTPS em produção+- Guardar em local seguro (variáveis de ambiente)++### 3. Use HTTPS em Produção++⚠️ **CRÍTICO**: Em produção, sempre use HTTPS!++```+✅ https://api.suaempresa.com/send/text+❌ http://api.suaempresa.com/send/text+```++Sem HTTPS, suas chaves trafegam em **texto puro** pela internet e podem ser interceptadas.++### 4. Rotação de Chaves++Se uma chave foi comprometida:++**Para API Key Global**:+1. Gere uma nova chave forte+2. Atualize a variável `GLOBAL_API_KEY` no servidor+3. Reinicie a aplicação+4. Atualize todos os clientes que usam a API++**Para Token de Instância**:+1. Crie uma nova instância com novo token+2. Migre seus dados+3. Delete a instância antiga++💡 Não há como "trocar" um token existente - você precisa criar uma nova instância.++### 5. Monitorando Acessos++**Sinais de problema**:+- Muitas tentativas com chaves inválidas+- Acessos de IPs desconhecidos+- Horários estranhos de acesso++**Recomendação**: Configure logs e alertas para tentativas de acesso não autorizado.++---++## Exemplos do Dia a Dia++### Cenário 1: Primeiro Uso++```bash+# 1. Configure a chave global no servidor+echo "GLOBAL_API_KEY=$(openssl rand -base64 32)" >> .env++# 2. Inicie o servidor+docker-compose up -d++# 3. Crie sua primeira instância+curl -X POST http://localhost:4000/instance/create \+ -H "apikey: $(grep GLOBAL_API_KEY .env | cut -d '=' -f2)" \+ -H "Content-Type: application/json" \+ -d '{"name": "vendas"}'++# Guarde o token que foi retornado!+```++### Cenário 2: Múltiplas Instâncias++```bash+# Vendas+curl -X POST http://localhost:4000/send/text \+ -H "apikey: token-vendas" \+ -d '{"number": "5511111111", "text": "Equipe vendas"}'++# Suporte+curl -X POST http://localhost:4000/send/text \+ -H "apikey: token-suporte" \+ -d '{"number": "5522222222", "text": "Equipe suporte"}'+```++Cada instância é independente e usa seu próprio token!++---++## Troubleshooting++### Erro: "not authorized"++**Possíveis causas**:+1. Header `apikey` está faltando+2. Valor da chave está errado+3. Usando chave global onde precisa token de instância (ou vice-versa)++**Como resolver**:+```bash+# Verifique se o header está sendo enviado+curl -v http://localhost:4000/send/text++# Confirme o valor no .env+cat .env | grep GLOBAL_API_KEY++# Liste suas instâncias para ver os tokens+curl -H "apikey: sua-chave-global" http://localhost:4000/instance/all+```++### Token não funciona após reiniciar++**Causa**: Tokens ficam salvos no banco e não mudam.++**Solução**: Use o mesmo token que foi fornecido na criação da instância.++### Esqueci minha API Key Global++**Solução**:+1. Acesse o servidor+2. Veja o arquivo `.env`+3. Procure por `GLOBAL_API_KEY`++---++## Resumo Rápido++| Tipo | Quando Usar | Exemplo |+|------|-------------|---------|+| **API Key Global** | Criar/deletar instâncias | `apikey: minha-chave-master` |+| **Token Instância** | Enviar mensagens, criar grupos | `apikey: token-vendas-123` |++**Lembre-se**:+- 🔑 API Key Global = Chave mestre (admin)+- 🎫 Token Instância = Chave de uma sala específica+- 🔒 Sempre use HTTPS em produção+- 📝 Guarde suas chaves em local seguro+- 🚫 Nunca compartilhe chaves publicamente++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/conceitos-core/database.md b/docs/wiki/conceitos-core/database.mdnew file mode 100644index 0000000..ae55aab--- /dev/null+++ b/docs/wiki/conceitos-core/database.md@@ -0,0 +1,425 @@+# Banco de Dados++Sistema de armazenamento de dados do Evolution GO usando bancos separados para diferentes finalidades.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Por que Dois Bancos](#por-que-dois-bancos)+- [Banco Auth](#banco-auth)+- [Banco Users](#banco-users)+- [Tabelas Principais](#tabelas-principais)+- [Como os Dados se Relacionam](#como-os-dados-se-relacionam)+- [Boas Práticas](#boas-práticas)++---++## Visão Geral++O Evolution GO usa **dois bancos de dados separados**. Pense nisso como ter dois armários diferentes:++1. **Banco Auth** (`evogo_auth`): Guarda os dados técnicos do WhatsApp+2. **Banco Users** (`evogo_users`): Guarda os dados da sua aplicação++### Tipos de Banco Suportados++- **PostgreSQL**: Recomendado para produção (servidores reais)+- **SQLite**: Usado para desenvolvimento e testes (arquivo local)++---++## Por que Dois Bancos++### Analogia do Armário++Imagine que você tem uma loja:+- **Armário 1** (Auth): Guarda as chaves, segredos e equipamentos técnicos+- **Armário 2** (Users): Guarda produtos, clientes e vendas++É mais organizado e seguro manter separado!++### Vantagens++1. **Organização**: Dados do WhatsApp separados dos dados da sua API+2. **Segurança**: Backup independente para cada tipo de dado+3. **Performance**: Cada banco pode ser otimizado para seu uso+4. **Escalabilidade**: Pode colocar cada banco em um servidor diferente++---++## Banco Auth++### O que Guarda++Todos os dados técnicos do WhatsApp (biblioteca whatsmeow):++- **Chaves de criptografia** - Para proteger suas mensagens+- **Informações do dispositivo** - Identificação do seu WhatsApp+- **Sessões ativas** - Conexões abertas+- **Contatos sincronizados** - Lista de contatos++### Tabelas Importantes++O WhatsApp cria automaticamente várias tabelas:++1. **whatsmeow_device** - Seu "telefone virtual"+2. **whatsmeow_identity_keys** - Chaves de segurança+3. **whatsmeow_sessions** - Sessões de conversa+4. **whatsmeow_contacts** - Lista de contatos+5. ... e outras 6-7 tabelas técnicas++⚠️ **IMPORTANTE**: Não mexa nessas tabelas manualmente! O WhatsApp gerencia tudo automaticamente.++### Por que é Crítico++Este banco contém as **chaves de criptografia**. Sem backup dele:+- ✅ Com backup: Reconecta automaticamente após reiniciar+- ❌ Sem backup: Precisa escanear QR Code novamente++---++## Banco Users++### O que Guarda++Todos os dados da **sua aplicação**:++- **Instâncias** - Cada WhatsApp conectado+- **Mensagens** - Histórico de mensagens enviadas+- **Labels** - Etiquetas/marcações+- **Configurações** - Webhooks, eventos, etc.++### Tabelas Principais++#### 1. Tabela `instances`++**O que é**: A tabela mais importante! Cada linha é um WhatsApp conectado.++**Informações guardadas**:+- **id**: Identificador único (tipo CPF)+- **name**: Nome amigável (ex: "vendas", "suporte")+- **token**: Chave de acesso da instância+- **webhook**: URL para receber eventos+- **jid**: Número do WhatsApp (ex: [email protected])+- **connected**: Está conectado? (true/false)+- **qrcode**: QR Code para conectar+- **events**: Quais eventos quer receber++**Configurações Avançadas**:+- **always_online**: Aparecer sempre online+- **reject_call**: Rejeitar chamadas automaticamente+- **read_messages**: Marcar mensagens como lidas+- **ignore_groups**: Ignorar mensagens de grupo+- **ignore_status**: Ignorar status/stories++#### 2. Tabela `messages`++**O que é**: Histórico de mensagens (opcional, pode ser desabilitado).++**Informações guardadas**:+- **id**: Identificador único+- **message_id**: ID da mensagem no WhatsApp+- **timestamp**: Quando foi enviada+- **status**: Status (enviada, entregue, lida)+- **source**: De qual instância veio++💡 **Dica**: Por padrão, não salvamos o conteúdo completo das mensagens por questão de espaço.++#### 3. Tabela `labels`++**O que é**: Etiquetas/marcações do WhatsApp.++**Informações guardadas**:+- **id**: Identificador único+- **instance_id**: De qual instância+- **label_name**: Nome da etiqueta (ex: "Cliente VIP")+- **label_color**: Cor da etiqueta (0-19)++---++## Tabelas Principais++### Estrutura Visual++```+┌──────────────┐+│ instances │ (Tabela Principal)+│ │+│ - id │◄─────────┐+│ - name │ │+│ - token │ │ Relacionamento+│ - connected │ │+└──────────────┘ │+ │+ ┌──────────────┴──────────────┐+ │ │+ ┌──────▼──────┐ ┌───────▼──────┐+ │ messages │ │ labels │+ │ │ │ │+ │ - id │ │ - id │+ │ - source ───┼─────┐ │ - instance_id│───┐+ │ (FK) │ │ │ (FK) │ │+ └─────────────┘ │ └──────────────┘ │+ │ │+ └────── Aponta para ────────┘+ instances.id+```++**FK = Foreign Key (Chave Estrangeira)**+- Significa que aponta para outra tabela+- Como um "link" entre tabelas++### Quando Deleta uma Instância++Se você deletar uma instância, automaticamente deleta:+- ✅ Todas as mensagens dessa instância+- ✅ Todas as labels dessa instância++Isso se chama **deleção em cascata** - como um efeito dominó!++---++## Como os Dados se Relacionam++### Exemplo Prático++Imagine que você tem:++**1 Instância**:+```+ID: abc-123+Nome: vendas+Token: token-vendas-123+```++**3 Mensagens desta instância**:+```+Mensagem 1: source = abc-123+Mensagem 2: source = abc-123+Mensagem 3: source = abc-123+```++**2 Labels desta instância**:+```+Label 1: instance_id = abc-123+Label 2: instance_id = abc-123+```++Se você deletar a instância `abc-123`:+- ❌ Instância deletada+- ❌ 3 mensagens deletadas automaticamente+- ❌ 2 labels deletadas automaticamente++---++## Configuração++### Variáveis de Ambiente++```env+# Banco Auth (Dados do WhatsApp)+POSTGRES_AUTH_DB=postgresql://user:pass@localhost:5432/evogo_auth++# Banco Users (Dados da API)+POSTGRES_USERS_DB=postgresql://user:pass@localhost:5432/evogo_users+```++### Criação Automática de Tabelas++Quando você inicia o Evolution GO pela primeira vez:++1. Sistema verifica se as tabelas existem+2. Se não existir, cria automaticamente+3. Se existir, apenas conecta+4. **Nunca remove ou altera tabelas existentes** (seguro!)++Isso se chama **Auto-Migration** (migração automática).++---++## Boas Práticas++### 1. Faça Backup Regular++**Recomendado**: Backup diário automático++```bash+# Backup do banco Auth (CRÍTICO!)+pg_dump -U postgres evogo_auth > backup_auth_$(date +%Y%m%d).sql++# Backup do banco Users+pg_dump -U postgres evogo_users > backup_users_$(date +%Y%m%d).sql+```++💡 O backup do **Auth** é mais crítico pois contém as chaves de criptografia!++### 2. Monitorar Espaço++Tabelas crescem com o tempo:++| Tabela | Crescimento |+|--------|-------------|+| **messages** | Rápido (se salvar mensagens) |+| **instances** | Lento |+| **labels** | Lento |+| **whatsmeow_***| Médio |++**Recomendação**: Limpar mensagens antigas regularmente.++### 3. Connection Pooling++**O que é**: Reutilizar conexões ao banco ao invés de abrir/fechar toda hora.++**Configurações recomendadas**:++**Desenvolvimento** (computador local):+- Máximo 20 conexões simultâneas+- 5 conexões em stand-by++**Produção** (servidor):+- Máximo 100 conexões simultâneas+- 25 conexões em stand-by++### 4. Índices para Performance++**O que são índices**: Como um índice de livro - ajuda a encontrar coisas mais rápido!++**Índices importantes já criados**:+- `instances.name` - Buscar por nome+- `instances.token` - Buscar por token+- `messages.source` - Buscar mensagens de uma instância+- `labels.instance_id` - Buscar labels de uma instância++### 5. Limpeza de Dados++**Recomendações**:++```bash+# Deletar mensagens com mais de 90 dias+DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '90 days';++# Deletar instâncias desconectadas há mais de 30 dias+DELETE FROM instances+WHERE connected = false+AND updated_at < NOW() - INTERVAL '30 days';+```++---++## Troubleshooting++### Erro: "too many connections"++**Problema**: Muitas conexões abertas ao banco.++**Soluções**:+1. Verifique quantas conexões o PostgreSQL permite+2. Reduza o número de conexões máximas no Evolution GO+3. Aumente o limite no PostgreSQL++```bash+# Ver limite atual+psql -c "SHOW max_connections;"++# Aumentar para 200 (editar postgresql.conf)+max_connections = 200+```++### Erro: "table does not exist"++**Problema**: Tabela não foi criada.++**Solução**: Reinicie a aplicação. Ela cria as tabelas automaticamente.++### Banco crescendo muito++**Problema**: Banco de dados está ocupando muito espaço.++**Diagnóstico**:+```sql+-- Ver tamanho de cada tabela+SELECT+ tablename,+ pg_size_pretty(pg_total_relation_size(tablename::text)) as size+FROM pg_tables+WHERE schemaname = 'public'+ORDER BY pg_total_relation_size(tablename::text) DESC;+```++**Solução**: Limpe mensagens antigas ou desabilite o salvamento de mensagens.++### Queries lentas++**Problema**: Operações demorando muito.++**Solução**: Provavelmente falta um índice. Consulte um DBA (administrador de banco de dados).++---++## Resumo Visual++### Separação de Responsabilidades++```+┌────────────────────────┐ ┌────────────────────────┐+│ Banco Auth │ │ Banco Users │+│ (evogo_auth) │ │ (evogo_users) │+├────────────────────────┤ ├────────────────────────┤+│ │ │ │+│ WhatsApp │ │ Sua Aplicação │+│ Dados Técnicos │ │ Dados de Negócio │+│ │ │ │+│ • Chaves cripto │ │ • Instâncias │+│ • Sessões │ │ • Mensagens │+│ • Device info │ │ • Labels │+│ • Contatos │ │ • Webhooks │+│ │ │ • Configurações │+└────────────────────────┘ └────────────────────────┘+ ▲ ▲+ │ │+ └───────── Gerenciado por ──────────┘+ Evolution GO+```++### Fluxo de Dados++```+1. Usuário cria instância+ ↓+2. Salvo em: users → instances++3. Usuário conecta WhatsApp+ ↓+4. WhatsApp salva sessão em: auth → whatsmeow_device++5. Mensagem enviada+ ↓+6. Salvo em: users → messages++7. Label criada+ ↓+8. Salvo em: users → labels+```++---++## Resumo Rápido++| Conceito | Explicação |+|----------|------------|+| **2 Bancos** | Auth (WhatsApp) + Users (API) |+| **Auto-Migration** | Cria tabelas automaticamente |+| **Cascata** | Deletar instância → deleta tudo relacionado |+| **Backup** | Crítico para Auth (chaves cripto) |+| **Índices** | Fazem buscas ficarem rápidas |++**Lembre-se**:+- 🔐 Banco Auth = Dados do WhatsApp (crítico!)+- 📊 Banco Users = Dados da sua aplicação+- 💾 Faça backup regular+- 🧹 Limpe dados antigos+- 📈 Monitore crescimento++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/conceitos-core/instances.md b/docs/wiki/conceitos-core/instances.mdnew file mode 100644index 0000000..3951f2c--- /dev/null+++ b/docs/wiki/conceitos-core/instances.md@@ -0,0 +1,790 @@+# Instâncias WhatsApp++Como funcionam as conexões do WhatsApp no Evolution GO - explicado de forma simples.++## 📋 Índice++- [O que é uma Instância](#o-que-é-uma-instância)+- [Informações de uma Instância](#informações-de-uma-instância)+- [Estados da Instância](#estados-da-instância)+- [Ciclo de Vida](#ciclo-de-vida)+- [Configurações Avançadas](#configurações-avançadas)+- [Sistema de Eventos](#sistema-de-eventos)+- [Proxy](#proxy)+- [Boas Práticas](#boas-práticas)++---++## O que é uma Instância++Uma **instância** é uma conexão independente com o WhatsApp. Pense assim:++### Analogia do Celular++Imagine que cada instância é como um celular separado:+- 📱 Celular 1 = Instância "vendas"+- 📱 Celular 2 = Instância "suporte"+- 📱 Celular 3 = Instância "marketing"++Cada um:+- Tem seu próprio número do WhatsApp+- Envia e recebe mensagens independentemente+- Não interfere nos outros+- Tem suas próprias configurações++### Características++**Isolamento**: Cada instância é completamente separada+- Não compartilham mensagens+- Não compartilham contatos+- Não compartilham configurações++**Persistência**: A conexão fica salva+- Se o servidor reiniciar, reconecta automaticamente+- Não precisa escanear QR Code novamente+- Sessão guardada com segurança++**Multi-Device**: Usa o protocolo do WhatsApp Web+- Funciona como WhatsApp no computador+- Não desconecta o celular+- Até 4 dispositivos por número++---++## Informações de uma Instância++### Dados Básicos++Toda instância tem essas informações:++**id** - Identificador único (como um CPF)+```+Exemplo: abc-123-def-456+```++**name** - Nome amigável+```+Exemplo: "vendas", "suporte", "atendimento-24h"+Deve ser único no sistema+```++**token** - Chave de acesso+```+Exemplo: "token-vendas-secreto-123"+Usado para autenticar requisições+Deve ser único no sistema+```++**jid** - ID do WhatsApp (seu número)+```+Formato: [email protected]+Só aparece depois de conectar+```++**connected** - Está conectado?+```+true = Conectado e funcionando+false = Desconectado+```++**qrcode** - QR Code para conectar+```+Formato: imagem_base64|codigo_texto+Expira em ~40 segundos+```++### Dados de Integração++**webhook** - URL para receber notificações+```+Exemplo: https://meusite.com/webhook+Recebe eventos em tempo real+```++**events** - Quais eventos quer receber+```+Exemplo: "MESSAGE,GROUP_UPDATE,CALL"+Pode ser "ALL" para receber tudo+```++**rabbitmqEnable** - Usar RabbitMQ?+```+"true" = Sim, enviar eventos+"false" = Não usar+```++**websocketEnable** - Usar WebSocket?+```+"true" = Sim, eventos em tempo real+"false" = Não usar+```++---++## Estados da Instância++### Diagrama de Estados++```+┌──────────────┐+│ CRIADA │ ← Acabou de criar+└──────┬───────┘+ │ (aguardando conexão)+ ▼+┌──────────────┐+│ DESCONECTADA │ ← Sem conexão WhatsApp+└──────┬───────┘+ │ (conectar)+ ▼+┌──────────────┐+│ CONECTANDO │ ← Iniciando conexão+└──────┬───────┘+ │ (gera QR Code)+ ▼+┌──────────────┐+│AGUARDANDO QR │ ← Esperando escanear+└──────┬───────┘+ │ (escaneia no celular)+ ▼+┌──────────────┐+│ ABERTA │ ← Conectado! ✓+└──────┬───────┘+ │ (pode enviar/receber)+ │+ │ (se desconectar)+ ▼+┌──────────────┐+│ DESCONECTADA │+└──────────────┘+```++### Verificando o Estado++**Via API**:+```bash+GET /instance/status?instanceName=vendas++Resposta:+{+ "connected": true,+ "loggedIn": true,+ "jid": "[email protected]",+ "name": "João Silva"+}+```++---++## Ciclo de Vida++### 1. Criar Instância++**Endpoint**: `POST /instance/create`++**O que acontece**:+1. Sistema verifica se o nome já existe+2. Gera um ID único automaticamente+3. Salva no banco de dados+4. Retorna informações da instância+5. **Não conecta ainda** - apenas cria o registro++**Exemplo**:+```json+POST /instance/create+{+ "name": "vendas",+ "token": "meu-token-vendas"+}++Resposta:+{+ "id": "abc-123",+ "name": "vendas",+ "token": "meu-token-vendas",+ "connected": false+}+```++### 2. Conectar Instância++**Endpoint**: `POST /instance/connect`++**O que acontece**:+1. Sistema inicia cliente WhatsApp+2. Gera QR Code+3. Salva QR Code no banco+4. Aguarda você escanear++**Exemplo**:+```json+POST /instance/connect+{+ "instanceName": "vendas",+ "webhookUrl": "https://meusite.com/webhook",+ "subscribe": ["MESSAGE", "GROUP_UPDATE"]+}+```++**Importante**: A conexão é assíncrona! O QR Code aparece depois de alguns segundos.++### 3. Obter QR Code++**Endpoint**: `GET /instance/qr?instanceName=vendas`++**O que acontece**:+1. Sistema verifica se já está conectado+2. Se não estiver, retorna o QR Code+3. QR Code tem duas partes separadas por `|`++**Formato do QR Code**:+```+parte1|parte2++parte1 = imagem PNG em base64+parte2 = código texto do QR+```++**Uso prático**:+```html+<!-- Mostrar QR Code na página -->+<img src="parte1" />++<!-- Ou usar a biblioteca JS -->+<qrcode value="parte2"></qrcode>+```++### 4. Parear com Código++**Endpoint**: `POST /instance/pair`++**Alternativa ao QR Code**: Você recebe um código de 8 dígitos para digitar no celular.++**Exemplo**:+```json+POST /instance/pair+{+ "instanceName": "vendas",+ "phone": "5511999999999"+}++Resposta:+{+ "pairingCode": "1234-5678"+}+```++**Como usar**:+1. Abra WhatsApp no celular+2. Vá em Dispositivos Conectados+3. Conectar Dispositivo+4. Digite o código: 1234-5678++### 5. Reconectar++**Endpoint**: `POST /instance/reconnect`++**Diferença importante**:+- **Connect**: Primeira vez, precisa de QR Code+- **Reconnect**: Já conectou antes, reutiliza sessão++**Quando usar**:+- Após reiniciar o servidor+- Quando perder conexão temporária+- Para forçar reconexão++**Não precisa de QR Code!** A sessão já está salva.++### 6. Desconectar++**Endpoint**: `POST /instance/disconnect`++**O que acontece**:+1. Fecha a conexão com WhatsApp+2. Para de receber mensagens+3. **Mantém a sessão salva**+4. Pode reconectar depois sem QR Code++**Quando usar**:+- Manutenção temporária+- Pausar operação+- Trocar configurações++### 7. Logout++**Endpoint**: `POST /instance/logout`++**Diferença de Disconnect**:+- **Disconnect**: Desliga mas mantém sessão+- **Logout**: Remove a sessão completamente++**O que acontece**:+1. Remove sessão do WhatsApp+2. Desconecta completamente+3. **Precisa de novo QR Code** para conectar de novo+4. Como se nunca tivesse conectado++**Quando usar**:+- Trocar de número+- Limpar conexão completamente+- Resetar instância++### 8. Deletar++**Endpoint**: `DELETE /instance/delete/:id`++**O que acontece**:+1. Faz logout se estiver conectado+2. Remove todas as mensagens dessa instância+3. Remove todas as labels dessa instância+4. **Deleta tudo do banco de dados**+5. Operação irreversível!++**⚠️ ATENÇÃO**: Não tem como desfazer!++---++## Configurações Avançadas++### O que São++Configurações extras para mudar o comportamento da instância.++### Opções Disponíveis++**alwaysOnline** - Aparecer sempre online+```+true = Sempre mostra como "online"+false = Normal (online quando está usando)+```++**rejectCall** - Rejeitar chamadas automaticamente+```+true = Rejeita chamadas de voz/vídeo+false = Aceita normalmente+```++**msgRejectCall** - Mensagem ao rejeitar+```+Exemplo: "Desculpe, não atendo chamadas. Envie mensagem de texto."+Enviada automaticamente quando rejeitar+```++**readMessages** - Marcar como lidas automaticamente+```+true = Marca todas as mensagens recebidas como lidas+false = Normal (você marca manualmente)+```++**ignoreGroups** - Ignorar mensagens de grupo+```+true = Não processa eventos de grupos+false = Normal (recebe tudo)+```++**ignoreStatus** - Ignorar status/stories+```+true = Não processa atualizações de status+false = Normal (recebe tudo)+```++### Como Configurar++**Endpoint**: `POST /instance/:id/advanced-settings`++**Exemplo**:+```json+{+ "alwaysOnline": true,+ "rejectCall": true,+ "msgRejectCall": "Não atendo chamadas, envie mensagem!",+ "readMessages": false,+ "ignoreGroups": false,+ "ignoreStatus": true+}+```++**Efeito**: Aplica instantaneamente sem precisar reconectar!++---++## Sistema de Eventos++### O que São Eventos++Notificações que o Evolution GO envia quando algo acontece.++**Analogia**: Como notificações do celular+- "Nova mensagem recebida!"+- "Fulano entrou no grupo!"+- "Chamada recebida!"++### Tipos de Eventos++**Mensagens**:+- `MESSAGE` - Mensagem recebida+- `MESSAGE_SENT` - Mensagem enviada+- `MESSAGE_UPDATE` - Mensagem editada/deletada+- `MESSAGE_REACTION` - Reação em mensagem++**Grupos**:+- `GROUP_UPDATE` - Grupo atualizado+- `GROUP_PARTICIPANT_UPDATE` - Alguém entrou/saiu++**Conexão**:+- `CONNECTION_UPDATE` - Mudou status de conexão+- `QR_CODE` - QR Code gerado+- `QRCODE_UPDATED` - QR Code atualizado++**Outros**:+- `PRESENCE_UPDATE` - Alguém ficou online/offline+- `CALL` - Chamada recebida+- `CONTACT_UPDATE` - Contato atualizado+- `LABEL` - Label criada/atualizada++### Como Subscrever++**Ao conectar, escolha quais eventos quer**:++```json+POST /instance/connect+{+ "instanceName": "vendas",+ "subscribe": ["MESSAGE", "GROUP_UPDATE", "CALL"]+}+```++**Opções**:+- Lista específica: `["MESSAGE", "CALL"]`+- Todos os eventos: `["ALL"]`+- Apenas mensagens (padrão): `["MESSAGE"]`++### Destinos dos Eventos++Pode enviar para vários lugares ao mesmo tempo:++**Webhook** (HTTP POST):+```json+{+ "webhookUrl": "https://meusite.com/webhook"+}+```++**RabbitMQ** (Fila de mensagens):+```json+{+ "rabbitmqEnable": "true"+}+```++**WebSocket** (Tempo real):+```json+{+ "websocketEnable": "true"+}+```++**NATS** (Sistema de eventos):+```json+{+ "natsEnable": "true"+}+```++**Pode ativar todos juntos!** Cada evento será enviado para todos os destinos configurados.++---++## Proxy++### O que é Proxy++Um servidor intermediário entre você e o WhatsApp.++**Analogia**: Como usar uma empresa de correio+- Você → Correio → Destinatário+- Seu IP fica escondido+- WhatsApp vê o IP do proxy++### Quando Usar++**Recomendado se**:+- Tem muitas instâncias (>10)+- Quer esconder seu IP real+- Precisa de múltiplos IPs+- WhatsApp bloqueou seu IP++### Como Configurar++**Endpoint**: `POST /instance/proxy/:id`++**Exemplo**:+```json+ {+ "host": "proxy.exemplo.com",+ "port": "8080",+ "username": "usuario", // Opcional+ "password": "senha" // Opcional+}+```++**Importante**: Precisa reconectar para aplicar!++### Como Remover++**Endpoint**: `DELETE /instance/proxy/:id`++Remove o proxy e volta a conexão direta.++---++## Boas Práticas++### 1. Nomeação++Use nomes descritivos:++**✅ Bom**:+- `vendas-regiao-sul`+- `suporte-nivel-1`+- `marketing-campanhas`+- `atendimento-24h`++**❌ Ruim**:+- `teste`+- `instance1`+- `minha-instancia`+- `zap`++### 2. Gerenciar Eventos++**Subscreva apenas o necessário**:++```json+// ✅ Bom - Apenas o que precisa+{"subscribe": ["MESSAGE", "GROUP_UPDATE"]}++// ❌ Ruim - Muito tráfego desnecessário+{"subscribe": ["ALL"]}+```++Menos eventos = menos processamento = mais rápido++### 3. Configurações Avançadas++**Otimize para seu caso**:++```json+// Bot de atendimento+{+ "ignoreGroups": true, // Não precisa de grupos+ "ignoreStatus": true, // Não precisa de status+ "readMessages": true // Marca como lido automaticamente+}++// Monitoramento de grupos+{+ "ignoreGroups": false, // Precisa de grupos+ "ignoreStatus": true, // Não precisa de status+ "readMessages": false // Não marca como lido+}+```++### 4. Use Proxy++**Se tiver muitas instâncias** (>10):++- Evita bloqueio de IP+- Distribui a carga+- Mais estável++### 5. Monitore Logs++**Acompanhe sua instância**:++```bash+GET /instance/logs/vendas?level=ERROR&limit=50+```++Veja erros antes que causem problemas!++### 6. Limpeza Regular++**Delete instâncias não usadas**:++```bash+DELETE /instance/delete/teste-antigo+```++Libera recursos e organiza o sistema.++### 7. Reconexão vs Logout++**Entenda a diferença**:++| Situação | Use |+|----------|-----|+| Reiniciou servidor | Reconnect |+| Perdeu conexão | Reconnect |+| Trocar de número | Logout |+| Limpar tudo | Logout + Delete |++---++## Limitações++### Limites do WhatsApp++**Dispositivos**:+- Máximo 4 dispositivos por número+- Evolution GO conta como 1 dispositivo++**QR Code**:+- Expira em ~40 segundos+- Máximo de tentativas por hora++**Reconexão**:+- Não reconecte mais de 1x por minuto+- Pode ser bloqueado temporariamente++### Limites do Evolution GO++**Por Servidor**:+- Depende da RAM disponível+- Cada instância usa ~50-100MB+- Exemplo: 16GB RAM = ~100 instâncias++**Banco de Dados**:+- PostgreSQL: 100 conexões simultâneas (padrão)+- Pode configurar mais se necessário++---++## Troubleshooting++### "no active session found"++**Problema**: Cliente não existe.++**Causa**: Não conectou ainda ou sessão expirou.++**Solução**:+1. Conecte via `POST /instance/connect`+2. Escaneie QR Code+3. Aguarde conectar++### "client disconnected"++**Problema**: Perdeu conexão com WhatsApp.++**Causa**: Internet caiu ou WhatsApp instável.++**Solução**:+```bash+POST /instance/reconnect+```++### QR Code não aparece++**Problema**: QR Code vazio ou nulo.++**Causa**: Cliente ainda inicializando.++**Solução**:+1. Aguarde 2-3 segundos após `/connect`+2. Tente `/instance/qr` novamente+3. Se persistir, tente reconectar++### Não reconecta após reiniciar++**Problema**: Precisa escanear QR Code de novo.++**Causa**: Sessão corrompida ou expirada.++**Solução**:+```bash+# 1. Logout completo+POST /instance/logout++# 2. Conectar de novo+POST /instance/connect++# 3. Escanear novo QR Code+```++### Mensagens não chegam++**Problema**: Eventos não são recebidos.++**Causa**: Configuração de eventos errada.++**Solução**:+1. Verifique se inscreveu no evento `MESSAGE`+2. Teste o webhook/RabbitMQ+3. Veja os logs da instância++---++## Exemplo Completo++### Do Zero até Enviar Mensagem++```bash+# 1. Criar instância+POST /instance/create+{+ "name": "vendas",+ "token": "token-vendas-123"+}++# 2. Conectar+POST /instance/connect+{+ "instanceName": "vendas",+ "webhookUrl": "https://meusite.com/webhook",+ "subscribe": ["MESSAGE"]+}++# 3. Aguardar 2 segundos...++# 4. Pegar QR Code+GET /instance/qr?instanceName=vendas++# 5. Escanear QR Code no celular++# 6. Aguardar conectar (~5 segundos)++# 7. Enviar mensagem! 🎉+POST /send/text+Headers: apikey: token-vendas-123+{+ "number": "5511999999999",+ "text": "Olá! Primeira mensagem!"+}+```++---++## Resumo Rápido++| Conceito | Explicação |+|----------|------------|+| **Instância** | Uma conexão WhatsApp independente |+| **QR Code** | Código para parear com celular |+| **Connect** | Primeira conexão (precisa QR) |+| **Reconnect** | Reconexão (não precisa QR) |+| **Logout** | Remove sessão completamente |+| **Delete** | Apaga tudo (irreversível) |+| **Eventos** | Notificações quando algo acontece |+| **Proxy** | Servidor intermediário |++**Lembre-se**:+- 📱 Cada instância = 1 WhatsApp+- 🔄 Reconnect não precisa de QR Code+- 🚪 Logout remove tudo+- 📊 Configure apenas eventos necessários+- 🔒 Use proxy para muitas instâncias+- 🗑️ Delete instâncias não usadas++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/deploy-producao/docker-deployment.md b/docs/wiki/deploy-producao/docker-deployment.mdnew file mode 100644index 0000000..70d1d8c--- /dev/null+++ b/docs/wiki/deploy-producao/docker-deployment.md@@ -0,0 +1,814 @@+# Deploy com Docker++Guia de deploy do Evolution GO usando Docker, Docker Compose, Swarm e Kubernetes.++## Índice++- [Visão Geral](#visão-geral)+- [Deploy com Docker Compose](#deploy-com-docker-compose)+- [Deploy com Docker Swarm](#deploy-com-docker-swarm)+- [Deploy com Kubernetes](#deploy-com-kubernetes)+- [Otimização e Gestão](#otimização-e-gestão)+- [Troubleshooting](#troubleshooting)++---++## Visão Geral++### Estratégias de Deploy++| Estratégia | Uso Recomendado | Complexidade | Escalabilidade |+|------------|-----------------|--------------|----------------|+| **Docker Compose** | Desenvolvimento, testes, deploys pequenos | Baixa | Limitada (single-host) |+| **Docker Swarm** | Produção pequena/média, HA | Média | Boa (multi-host) |+| **Kubernetes** | Produção enterprise, orquestração avançada | Alta | Excelente |++### Arquitetura de Componentes++```+┌─────────────────────────────────────────────────────────────────┐+│ EVOLUTION GO STACK │+├─────────────────────────────────────────────────────────────────┤+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Evolution GO │◄────►│ PostgreSQL │ │ RabbitMQ │ │+│ │ (API) │ │ (Auth DB) │ │ (Events) │ │+│ │ Port: 4000 │ │ (Users DB) │ │ Port: 5672 │ │+│ └──────┬───────┘ └──────────────┘ └──────────────┘ │+│ │ │+│ │ ┌──────────────┐ ┌──────────────┐ │+│ └─────────────►│ MinIO │ │ NATS │ │+│ │ (Media) │ │ (Optional) │ │+│ │ Port: 9000 │ │ Port: 4222 │ │+│ └──────────────┘ └──────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────┘+```++### Imagem Docker++- **Registry**: `evoapicloud/evolution-go`+- **Tags**: `latest`, `v1.x.x`+- **Base**: Alpine Linux 3.19.1+- **Tamanho**: ~50MB (compactada)+- **Arquiteturas**: amd64, arm64++---++## Deploy com Docker Compose++### Setup Básico++Configuração mínima com Evolution GO + PostgreSQL.++#### docker-compose.yml++```yaml+version: '3.8'++services:+ evolution-go:+ image: evoapicloud/evolution-go:latest+ container_name: evolution-go+ restart: unless-stopped+ ports:+ - "4000:4000"+ environment:+ SERVER_PORT: 4000+ CLIENT_NAME: "evolution"+ GLOBAL_API_KEY: "SUBSTITUA-POR-UUID-FORTE"++ POSTGRES_AUTH_DB: "postgresql://postgres:postgres@postgres:5432/evogo_auth?sslmode=disable"+ POSTGRES_USERS_DB: "postgresql://postgres:postgres@postgres:5432/evogo_users?sslmode=disable"+ DATABASE_SAVE_MESSAGES: "false"++ WADEBUG: "INFO"+ LOGTYPE: "console"+ CONNECT_ON_STARTUP: "false"+ WEBHOOKFILES: "true"++ volumes:+ - evolution_data:/app/dbdata+ - evolution_logs:/app/logs+ networks:+ - evolution_network+ depends_on:+ - postgres++ postgres:+ image: postgres:15-alpine+ container_name: postgres+ restart: unless-stopped+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: postgres+ ports:+ - "5432:5432"+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql+ networks:+ - evolution_network++volumes:+ evolution_data:+ evolution_logs:+ postgres_data:++networks:+ evolution_network:+ driver: bridge+```++#### init-db.sql++```sql+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+SELECT 'Databases criados com sucesso!' as message;+```++#### Deploy++```bash+# Gerar API Key+uuidgen++# Editar docker-compose.yml e inserir API Key++# Iniciar+docker-compose up -d++# Verificar+docker-compose logs -f evolution-go+curl http://localhost:4000/server/ok+```++### Setup Completo++Incluindo RabbitMQ, MinIO e NATS.++```yaml+version: '3.8'++services:+ evolution-go:+ image: evoapicloud/evolution-go:latest+ restart: unless-stopped+ ports:+ - "4000:4000"+ environment:+ SERVER_PORT: 4000+ GLOBAL_API_KEY: "SUA-CHAVE-AQUI"++ POSTGRES_AUTH_DB: "postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable"+ POSTGRES_USERS_DB: "postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable"+ DATABASE_SAVE_MESSAGES: "true"++ AMQP_URL: "amqp://admin:admin@rabbitmq:5672/default"+ AMQP_GLOBAL_ENABLED: "true"+ AMQP_GLOBAL_EVENTS: "messages.upsert,messages.update,connection.update"++ MINIO_ENABLED: "true"+ MINIO_ENDPOINT: "minio:9000"+ MINIO_ACCESS_KEY: "minioadmin"+ MINIO_SECRET_KEY: "minioadmin"+ MINIO_BUCKET: "evolution-media"+ MINIO_USE_SSL: "false"++ volumes:+ - evolution_data:/app/dbdata+ - evolution_logs:/app/logs+ depends_on:+ - postgres+ - rabbitmq+ - minio++ postgres:+ image: postgres:15-alpine+ restart: unless-stopped+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: senha+ POSTGRES_DB: postgres+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./init-db.sql:/docker-entrypoint-initdb.d/init-db.sql++ rabbitmq:+ image: rabbitmq:3-management-alpine+ restart: unless-stopped+ environment:+ RABBITMQ_DEFAULT_USER: admin+ RABBITMQ_DEFAULT_PASS: admin+ RABBITMQ_DEFAULT_VHOST: default+ ports:+ - "5672:5672"+ - "15672:15672"+ volumes:+ - rabbitmq_data:/var/lib/rabbitmq++ minio:+ image: minio/minio:latest+ restart: unless-stopped+ command: server /data --console-address ":9001"+ environment:+ MINIO_ROOT_USER: minioadmin+ MINIO_ROOT_PASSWORD: minioadmin+ ports:+ - "9000:9000"+ - "9001:9001"+ volumes:+ - minio_data:/data++ nats:+ image: nats:2-alpine+ restart: unless-stopped+ ports:+ - "4222:4222"+ - "8222:8222"++volumes:+ evolution_data:+ evolution_logs:+ postgres_data:+ rabbitmq_data:+ minio_data:+```++**Acessos:**+- Evolution GO: http://localhost:4000+- Swagger: http://localhost:4000/swagger/index.html+- RabbitMQ: http://localhost:15672 (admin/admin)+- MinIO: http://localhost:9001 (minioadmin/minioadmin)++### Configurações Avançadas++#### Arquivo .env++```bash+# .env+EVOLUTION_VERSION=latest+POSTGRES_VERSION=15-alpine++# Portas+EVOLUTION_PORT=4000+POSTGRES_PORT=5432++# Credenciais+POSTGRES_USER=postgres+POSTGRES_PASSWORD=senha_forte+RABBITMQ_USER=admin+RABBITMQ_PASS=senha_forte++# Evolution GO+GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db+CLIENT_NAME=evolution-prod+```++Referência no compose:+```yaml+services:+ evolution-go:+ image: evoapicloud/evolution-go:${EVOLUTION_VERSION:-latest}+ ports:+ - "${EVOLUTION_PORT:-4000}:4000"+ environment:+ GLOBAL_API_KEY: "${GLOBAL_API_KEY}"+```++#### Health Checks++```yaml+services:+ evolution-go:+ healthcheck:+ test: ["CMD", "wget", "-q", "--spider", "http://localhost:4000/server/ok"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 40s++ postgres:+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 10s+ timeout: 5s+ retries: 5++ rabbitmq:+ healthcheck:+ test: ["CMD", "rabbitmq-diagnostics", "ping"]+ interval: 30s+ timeout: 10s+ retries: 3+```++#### Resource Limits++```yaml+services:+ evolution-go:+ deploy:+ resources:+ limits:+ cpus: '2.0'+ memory: 2G+ reservations:+ cpus: '0.5'+ memory: 512M++ postgres:+ deploy:+ resources:+ limits:+ cpus: '1.0'+ memory: 1G+ reservations:+ cpus: '0.25'+ memory: 256M+```++---++## Deploy com Docker Swarm++### Inicialização++```bash+# Manager node+docker swarm init --advertise-addr 192.168.1.10++# Worker nodes+docker swarm join --token SWMTKN-1-xxxxx 192.168.1.10:2377++# Verificar cluster+docker node ls+```++### Preparação++```bash+# Volumes+docker volume create evolution_go_data+docker volume create evolution_go_logs++# Rede+docker network create --driver overlay network_public+```++### docker-compose.swarm.yml++```yaml+version: '3.8'++services:+ evolution_go:+ image: evoapicloud/evolution-go:latest+ networks:+ - network_public+ environment:+ SERVER_PORT: 4000+ GLOBAL_API_KEY: "sua-chave-api"+ POSTGRES_AUTH_DB: "postgresql://user:pass@postgres:5432/evogo_auth"+ POSTGRES_USERS_DB: "postgresql://user:pass@postgres:5432/evogo_users"++ volumes:+ - evolution_go_data:/app/dbdata+ - evolution_go_logs:/app/logs++ deploy:+ replicas: 3+ placement:+ constraints:+ - node.role == worker+ restart_policy:+ condition: on-failure+ delay: 5s+ max_attempts: 3+ window: 120s+ update_config:+ parallelism: 1+ delay: 10s+ failure_action: rollback+ order: start-first+ rollback_config:+ parallelism: 1+ delay: 5s+ labels:+ - traefik.enable=true+ - traefik.http.routers.evolution.rule=Host(`evolution.domain.com`)+ - traefik.http.routers.evolution.entrypoints=websecure+ - traefik.http.routers.evolution.tls.certresolver=letsencrypt+ - traefik.http.services.evolution.loadbalancer.server.port=4000++volumes:+ evolution_go_data:+ external: true+ evolution_go_logs:+ external: true++networks:+ network_public:+ external: true+```++### Deploy e Gerenciamento++```bash+# Deploy+docker stack deploy -c docker-compose.swarm.yml evolution++# Status+docker stack ls+docker service ls+docker service ps evolution_evolution_go++# Logs+docker service logs evolution_evolution_go -f++# Escalar+docker service scale evolution_evolution_go=5++# Atualizar (rolling update)+docker service update --image evoapicloud/evolution-go:v1.2.0 evolution_evolution_go++# Remover+docker stack rm evolution+```++---++## Deploy com Kubernetes++### Manifests Básicos++#### Namespace++```yaml+# namespace.yaml+apiVersion: v1+kind: Namespace+metadata:+ name: evolution-go+```++#### ConfigMap++```yaml+# configmap.yaml+apiVersion: v1+kind: ConfigMap+metadata:+ name: evolution-config+ namespace: evolution-go+data:+ SERVER_PORT: "4000"+ CLIENT_NAME: "evolution"+ WADEBUG: "INFO"+ LOGTYPE: "console"+ CONNECT_ON_STARTUP: "false"+ WEBHOOKFILES: "true"+ DATABASE_SAVE_MESSAGES: "false"+```++#### Secrets++```bash+kubectl create secret generic evolution-secrets \+ --from-literal=GLOBAL_API_KEY=$(uuidgen) \+ --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \+ --namespace=evolution-go+```++#### Deployment++```yaml+# deployment.yaml+apiVersion: apps/v1+kind: Deployment+metadata:+ name: evolution-go+ namespace: evolution-go+spec:+ replicas: 3+ selector:+ matchLabels:+ app: evolution-go+ template:+ metadata:+ labels:+ app: evolution-go+ spec:+ containers:+ - name: evolution-go+ image: evoapicloud/evolution-go:latest+ ports:+ - containerPort: 4000+ env:+ - name: SERVER_PORT+ valueFrom:+ configMapKeyRef:+ name: evolution-config+ key: SERVER_PORT+ - name: GLOBAL_API_KEY+ valueFrom:+ secretKeyRef:+ name: evolution-secrets+ key: GLOBAL_API_KEY+ resources:+ requests:+ memory: "512Mi"+ cpu: "500m"+ limits:+ memory: "2Gi"+ cpu: "2000m"+ livenessProbe:+ httpGet:+ path: /server/ok+ port: 4000+ initialDelaySeconds: 30+ periodSeconds: 10+ readinessProbe:+ httpGet:+ path: /server/ok+ port: 4000+ initialDelaySeconds: 10+ periodSeconds: 5+ volumeMounts:+ - name: evolution-data+ mountPath: /app/dbdata+ - name: evolution-logs+ mountPath: /app/logs+ volumes:+ - name: evolution-data+ persistentVolumeClaim:+ claimName: evolution-data-pvc+ - name: evolution-logs+ persistentVolumeClaim:+ claimName: evolution-logs-pvc+```++#### Service++```yaml+# service.yaml+apiVersion: v1+kind: Service+metadata:+ name: evolution-go-service+ namespace: evolution-go+spec:+ type: LoadBalancer+ selector:+ app: evolution-go+ ports:+ - port: 4000+ targetPort: 4000+```++#### Ingress++```yaml+# ingress.yaml+apiVersion: networking.k8s.io/v1+kind: Ingress+metadata:+ name: evolution-ingress+ namespace: evolution-go+ annotations:+ kubernetes.io/ingress.class: "nginx"+ cert-manager.io/cluster-issuer: "letsencrypt-prod"+spec:+ tls:+ - hosts:+ - evolution.domain.com+ secretName: evolution-tls+ rules:+ - host: evolution.domain.com+ http:+ paths:+ - path: /+ pathType: Prefix+ backend:+ service:+ name: evolution-go-service+ port:+ number: 4000+```++#### HorizontalPodAutoscaler++```yaml+# hpa.yaml+apiVersion: autoscaling/v2+kind: HorizontalPodAutoscaler+metadata:+ name: evolution-hpa+ namespace: evolution-go+spec:+ scaleTargetRef:+ apiVersion: apps/v1+ kind: Deployment+ name: evolution-go+ minReplicas: 3+ maxReplicas: 10+ metrics:+ - type: Resource+ resource:+ name: cpu+ target:+ type: Utilization+ averageUtilization: 70+ - type: Resource+ resource:+ name: memory+ target:+ type: Utilization+ averageUtilization: 80+```++### Deploy Kubernetes++```bash+# Aplicar manifests+kubectl apply -f namespace.yaml+kubectl apply -f configmap.yaml+kubectl apply -f secrets.yaml+kubectl apply -f deployment.yaml+kubectl apply -f service.yaml+kubectl apply -f ingress.yaml+kubectl apply -f hpa.yaml++# Verificar+kubectl get all -n evolution-go+kubectl get pods -n evolution-go++# Logs+kubectl logs -f deployment/evolution-go -n evolution-go++# Escalar+kubectl scale deployment evolution-go --replicas=5 -n evolution-go++# Atualizar+kubectl set image deployment/evolution-go \+ evolution-go=evoapicloud/evolution-go:v1.2.0 \+ -n evolution-go++# Rollback+kubectl rollout undo deployment/evolution-go -n evolution-go+```++---++## Otimização e Gestão++### Gestão de Volumes++#### Backup++```bash+# Backup volume+docker run --rm \+ -v evolution_data:/data \+ -v $(pwd):/backup \+ alpine tar czf /backup/backup-$(date +%Y%m%d).tar.gz -C /data .++# Restaurar+docker run --rm \+ -v evolution_data:/data \+ -v $(pwd):/backup \+ alpine tar xzf /backup/backup-20250111.tar.gz -C /data+```++### Logging++```yaml+services:+ evolution-go:+logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "3"+```++### Boas Práticas++**Segurança:**+- Não executar containers como root+- Usar secrets para credenciais+- Habilitar HTTPS em produção+- Configurar resource limits+- Implementar health checks++**Performance:**+- Definir resource requests/limits+- Usar health checks+- Implementar HPA (Kubernetes)+- Configurar connection pooling++**Monitoramento:**+- Coletar logs centralizados+- Implementar métricas (Prometheus)+- Configurar alertas+- Dashboard de visualização (Grafana)++---++## Troubleshooting++### Container Reiniciando++```bash+# Ver logs+docker-compose logs evolution-go++# Verificar variáveis obrigatórias+# - GLOBAL_API_KEY+# - POSTGRES_*_DB+```++### Conectividade PostgreSQL++```bash+# Testar conexão+docker-compose exec evolution-go ping postgres++# Verificar porta+docker-compose exec evolution-go nc -zv postgres 5432++# Inspecionar rede+docker network inspect evolution_network+```++### Sem Espaço em Disco++```bash+# Ver uso+docker system df++# Limpar+docker container prune+docker image prune+docker volume prune # CUIDADO: apaga volumes não utilizados+docker system prune -a+```++### OOM (Out of Memory)++```bash+# Ver eventos OOM+docker events --filter 'event=oom'++# Ver uso de memória+docker stats evolution-go++# Aumentar limite+deploy:+ resources:+ limits:+ memory: 4G+```++---++## Comandos Úteis++### Docker Compose++```bash+docker-compose up -d # Iniciar+docker-compose ps # Status+docker-compose logs -f # Logs+docker-compose stop # Parar+docker-compose restart # Reiniciar+docker-compose down # Remover+docker-compose pull # Atualizar imagens+```++### Docker Swarm++```bash+docker stack deploy -c file.yml name # Deploy+docker stack ls # Listar stacks+docker service ls # Listar serviços+docker service logs name -f # Logs+docker service scale name=N # Escalar+docker stack rm name # Remover+```++### Kubernetes++```bash+kubectl apply -f file.yaml # Aplicar+kubectl get all -n namespace # Listar recursos+kubectl logs -f deployment/name # Logs+kubectl scale deployment name --replicas=N # Escalar+kubectl delete -f file.yaml # Deletar+```++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/deploy-producao/security.md b/docs/wiki/deploy-producao/security.mdnew file mode 100644index 0000000..fc2a6a2--- /dev/null+++ b/docs/wiki/deploy-producao/security.md@@ -0,0 +1,732 @@+# Segurança e Hardening++Guia de práticas de segurança para ambientes de produção do Evolution GO.++## Índice++- [Princípios de Segurança](#princípios-de-segurança)+- [Autenticação e API Keys](#autenticação-e-api-keys)+- [Gestão de Secrets](#gestão-de-secrets)+- [Segurança de Rede](#segurança-de-rede)+- [Hardening de Containers](#hardening-de-containers)+- [SSL/TLS](#ssltls)+- [Segurança do Banco de Dados](#segurança-do-banco-de-dados)+- [Backup Seguro](#backup-seguro)+- [Proteção contra Ataques](#proteção-contra-ataques)+- [Auditoria e Compliance](#auditoria-e-compliance)+- [Resposta a Incidentes](#resposta-a-incidentes)++---++## Princípios de Segurança++### Defense in Depth++Implementar múltiplas camadas de proteção:+- Autenticação forte+- Firewall e isolamento de rede+- Criptografia em trânsito e repouso+- Monitoramento e auditoria+- Backup e disaster recovery++### Least Privilege++Conceder apenas permissões mínimas necessárias:+- Containers não executam como root+- Credenciais com escopo limitado+- Acesso à rede restrito+- Segregação de ambientes++### Security by Default++- Configurações seguras desde a instalação+- HTTPS obrigatório em produção+- Logs de auditoria habilitados+- Credenciais fortes exigidas++### Requisitos por Ambiente++| Ambiente | Segurança Mínima |+|----------|------------------|+| **Desenvolvimento** | API Key forte, senhas não-padrão |+| **Staging** | + Firewall, backup, logs |+| **Produção** | + HTTPS, monitoramento, auditoria, secrets management |++---++## Autenticação e API Keys++### Geração de API Keys++Utilize chaves criptograficamente seguras:++```bash+# UUID v4 (recomendado)+uuidgen++# 64 caracteres hexadecimais+openssl rand -hex 32++# URL-safe base64+python3 -c "import secrets; print(secrets.token_urlsafe(32))"+```++**Exemplo de chave forte:**+```+df16caad-d0d2-41b2-bec5-75b90048a0db+```++**Evitar:**+- Valores padrão ou previsíveis+- Senhas comuns ou sequências+- Reutilização de chaves entre ambientes++### Rotação de Chaves++**Política recomendada:**+- Rotação periódica (90 dias)+- Rotação imediata em caso de comprometimento+- Manter período de transição para atualização de clientes++**Processo de rotação:**++1. Gerar nova chave+2. Atualizar configuração do servidor+3. Notificar clientes integradores+4. Estabelecer deadline para migração+5. Desabilitar chave antiga++### Rate Limiting++Implementar limitação de requisições por API Key via NGINX:++```nginx+http {+ map $http_apikey $limit_key {+ default $http_apikey;+ "" $binary_remote_addr;+ }++ limit_req_zone $limit_key zone=api_limit:10m rate=100r/s;++ server {+ location / {+ limit_req zone=api_limit burst=200 nodelay;+ limit_req_status 429;+ proxy_pass http://evolution-go:4000;+ }+ }+}+```++---++## Gestão de Secrets++### Docker Secrets (Swarm)++```bash+# Criar secrets+echo "senha_postgres" | docker secret create postgres_password -+echo "$(uuidgen)" | docker secret create evolution_api_key -++# docker-compose.swarm.yml+services:+ evolution-go:+ secrets:+ - evolution_api_key+ - postgres_password+ environment:+ GLOBAL_API_KEY_FILE: /run/secrets/evolution_api_key+ POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password++secrets:+ evolution_api_key:+ external: true+ postgres_password:+ external: true+```++### Kubernetes Secrets++```bash+# Criar secrets+kubectl create secret generic evolution-secrets \+ --from-literal=GLOBAL_API_KEY=$(uuidgen) \+ --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 32) \+ --namespace=evolution-go++# Habilitar encryption at rest+# https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/+```++```yaml+# deployment.yaml+ env:+ - name: GLOBAL_API_KEY+ valueFrom:+ secretKeyRef:+ name: evolution-secrets+ key: GLOBAL_API_KEY+ - name: POSTGRES_PASSWORD+ valueFrom:+ secretKeyRef:+ name: evolution-secrets+ key: POSTGRES_PASSWORD+```++### HashiCorp Vault++```yaml+# vault-agent-config.hcl+vault {+ address = "https://vault.seudominio.com:8200"+}++auto_auth {+ method {+ type = "kubernetes"+ config = {+ role = "evolution-go"+ }+ }+}++template {+ source = "/vault/configs/.env.tpl"+ destination = "/app/.env"+}+```++---++## Segurança de Rede++### Firewall (iptables)++```bash+#!/bin/bash+# firewall-setup.sh++# Políticas padrão+iptables -P INPUT DROP+iptables -P FORWARD DROP+iptables -P OUTPUT ACCEPT++# Loopback+iptables -A INPUT -i lo -j ACCEPT++# Conexões estabelecidas+iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT++# SSH com rate limiting+iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set+iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP+iptables -A INPUT -p tcp --dport 22 -j ACCEPT++# HTTP/HTTPS restrito à rede interna+iptables -A INPUT -p tcp --dport 80 -s 10.0.1.0/24 -j ACCEPT+iptables -A INPUT -p tcp --dport 443 -s 10.0.1.0/24 -j ACCEPT++# Docker network+iptables -A INPUT -s 172.16.0.0/12 -j ACCEPT++# Drop inválidos+iptables -A INPUT -m conntrack --ctstate INVALID -j DROP++# Salvar regras+iptables-save > /etc/iptables/rules.v4+```++### UFW (Alternativa Simplificada)++```bash+sudo apt-get install ufw++# Configurar padrões+sudo ufw default deny incoming+sudo ufw default allow outgoing++# Permitir serviços+sudo ufw allow 22/tcp # SSH+sudo ufw allow 80/tcp # HTTP+sudo ufw allow 443/tcp # HTTPS++# Ativar+sudo ufw enable++# Status+sudo ufw status+```++### Isolamento de Redes Docker++```yaml+networks:+ frontend:+ driver: overlay+ driver_opts:+ encrypted: "true"++ backend:+ driver: overlay+ driver_opts:+ encrypted: "true"+ internal: true # Sem acesso externo++services:+ evolution-go:+ networks:+ - frontend+ - backend++ postgres:+ networks:+ - backend # Apenas rede interna+```++---++## Hardening de Containers++### Não Executar como Root++```dockerfile+FROM alpine:3.19.1++RUN addgroup -g 1000 evolution && \+ adduser -D -u 1000 -G evolution evolution++WORKDIR /app+COPY --chown=evolution:evolution server .++USER evolution++ENTRYPOINT ["/app/server"]+```++### Filesystem Read-Only++```yaml+services:+ evolution-go:+ read_only: true+ tmpfs:+ - /tmp+ volumes:+ - evolution_data:/app/dbdata+ - evolution_logs:/app/logs+```++### Security Options++```yaml+services:+ evolution-go:+ security_opt:+ - no-new-privileges:true+ - apparmor:docker-default+ - seccomp:default.json+ cap_drop:+ - ALL+ cap_add:+ - NET_BIND_SERVICE # Apenas se necessário+```++### Limites de Recursos++```yaml+services:+ evolution-go:+ deploy:+ resources:+ limits:+ cpus: '2.0'+ memory: 2G+ pids: 100+ reservations:+ cpus: '1.0'+ memory: 1G+ ulimits:+ nofile:+ soft: 1024+ hard: 2048+ nproc: 64+```++### Scan de Vulnerabilidades++```bash+# Trivy+trivy image evoapicloud/evolution-go:latest++# Apenas críticas+trivy image --severity CRITICAL evoapicloud/evolution-go:latest++# Docker Scout+docker scout cves evoapicloud/evolution-go:latest+```++---++## SSL/TLS++### Obtenção de Certificados (Let's Encrypt)++```bash+# Instalar Certbot+sudo apt-get install certbot++# Gerar certificado+sudo certbot certonly --standalone -d evolution.seudominio.com++# Certificados em:+# /etc/letsencrypt/live/evolution.seudominio.com/+```++### Configuração NGINX++```nginx+# Redirecionar HTTP → HTTPS+server {+ listen 80;+ server_name evolution.seudominio.com;+ return 301 https://$server_name$request_uri;+}++# HTTPS+server {+ listen 443 ssl http2;+ server_name evolution.seudominio.com;++ # Certificados+ ssl_certificate /etc/letsencrypt/live/evolution.seudominio.com/fullchain.pem;+ ssl_certificate_key /etc/letsencrypt/live/evolution.seudominio.com/privkey.pem;++ # Protocolos e ciphers+ ssl_protocols TLSv1.2 TLSv1.3;+ ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';+ ssl_prefer_server_ciphers off;++ # HSTS+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;++ # OCSP Stapling+ ssl_stapling on;+ ssl_stapling_verify on;+ ssl_trusted_certificate /etc/letsencrypt/live/evolution.seudominio.com/chain.pem;++ # Security Headers+ add_header X-Frame-Options "SAMEORIGIN" always;+ add_header X-Content-Type-Options "nosniff" always;+ add_header X-XSS-Protection "1; mode=block" always;+ add_header Referrer-Policy "no-referrer-when-downgrade" always;++ # Ocultar server tokens+ server_tokens off;++ location / {+ proxy_pass http://evolution-go:4000;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_hide_header X-Powered-By;+ }+}+```++### Renovação Automática++```bash+# Testar renovação+sudo certbot renew --dry-run++# Agendar via cron+sudo crontab -e++# Adicionar (renovação diária às 3h)+0 3 * * * certbot renew --quiet && systemctl reload nginx+```++---++## Segurança do Banco de Dados++### PostgreSQL Hardening++```ini+# postgresql.conf++# SSL obrigatório+ssl = on+ssl_cert_file = '/etc/ssl/certs/server.crt'+ssl_key_file = '/etc/ssl/private/server.key'++# Auditoria+log_connections = on+log_disconnections = on+log_duration = on+log_statement = 'mod' # INSERT, UPDATE, DELETE++# Senha forte obrigatória+password_encryption = scram-sha-256+```++```ini+# pg_hba.conf++# Apenas SSL+hostssl evogo_auth evolution 10.0.0.0/8 scram-sha-256+hostssl evogo_users evolution 10.0.0.0/8 scram-sha-256++# Rejeitar sem SSL+hostnossl all all 0.0.0.0/0 reject+```++### Backup Criptografado++```bash+#!/bin/bash+# backup-encrypted.sh++TIMESTAMP=$(date +%Y%m%d_%H%M%S)+BACKUP_FILE="postgres_${TIMESTAMP}.sql.gz.gpg"++# Dump e criptografar+docker exec postgres pg_dumpall -U postgres | \+ gzip | \+ gpg --symmetric --cipher-algo AES256 --output "/backups/${BACKUP_FILE}"++# Upload S3 com SSE+aws s3 cp "/backups/${BACKUP_FILE}" \+ "s3://bucket-backup/postgres/${BACKUP_FILE}" \+ --server-side-encryption AES256+```++---++## Backup Seguro++### Estratégia 3-2-1++- 3 cópias dos dados+- 2 mídias diferentes+- 1 cópia offsite++```bash+#!/bin/bash+# backup-secure.sh++TIMESTAMP=$(date +%Y%m%d_%H%M%S)+BACKUP_DIR="/backups"+S3_BUCKET="s3://backup-bucket"+GPG_KEY="[email protected]"++# PostgreSQL+docker exec postgres pg_dumpall -U postgres | \+ gzip | \+ gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg"++# Volumes+docker run --rm \+ -v evolution_data:/data \+ -v ${BACKUP_DIR}:/backup \+ alpine tar czf - -C /data . | \+ gpg --encrypt --recipient $GPG_KEY --output "${BACKUP_DIR}/evolution_data_${TIMESTAMP}.tar.gz.gpg"++# Upload S3 com KMS+aws s3 cp "${BACKUP_DIR}/postgres_${TIMESTAMP}.sql.gz.gpg" \+ "${S3_BUCKET}/postgres/" \+ --server-side-encryption aws:kms \+ --ssekms-key-id alias/backup-key++# Limpeza (30 dias)+find ${BACKUP_DIR} -name "*.gpg" -mtime +30 -delete+```++---++## Proteção contra Ataques++### DDoS Protection++**NGINX Rate Limiting:**++```nginx+http {+ limit_conn_zone $binary_remote_addr zone=conn_limit:10m;+ limit_conn conn_limit 10;++ limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;++ server {+ location / {+ limit_req zone=req_limit burst=20 nodelay;+ proxy_pass http://evolution-go:4000;+ }+ }+}+```++**Cloudflare:** Habilitar proteção DDoS no painel.++### SQL Injection++Evolution GO usa GORM (ORM) que previne SQL injection por padrão através de prepared statements.++### Brute-Force Protection (Fail2ban)++```bash+sudo apt-get install fail2ban+```++```ini+# /etc/fail2ban/jail.local+[nginx-req-limit]+enabled = true+filter = nginx-req-limit+logpath = /var/log/nginx/error.log+maxretry = 5+findtime = 600+bantime = 3600+```++```ini+# /etc/fail2ban/filter.d/nginx-req-limit.conf+[Definition]+failregex = limiting requests, excess:.* by zone.*client: <HOST>+```++---++## Auditoria e Compliance++### LGPD/GDPR++**Direito ao esquecimento:**++```sql+CREATE PROCEDURE delete_user_data(user_phone VARCHAR)+LANGUAGE plpgsql+AS $$+BEGIN+ DELETE FROM messages WHERE phone = user_phone;+ DELETE FROM contacts WHERE phone = user_phone;+ DELETE FROM instances WHERE owner_phone = user_phone;++ INSERT INTO audit_log (action, details, timestamp)+ VALUES ('user_data_deleted', user_phone, NOW());++ COMMIT;+END;+$$;+```++**Retenção de dados:**++```sql+-- Deletar mensagens antigas (30 dias)+DELETE FROM messages WHERE timestamp < NOW() - INTERVAL '30 days';+```++### Logging de Auditoria++```yaml+services:+ evolution-go:+ logging:+ driver: "json-file"+ options:+ max-size: "10m"+ max-file: "5"+ labels: "service,environment"+```++---++## Resposta a Incidentes++### Plano de Resposta++**1. Detecção**+- Alertas automatizados+- Monitoramento de logs+- Relatórios de usuários++**2. Contenção**+- Isolar sistemas afetados+- Revogar credenciais comprometidas+- Bloquear IPs maliciosos+- Capturar evidências++**3. Erradicação**+- Aplicar patches+- Atualizar imagens+- Revisar logs de auditoria+- Remover backdoors++**4. Recuperação**+- Restaurar de backup+- Validar integridade+- Monitorar por 48h++**5. Pós-Incidente**+- Documentar lições aprendidas+- Atualizar runbooks+- Treinar equipe++### Forensics++```bash+# Capturar estado do container+docker commit container_suspeito forensics-image+docker save forensics-image > forensics-image.tar++# Coletar logs+docker logs container_suspeito > logs_suspeito.txt++# Inspecionar+docker inspect container_suspeito > inspect_suspeito.json++# Exportar filesystem+docker export container_suspeito > filesystem_suspeito.tar+```++---++## Checklist de Segurança++### Crítico+- [ ] API Keys fortes (UUID)+- [ ] HTTPS habilitado+- [ ] Secrets em vault/secrets manager+- [ ] Firewall configurado+- [ ] Backups automáticos funcionando++### Importante+- [ ] Containers não executam como root+- [ ] Isolamento de redes Docker+- [ ] Limites de recursos definidos+- [ ] Logs de auditoria ativos+- [ ] Monitoramento configurado++### Recomendado+- [ ] Scan de vulnerabilidades regular+- [ ] Plano de resposta a incidentes+- [ ] Testes de restauração de backup+- [ ] Documentação de segurança+- [ ] Treinamento da equipe++---++## Recursos Adicionais++- [OWASP Top 10](https://owasp.org/www-project-top-ten/)+- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker)+- [Kubernetes Security Best Practices](https://kubernetes.io/docs/concepts/security/)+- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/desenvolvimento/contributing.md b/docs/wiki/desenvolvimento/contributing.mdnew file mode 100644index 0000000..f9dea82--- /dev/null+++ b/docs/wiki/desenvolvimento/contributing.md@@ -0,0 +1,297 @@+# Como Contribuir++Guia para contribuir com o Evolution GO.++## Índice++- [Como Contribuir](#como-contribuir)+- [Código de Conduta](#código-de-conduta)+- [Reportando Bugs](#reportando-bugs)+- [Sugerindo Features](#sugerindo-features)+- [Pull Requests](#pull-requests)+- [Padrões de Código](#padrões-de-código)+- [Processo de Review](#processo-de-review)++---++## Como Contribuir++Contribuições são bem-vindas! Você pode contribuir:++- 🐛 Reportando bugs+- 💡 Sugerindo novas features+- 📝 Melhorando documentação+- 🔧 Corrigindo bugs+- ✨ Implementando features++---++## Código de Conduta++- Seja respeitoso e profissional+- Aceite feedback construtivo+- Foque no que é melhor para a comunidade+- Mostre empatia com outros membros++---++## Reportando Bugs++### Antes de Reportar++1. Verifique se o bug já foi reportado nas [Issues](https://git.evoai.app/Evolution/evolution-go/issues)+2. Teste na versão mais recente+3. Colete informações: logs, versão do Go, sistema operacional++### Template de Bug Report++```markdown+**Descrição do Bug**+Descrição clara e concisa do bug.++**Como Reproduzir**+1. Faça X+2. Execute Y+3. Veja erro Z++**Comportamento Esperado**+O que deveria acontecer.++**Comportamento Atual**+O que está acontecendo.++**Screenshots/Logs**+Se aplicável, adicione screenshots ou logs.++**Ambiente**+- OS: [ex: Ubuntu 22.04]+- Go Version: [ex: 1.24.0]+- Evolution GO Version: [ex: v1.0.0]+- PostgreSQL Version: [ex: 15.2]++**Informações Adicionais**+Qualquer outro contexto sobre o problema.+```++---++## Sugerindo Features++### Template de Feature Request++```markdown+**Descrição da Feature**+Descrição clara da feature proposta.++**Problema que Resolve**+Qual problema esta feature resolve?++**Solução Proposta**+Como você imagina que esta feature funcionaria?++**Alternativas Consideradas**+Outras abordagens que você considerou?++**Informações Adicionais**+Mockups, exemplos, referências, etc.+```++---++## Pull Requests++### Processo++1. **Fork** o repositório+2. **Clone** seu fork: `git clone https://git.evochat.com/SEU-USUARIO/evolution-go.git`+3. **Crie branch**: `git checkout -b feature/minha-feature`+4. **Desenvolva** e **commit** suas mudanças+5. **Push**: `git push origin feature/minha-feature`+6. **Abra PR** no repositório original++### Checklist do PR++- [ ] Código segue os padrões do projeto+- [ ] Código foi formatado (`make fmt`)+- [ ] Lint passou sem erros (`make lint`)+- [ ] Documentação foi atualizada (se necessário)+- [ ] Swagger foi atualizado (`make swagger`) se alterou endpoints+- [ ] Commit messages são descritivas++### Padrão de Commit++Use [Conventional Commits](https://www.conventionalcommits.org/):++```bash+# Feature+git commit -m "feat: adiciona suporte para envio de áudio"++# Bug fix+git commit -m "fix: corrige erro ao deletar instância"++# Documentação+git commit -m "docs: atualiza guia de instalação"++# Refatoração+git commit -m "refactor: simplifica lógica de conexão"++# Chore (manutenção)+git commit -m "chore: atualiza dependências"++# Performance+git commit -m "perf: otimiza query de listagem de mensagens"+```++### Mensagens de Commit Detalhadas++```bash+git commit -m "feat: adiciona endpoint de busca de mensagens++- Implementa GET /message/search+- Adiciona filtros por data, remetente e texto+- Inclui paginação (limit/offset)+- Atualiza documentação Swagger++Closes #42"+```++---++## Padrões de Código++### Go Formatting++```bash+# Sempre formate antes de commit+make fmt++# Ou manualmente+go fmt ./...+goimports -w .+```++### Linting++```bash+# Execute lint+make lint++# Corrige automaticamente quando possível+golangci-lint run --fix+```++### Estrutura de Código++Siga o padrão **Handler → Service → Repository**:++```go+// pkg/mymodule/handler.go+package mymodule++type MyHandler struct {+ service MyService+}++func (h *MyHandler) Create(c *gin.Context) {+ // Valida input+ // Chama service+ // Retorna response+}++// pkg/mymodule/service.go+type MyService interface {+ Create(dto CreateDTO) (*Model, error)+}++type myService struct {+ repo MyRepository+}++func (s *myService) Create(dto CreateDTO) (*Model, error) {+ // Lógica de negócio+ // Chama repository+ return model, nil+}++// pkg/mymodule/repository.go+type MyRepository interface {+ Save(model *Model) error+}++type myRepository struct {+ db *gorm.DB+}++func (r *myRepository) Save(model *Model) error {+ return r.db.Create(model).Error+}+```++### Documentação Swagger++Sempre documente endpoints públicos:++```go+// GetInstance retorna uma instância por ID.+//+// @Summary Buscar instância+// @Description Retorna detalhes de uma instância WhatsApp+// @Tags instance+// @Accept json+// @Produce json+// @Param instanceName path string true "Nome da instância"+// @Success 200 {object} Instance+// @Failure 404 {object} ErrorResponse+// @Security ApiKeyAuth+// @Router /instance/{instanceName} [get]+func (h *InstanceHandler) GetInstance(c *gin.Context) {+ // ...+}+```++---++## Processo de Review++### O que os Reviewers Avaliam++- ✅ **Funcionalidade**: O código faz o que deveria?+- ✅ **Qualidade**: Código limpo, legível e manutenível?+- ✅ **Performance**: Há problemas de performance?+- ✅ **Segurança**: Há vulnerabilidades?+- ✅ **Testes**: Há cobertura adequada? (quando testes existirem)+- ✅ **Documentação**: Está atualizada?++### Timeline Esperado++- **Primeira revisão**: 1-3 dias úteis+- **Revisões subsequentes**: 1-2 dias úteis+- **Merge**: Após aprovação de 1+ mantainer++### Respondendo a Feedbacks++- Seja receptivo a sugestões+- Faça perguntas se não entender+- Atualize o código conforme feedback+- Force push (`git push -f`) é OK durante review++### Após o Merge++- Delete sua branch: `git branch -d feature/minha-feature`+- Atualize seu fork: `git pull upstream main`++---++## Recursos Úteis++- **Issues**: https://git.evoai.app/Evolution/evolution-go/issues+- **Pull Requests**: https://git.evoai.app/Evolution/evolution-go/merge_requests+- **Documentação**: https://git.evoai.app/Evolution/evolution-go/-/wikis+- **Go Style Guide**: https://google.github.io/styleguide/go/+- **Effective Go**: https://go.dev/doc/effective_go++---++**Obrigado por contribuir!** 🎉++**Mantido por**: Equipe EvoAI Servicesdiff --git a/docs/wiki/desenvolvimento/debugging.md b/docs/wiki/desenvolvimento/debugging.mdnew file mode 100644index 0000000..80b637d--- /dev/null+++ b/docs/wiki/desenvolvimento/debugging.md@@ -0,0 +1,407 @@+# Debugging e Troubleshooting++Guia para resolver problemas comuns no Evolution GO.++## Índice++- [Logs e Debug Mode](#logs-e-debug-mode)+- [Problemas Comuns](#problemas-comuns)+- [Debugging com IDE](#debugging-com-ide)+- [Profiling de Performance](#profiling-de-performance)+- [Análise de Banco de Dados](#análise-de-banco-de-dados)+- [Network Debugging](#network-debugging)+- [Ferramentas Úteis](#ferramentas-úteis)++---++## Logs e Debug Mode++### Habilitar Debug Mode++```env+# .env+WADEBUG=DEBUG+LOGTYPE=console # ou 'file'+```++### Visualizar Logs++```bash+# Logs em console+make dev++# Logs em arquivo+tail -f logs/evolution-go.log++# Docker+docker-compose logs -f evolution-go++# Filtrar logs de erro+docker-compose logs evolution-go | grep ERROR+```++### Níveis de Log++- **DEBUG**: Detalhes de execução (desenvolvimento)+- **INFO**: Informações gerais (produção)+- **WARN**: Avisos (produção)+- **ERROR**: Erros (sempre)++---++## Problemas Comuns++### 1. Erro: "port 4000 already in use"++**Causa**: Outra aplicação usando a porta 4000.++**Solução**:++```bash+# Verificar processo usando a porta+lsof -i :4000++# Ou+netstat -tuln | grep 4000++# Matar processo+kill -9 <PID>++# Ou alterar porta no .env+SERVER_PORT=4001+```++### 2. Erro: "connection refused" (PostgreSQL)++**Causa**: PostgreSQL não está rodando ou inacessível.++**Solução**:++```bash+# Verificar se PostgreSQL está rodando+sudo systemctl status postgresql++# Ou via Docker+docker ps | grep postgres++# Iniciar PostgreSQL+sudo systemctl start postgresql++# Ou via Docker+docker start postgres++# Testar conexão+psql -h localhost -U postgres -d evogo_auth+```++### 3. Erro: "database does not exist"++**Causa**: Databases `evogo_auth` ou `evogo_users` não criados.++**Solução**:++```bash+# Criar databases+sudo -u postgres psql << EOF+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+EOF++# Ou via Docker+docker exec -i postgres psql -U postgres << EOF+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+EOF+```++### 4. Erro: "invalid API key"++**Causa**: API key incorreta ou não configurada.++**Solução**:++```bash+# Verificar .env+cat .env | grep GLOBAL_API_KEY++# Testar com API key correta+curl -H "apikey: SUA-CHAVE" http://localhost:4000/server/ok+```++### 5. QR Code não Aparece++**Causa**: Instância já conectada ou erro de criação.++**Solução**:++```bash+# Verificar logs+docker-compose logs -f evolution-go | grep QR++# Deletar e recriar instância+curl -X DELETE http://localhost:4000/instance/delete/NOME \+ -H "apikey: SUA-CHAVE"++curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE" \+ -d '{"instanceName": "NOME"}'+```++### 6. Webhook não Funciona++**Causa**: URL inválida ou endpoint indisponível.++**Solução**:++```bash+# Testar webhook manualmente+curl -X POST https://seu-webhook.com/endpoint \+ -H "Content-Type: application/json" \+ -d '{"test": true}'++# Verificar logs+docker-compose logs evolution-go | grep webhook++# Verificar configuração+curl http://localhost:4000/instance/connectionState/NOME \+ -H "apikey: SUA-CHAVE"+```++### 7. Mensagem não Envia++**Causa**: Instância desconectada, número inválido, ou erro de rede.++**Solução**:++```bash+# Verificar conexão+curl http://localhost:4000/instance/connectionState/NOME \+ -H "apikey: SUA-CHAVE"++# Verificar logs+docker-compose logs -f evolution-go++# Verificar formato do número+# Correto: 5511999999999 (DDI + DDD + número)+# Errado: 11999999999, +55 11 99999-9999+```++---++## Debugging com IDE++### VSCode++1. Abrir `Run and Debug` (Ctrl+Shift+D)+2. Selecionar "Launch Evolution GO"+3. Adicionar breakpoints (F9)+4. Iniciar debug (F5)++**launch.json**:++```json+{+ "version": "0.2.0",+ "configurations": [+ {+ "name": "Debug Evolution GO",+ "type": "go",+ "request": "launch",+ "mode": "debug",+ "program": "${workspaceFolder}/cmd/evolution-go",+ "args": ["-dev"],+ "showLog": true+ }+ ]+}+```++### GoLand++1. **Run → Debug 'Evolution GO'**+2. Adicionar breakpoints (Ctrl+F8)+3. Debug com F5++---++## Profiling de Performance++### CPU Profiling++```bash+# Executar com pprof+go run cmd/evolution-go/main.go -dev &+PID=$!++# Gerar CPU profile (30 segundos)+curl http://localhost:4000/debug/pprof/profile?seconds=30 > cpu.prof++# Analisar+go tool pprof cpu.prof++# Comandos no pprof:+# top10 - Top 10 funções+# list <func> - Código da função+# web - Visualização gráfica (requer graphviz)+```++### Memory Profiling++```bash+# Heap snapshot+curl http://localhost:4000/debug/pprof/heap > heap.prof++# Analisar+go tool pprof heap.prof++# Visualizar em browser+go tool pprof -http=:8081 heap.prof+```++### Goroutine Leaks++```bash+# Ver goroutines ativas+curl http://localhost:4000/debug/pprof/goroutine?debug=1++# Profile de goroutines+curl http://localhost:4000/debug/pprof/goroutine > goroutine.prof+go tool pprof goroutine.prof+```++---++## Análise de Banco de Dados++### Queries Lentas++```sql+-- Habilitar log de queries lentas (PostgreSQL)+ALTER DATABASE evogo_users SET log_min_duration_statement = 1000;++-- Ver queries lentas+SELECT query, calls, total_time, mean_time+FROM pg_stat_statements+ORDER BY mean_time DESC+LIMIT 10;+```++### Ver Conexões Ativas++```sql+-- PostgreSQL+SELECT count(*) FROM pg_stat_activity;++SELECT datname, usename, state, query+FROM pg_stat_activity+WHERE datname IN ('evogo_auth', 'evogo_users');+```++### Índices Faltantes++```sql+-- Verificar scans sequenciais (ruim)+SELECT schemaname, tablename, seq_scan, seq_tup_read+FROM pg_stat_user_tables+WHERE seq_scan > 0+ORDER BY seq_tup_read DESC+LIMIT 10;+```++---++## Network Debugging++### Testar Conectividade++```bash+# Testar se porta está aberta+nc -zv localhost 4000++# Testar endpoint+curl -v http://localhost:4000/server/ok++# Com proxy+curl -x http://proxy:8080 http://localhost:4000/server/ok+```++### Capturar Tráfego HTTP++```bash+# tcpdump+sudo tcpdump -i any -A 'port 4000'++# Wireshark+# Filtro: tcp.port == 4000+```++---++## Ferramentas Úteis++### 1. delve (Go Debugger)++```bash+# Instalar+go install github.com/go-delve/delve/cmd/dlv@latest++# Debug+dlv debug cmd/evolution-go/main.go -- -dev++# Comandos:+# break main.main - Breakpoint+# continue - Continuar+# next - Próxima linha+# print var - Imprimir variável+```++### 2. Postman/Insomnia++Importar collection Swagger:+- URL: http://localhost:4000/swagger/doc.json++### 3. pgAdmin / DBeaver++Conectar ao PostgreSQL:+- Host: localhost+- Port: 5432+- Database: evogo_users+- Username: postgres++### 4. Docker Stats++```bash+# Ver uso de recursos+docker stats evolution-go++# Inspecionar container+docker inspect evolution-go+```++---++## Checklist de Troubleshooting++Quando algo não funciona:++1. ✅ Verificar logs: `docker-compose logs -f`+2. ✅ Verificar .env: variáveis corretas?+3. ✅ Verificar PostgreSQL: está rodando?+4. ✅ Verificar porta: 4000 livre?+5. ✅ Verificar API key: está correta?+6. ✅ Testar health check: `/server/ok`+7. ✅ Verificar Swagger: documentação atualizada?+8. ✅ Verificar versão Go: 1.24+?++---++## Recursos Adicionais++- **Go Debugging**: https://go.dev/doc/gdb+- **GORM Debugging**: https://gorm.io/docs/logger.html+- **Gin Debugging**: https://gin-gonic.com/docs/examples/++---++**Mantido por**: Equipe EvoAI Servicesdiff --git a/docs/wiki/desenvolvimento/development-guide.md b/docs/wiki/desenvolvimento/development-guide.mdnew file mode 100644index 0000000..a471264--- /dev/null+++ b/docs/wiki/desenvolvimento/development-guide.md@@ -0,0 +1,773 @@+# Guia de Desenvolvimento++Guia completo para desenvolver e contribuir com o Evolution GO.++## Índice++- [Visão Geral](#visão-geral)+- [Requisitos](#requisitos)+- [Setup Inicial](#setup-inicial)+- [Estrutura do Projeto](#estrutura-do-projeto)+- [Executando Localmente](#executando-localmente)+- [Makefile e Comandos](#makefile-e-comandos)+- [Configuração de IDE](#configuração-de-ide)+- [Convenções de Código](#convenções-de-código)+- [Workflow de Desenvolvimento](#workflow-de-desenvolvimento)+- [Próximos Passos](#próximos-passos)++---++## Visão Geral++O Evolution GO é um **gateway de API WhatsApp** escrito em Go, utilizando:++- **Linguagem**: Go 1.24++- **Framework Web**: Gin+- **ORM**: GORM+- **Banco de Dados**: PostgreSQL / SQLite+- **WhatsApp Library**: whatsmeow+- **Documentação API**: Swagger++---++## Requisitos++### Obrigatórios++- **Go 1.24+** ([Download](https://go.dev/dl/))+- **Git** ([Download](https://git-scm.com/downloads))+- **PostgreSQL 12+** ([Download](https://www.postgresql.org/download/))+ - Ou usar Docker: `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:15-alpine`++### Opcionais++- **Make** (incluído no Linux/Mac, Windows: `choco install make`)+- **Docker** e **Docker Compose** (para desenvolvimento com containers)+- **RabbitMQ** (para testar sistema de eventos)+- **MinIO** (para testar armazenamento de mídia)++### Ferramentas Recomendadas++- **IDE**: VSCode, GoLand, ou Vim/Neovim+- **Postman** ou **Insomnia** (para testar API)+- **PostgreSQL Client**: pgAdmin, DBeaver, ou psql+- **Git GUI**: GitKraken, Sourcetree (opcional)++---++## Setup Inicial++### 1. Clonar o Repositório++```bash+# Via HTTPS+git clone https://git.evoai.app/Evolution/evolution-go.git+cd evolution-go++# Ou via SSH (se configurado)+git clone [email protected]:Evolution/evolution-go.git+cd evolution-go+```++### 2. Instalar Dependências Go++```bash+# Baixar dependências+go mod download++# Ou usando Make+make deps+```++### 3. Configurar PostgreSQL++**Opção A: PostgreSQL Local**++```bash+# Ubuntu/Debian+sudo apt-get install postgresql postgresql-contrib+sudo systemctl start postgresql++# macOS+brew install postgresql@15+brew services start postgresql@15++# Criar databases+sudo -u postgres psql << EOF+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+EOF+```++**Opção B: PostgreSQL via Docker**++```bash+docker run -d \+ --name postgres \+ -p 5432:5432 \+ -e POSTGRES_PASSWORD=postgres \+ -v postgres_data:/var/lib/postgresql/data \+ postgres:15-alpine++# Criar databases+docker exec -i postgres psql -U postgres << EOF+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+EOF+```++### 4. Configurar Variáveis de Ambiente++```bash+# Copiar arquivo de exemplo+cp .env.example .env++# Editar configurações+nano .env+```++**Configuração mínima (.env)**:++```env+# Servidor+SERVER_PORT=4000+CLIENT_NAME=evolution-dev++# API Key (gere uma segura)+GLOBAL_API_KEY=dev-key-12345++# PostgreSQL+POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable+DATABASE_SAVE_MESSAGES=false++# Logs+WADEBUG=DEBUG+LOGTYPE=console++# Configurações de desenvolvimento+CONNECT_ON_STARTUP=false+WEBHOOKFILES=true+OS_NAME=Linux+```++### 5. Verificar Instalação++```bash+# Verificar versão do Go+go version+# Deve mostrar: go version go1.24.x ...++# Verificar dependências+go mod verify++# Compilar (teste)+go build ./cmd/evolution-go+```++---++## Estrutura do Projeto++```+evolution-go/+├── cmd/+│ └── evolution-go/+│ └── main.go # Entry point da aplicação+│+├── pkg/ # Pacotes principais+│ ├── config/ # Configuração e env vars+│ │ ├── config.go+│ │ └── env.go+│ │+│ ├── instance/ # Gerenciamento de instâncias+│ │ ├── handler.go # HTTP handlers+│ │ ├── service.go # Lógica de negócio+│ │ ├── repository.go # Acesso ao banco+│ │ └── model/+│ │ └── instance_model.go+│ │+│ ├── whatsmeow/ # Cliente WhatsApp+│ │ ├── whatsmeow.go+│ │ └── events.go+│ │+│ ├── message/ # Mensagens+│ │ ├── handler.go+│ │ ├── service.go+│ │ ├── repository.go+│ │ └── model/+│ │+│ ├── sendMessage/ # Envio de mensagens+│ │ ├── handler.go+│ │ └── service.go+│ │+│ ├── events/ # Produtores de eventos+│ │ ├── webhook/+│ │ ├── rabbitmq/+│ │ ├── nats/+│ │ └── websocket/+│ │+│ ├── storage/ # Armazenamento de mídia+│ │ ├── media_storage.go+│ │ └── minio/+│ │+│ └── utils/ # Utilitários+│ ├── logger/+│ └── validator/+│+├── docs/ # Documentação Swagger+│ ├── docs.go+│ ├── swagger.json+│ └── swagger.yaml+│+├── docker/ # Configurações Docker+│ └── examples/+│ ├── docker-compose.yml+│ ├── docker-compose.swarm.yml+│ └── .env.example+│+├── Dockerfile # Imagem Docker+├── Makefile # Comandos de automação+├── go.mod # Dependências Go+├── go.sum # Checksums de dependências+├── .env.example # Exemplo de variáveis de ambiente+└── README.md # Documentação principal+```++### Arquitetura em Camadas++Cada módulo segue o padrão **Handler → Service → Repository**:++```+┌─────────────┐+│ Handler │ ← Recebe requests HTTP (Gin)+└──────┬──────┘+ │+ ▼+┌─────────────┐+│ Service │ ← Lógica de negócio+└──────┬──────┘+ │+ ▼+┌─────────────┐+│ Repository │ ← Acesso ao banco (GORM)+└─────────────┘+```++---++## Executando Localmente++### Modo Desenvolvimento (Hot Reload)++```bash+# Executar em modo dev+make dev++# Ou diretamente+go run cmd/evolution-go/main.go -dev+```++**Saída esperada**:++```+[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.+[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.+[GIN-debug] GET /swagger/*any --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers)+[GIN-debug] GET /server/ok --> main.main.func1 (3 handlers)+[GIN-debug] POST /instance/create --> evolution-go/pkg/instance.(*InstanceHandler).Create-fm (4 handlers)+...+[GIN-debug] Listening and serving HTTP on :4000+```++### Build e Executar++```bash+# Build local+make build-local++# Executar binário+./build/evolution-go+```++### Com Docker Compose++```bash+# Copiar exemplo+cp docker/examples/docker-compose.yml ./++# Editar GLOBAL_API_KEY+nano docker-compose.yml++# Iniciar+docker-compose up -d++# Ver logs+docker-compose logs -f evolution-go+```++### Acessar a Aplicação++- **API Base**: http://localhost:4000+- **Health Check**: http://localhost:4000/server/ok+- **Swagger UI**: http://localhost:4000/swagger/index.html++---++## Makefile e Comandos++### Comandos de Desenvolvimento++```bash+# Executar em modo dev (hot reload)+make dev++# Build para produção (Linux)+make build++# Build local (seu SO)+make build-local++# Build e executar+make run+```++### Comandos de Qualidade++```bash+# Instalar dependências+make deps++# Atualizar dependências+make deps-update++# Formatar código+make fmt++# Lint (fmt + vet)+make lint++# Verificar tudo (deps + lint)+make check+```++### Comandos de Documentação++```bash+# Gerar documentação Swagger+make swagger++# Requer: go install github.com/swaggo/swag/cmd/swag@latest+```++### Comandos Docker++```bash+# Build imagem Docker+make docker-build++# Executar container+make docker-run++# Executar em modo dev+make docker-run-dev++# Limpar imagens+make docker-clean+```++### Comandos Auxiliares++```bash+# Ver logs+make logs++# Limpar builds+make clean++# Setup completo (deps + tools)+make setup++# Quick start+make quick-start+```++---++## Configuração de IDE++### Visual Studio Code++#### Extensões Recomendadas++```json+{+ "recommendations": [+ "golang.go", // Go support+ "ms-vscode.makefile-tools", // Makefile support+ "humao.rest-client", // REST client+ "42crunch.vscode-openapi", // Swagger/OpenAPI+ "streetsidesoftware.code-spell-checker"+ ]+}+```++Salvar em `.vscode/extensions.json`.++#### Settings++```json+{+ "go.useLanguageServer": true,+ "go.lintTool": "golangci-lint",+ "go.lintOnSave": "package",+ "go.formatTool": "goimports",+ "editor.formatOnSave": true,+ "go.testFlags": ["-v"],+ "go.coverOnSave": false,+ "[go]": {+ "editor.codeActionsOnSave": {+ "source.organizeImports": true+ }+ }+}+```++Salvar em `.vscode/settings.json`.++#### Tasks++```json+{+ "version": "2.0.0",+ "tasks": [+ {+ "label": "Run Dev",+ "type": "shell",+ "command": "make dev",+ "group": {+ "kind": "build",+ "isDefault": true+ }+ },+ {+ "label": "Build",+ "type": "shell",+ "command": "make build-local"+ },+ {+ "label": "Lint",+ "type": "shell",+ "command": "make lint"+ }+ ]+}+```++Salvar em `.vscode/tasks.json`.++#### Launch (Debug)++```json+{+ "version": "0.2.0",+ "configurations": [+ {+ "name": "Launch Evolution GO",+ "type": "go",+ "request": "launch",+ "mode": "debug",+ "program": "${workspaceFolder}/cmd/evolution-go",+ "args": ["-dev"],+ "env": {+ "WADEBUG": "DEBUG"+ },+ "showLog": true+ }+ ]+}+```++Salvar em `.vscode/launch.json`.++### GoLand / IntelliJ IDEA++#### Run Configuration++1. **Run → Edit Configurations**+2. **Add New Configuration → Go Build**+3. Configurar:+ - **Name**: Evolution GO Dev+ - **Run kind**: Directory+ - **Directory**: `cmd/evolution-go`+ - **Program arguments**: `-dev`+ - **Environment**: `WADEBUG=DEBUG`+ - **Working directory**: Raiz do projeto++#### File Watchers (opcional)++1. **Settings → Tools → File Watchers**+2. **Add → go fmt**+3. **Add → goimports**++---++## Convenções de Código++### Estrutura de Pacotes++```go+// Cada módulo deve ter:+package instance++// handler.go - HTTP handlers+type InstanceHandler struct {+ service InstanceService+}++func (h *InstanceHandler) Create(c *gin.Context) { }++// service.go - Lógica de negócio+type InstanceService interface {+ Create(data CreateInstanceDTO) (*Instance, error)+}++// repository.go - Banco de dados+type InstanceRepository interface {+ Save(instance *Instance) error+ FindByID(id string) (*Instance, error)+}++// model/instance_model.go - Structs+type Instance struct {+ Id string+ Name string+}+```++### Nomenclatura++```go+// Variáveis: camelCase+var instanceName string++// Constantes: PascalCase ou UPPER_CASE+const MaxRetries = 5+const DEFAULT_TIMEOUT = 30++// Structs: PascalCase+type InstanceConfig struct { }++// Interfaces: PascalCase + sufixo "er" ou nome descritivo+type InstanceRepository interface { }+type MessageSender interface { }++// Métodos: PascalCase+func (h *Handler) CreateInstance() { }++// Funções privadas: camelCase+func parseConfig() { }++// Funções públicas: PascalCase+func NewInstanceHandler() { }+```++### Comentários++```go+// Comentários de package (em <package>_doc.go ou no arquivo principal)+// Package instance fornece gerenciamento de instâncias WhatsApp.+package instance++// Comentários de funções exportadas (obrigatório para Swagger)+// CreateInstance cria uma nova instância WhatsApp.+//+// @Summary Criar instância+// @Description Cria uma nova instância WhatsApp+// @Tags instance+// @Accept json+// @Produce json+// @Param data body CreateInstanceDTO true "Dados da instância"+// @Success 201 {object} Instance+// @Failure 400 {object} ErrorResponse+// @Router /instance/create [post]+func (h *InstanceHandler) CreateInstance(c *gin.Context) {+ // Implementação...+}++// Comentários inline para lógica complexa+// Gera UUID v4 para identificação única+instanceID := uuid.New().String()+```++### Tratamento de Erros++```go+// Sempre retornar erros, não panic+func CreateInstance(name string) (*Instance, error) {+ if name == "" {+ return nil, fmt.Errorf("name cannot be empty")+ }++ instance := &Instance{Name: name}+ if err := repository.Save(instance); err != nil {+ return nil, fmt.Errorf("failed to save instance: %w", err)+ }++ return instance, nil+}++// Em handlers HTTP+func (h *Handler) Create(c *gin.Context) {+ var dto CreateDTO+ if err := c.ShouldBindJSON(&dto); err != nil {+ c.JSON(400, gin.H{"error": err.Error()})+ return+ }++ instance, err := h.service.Create(dto)+ if err != nil {+ logger.LogError("Failed to create instance: %v", err)+ c.JSON(500, gin.H{"error": "Internal server error"})+ return+ }++ c.JSON(201, instance)+}+```++### Logging++```go+import "evolution-go/pkg/utils/logger"++// Níveis de log+logger.LogInfo("Instance %s created successfully", instanceName)+logger.LogWarn("Webhook URL not configured for instance %s", instanceName)+logger.LogError("Failed to connect to database: %v", err)+logger.LogDebug("Processing message: %+v", message)+```++---++## Workflow de Desenvolvimento++### 1. Criar Branch++```bash+# Atualizar main+git checkout main+git pull origin main++# Criar feature branch+git checkout -b feature/nome-da-feature++# Ou bugfix+git checkout -b fix/nome-do-bug+```++### 2. Desenvolver++```bash+# Executar em modo dev+make dev++# Em outro terminal, fazer mudanças no código+# O servidor reinicia automaticamente com hot-reload+```++### 3. Testar Manualmente++```bash+# Testar health check+curl http://localhost:4000/server/ok++# Criar instância+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: dev-key-12345" \+ -d '{"instanceName": "teste"}'++# Verificar Swagger+open http://localhost:4000/swagger/index.html+```++### 4. Formatar e Lint++```bash+# Formatar código+make fmt++# Lint+make lint+```++### 5. Atualizar Swagger (se alterou endpoints)++```bash+# Gerar documentação+make swagger++# Verificar se docs/ foi atualizado+git status+```++### 6. Commit++```bash+# Add mudanças+git add .++# Commit com mensagem descritiva+git commit -m "feat: adiciona endpoint de listagem de instâncias++- Implementa GET /instance/list+- Adiciona paginação+- Atualiza documentação Swagger"++# Padrões de commit:+# feat: nova feature+# fix: correção de bug+# docs: documentação+# refactor: refatoração+# chore: tarefas de manutenção+```++### 7. Push e Pull Request++```bash+# Push para origin+git push origin feature/nome-da-feature++# Criar PR no GitLab/GitHub+# Preencher descrição detalhada+# Aguardar code review+```++---++## Próximos Passos++Após setup completo:++1. **[Como Contribuir](./contributing.md)** - Processo de contribuição e PR+2. **[Debugging](./debugging.md)** - Troubleshooting e resolução de problemas+3. **[Arquitetura](../conceitos-core/architecture.md)** - Entenda a arquitetura+4. **[API Overview](../guias-api/api-overview.md)** - Comece a desenvolver na API++---++## Recursos Adicionais++- **Documentação Go**: https://go.dev/doc/+- **GORM**: https://gorm.io/docs/+- **Gin Framework**: https://gin-gonic.com/docs/+- **Whatsmeow**: https://github.com/tulir/whatsmeow+- **Swagger**: https://swagger.io/docs/++---++**Dica**: Use `make help` para ver todos os comandos disponíveis!++**Mantido por**: Equipe EvoAI Services+**Versão**: 1.0.0diff --git a/docs/wiki/fundamentos/configuration.md b/docs/wiki/fundamentos/configuration.mdnew file mode 100644index 0000000..35460c0--- /dev/null+++ b/docs/wiki/fundamentos/configuration.md@@ -0,0 +1,558 @@+# Configuração++Referência completa de variáveis de ambiente do Evolution GO.++Para exemplos práticos, consulte: `docker/examples/.env.example`++## Configuração via Ambiente++As configurações podem ser definidas através de:+- **Variáveis de ambiente** (Docker, Kubernetes)+- **Arquivo `.env`** (instalação local)++---++## Variáveis Obrigatórias++### GLOBAL_API_KEY++Chave de autenticação para acesso à API.++- **Tipo**: String (UUID recomendado)+- **Obrigatório**: Sim++```env+GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db+```++**Geração:**+```bash+# UUID v4+uuidgen++# Ou via Python+python3 -c "import uuid; print(uuid.uuid4())"+```++### DATABASE_SAVE_MESSAGES++Habilita persistência de mensagens no banco de dados.++- **Tipo**: Boolean+- **Obrigatório**: Sim+- **Padrão**: `false`++```env+DATABASE_SAVE_MESSAGES=false+```++**Nota**: `true` aumenta significativamente o uso de storage. Recomendado apenas quando necessário manter histórico completo.++---++## Servidor++### SERVER_PORT++Porta HTTP do servidor API.++- **Tipo**: Integer+- **Padrão**: `4000`++```env+SERVER_PORT=4000+```++### CLIENT_NAME++Identificador do cliente/instalação.++- **Tipo**: String++```env+CLIENT_NAME=evolution-production+```++### OS_NAME++Sistema operacional do ambiente.++- **Tipo**: String+- **Valores**: `Linux`, `Windows`, `macOS`++```env+OS_NAME=Linux+```++---++## Banco de Dados PostgreSQL++### POSTGRES_AUTH_DB++String de conexão para banco de autenticação.++- **Formato**: `postgresql://user:pass@host:port/database?sslmode=disable`++```env+POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable+```++### POSTGRES_USERS_DB++String de conexão para banco de dados de usuários.++```env+POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable+```++**Componentes da URL:**+- `postgres` - usuário+- `senha` - password (substituir)+- `postgres` - hostname (ou `localhost`)+- `5432` - porta+- `evogo_auth` / `evogo_users` - database name++---++## Logs e Debug++### WADEBUG++Nível de logging do WhatsApp.++- **Valores**: `ERROR`, `INFO`, `DEBUG`+- **Padrão**: `INFO`++```env+WADEBUG=INFO+```++- `ERROR` - Apenas erros críticos+- `INFO` - Informações importantes+- `DEBUG` - Detalhamento completo (uso em desenvolvimento)++### LOGTYPE++Destino de saída dos logs.++- **Valores**: `console`, `file`+- **Padrão**: `console`++```env+LOGTYPE=console+```++### LOG_DIRECTORY++Diretório para arquivos de log (quando `LOGTYPE=file`).++- **Padrão**: `./logs`++```env+LOG_DIRECTORY=/app/logs+```++### LOG_MAX_SIZE++Tamanho máximo de cada arquivo de log em MB.++- **Padrão**: `100`++```env+LOG_MAX_SIZE=100+```++### LOG_MAX_BACKUPS++Número de arquivos de log rotacionados a manter.++- **Padrão**: `5`++```env+LOG_MAX_BACKUPS=5+```++### LOG_MAX_AGE++Dias de retenção de arquivos de log.++- **Padrão**: `30`++```env+LOG_MAX_AGE=30+```++### LOG_COMPRESS++Compressão de logs rotacionados.++- **Tipo**: Boolean+- **Padrão**: `true`++```env+LOG_COMPRESS=true+```++---++## Conexão e Comportamento++### CONNECT_ON_STARTUP++Conecta automaticamente todas as instâncias ao iniciar o servidor.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+CONNECT_ON_STARTUP=false+```++**Recomendação**: `false` para maior controle sobre o ciclo de vida das instâncias.++### WEBHOOKFILES++Envia URLs de mídia nos payloads de webhook.++- **Tipo**: Boolean+- **Padrão**: `true`++```env+WEBHOOKFILES=true+```++### QRCODE_MAX_COUNT++Número máximo de tentativas de geração de QR Code antes de exigir reconexão manual.++- **Tipo**: Integer+- **Padrão**: `5`++```env+QRCODE_MAX_COUNT=5+```++### CHECK_USER_EXISTS++Valida existência do destinatário no WhatsApp antes de enviar mensagem.++- **Tipo**: Boolean+- **Padrão**: `true`++```env+CHECK_USER_EXISTS=true+```++**Nota**: `false` pode resultar em erros de envio para números inválidos.++### EVENT_IGNORE_GROUP++Ignora eventos originados de grupos.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+EVENT_IGNORE_GROUP=false+```++### EVENT_IGNORE_STATUS++Ignora eventos de status/stories.++- **Tipo**: Boolean+- **Padrão**: `true`++```env+EVENT_IGNORE_STATUS=true+```++---++## Webhooks++### WEBHOOK_URL++URL de destino para callbacks HTTP de eventos.++```env+WEBHOOK_URL=https://api.seudominio.com/webhook+```++Eventos serão enviados via POST com payload JSON:++```json+{+ "event": "messages.upsert",+ "instanceName": "nome-instancia",+ "data": { ... }+}+```++---++## RabbitMQ (AMQP)++Sistema de filas para processamento assíncrono de eventos.++### AMQP_URL++URL de conexão RabbitMQ.++- **Formato**: `amqp://user:pass@host:port/vhost`++```env+AMQP_URL=amqp://admin:admin@rabbitmq:5672/default+```++### AMQP_GLOBAL_ENABLED++Habilita publicação global de eventos via RabbitMQ.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+AMQP_GLOBAL_ENABLED=true+```++### AMQP_GLOBAL_EVENTS++Lista de eventos a serem publicados (separados por vírgula).++```env+AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update+```++**Eventos disponíveis:**+- `messages.upsert` - Nova mensagem recebida+- `messages.update` - Atualização de mensagem (leitura, entrega)+- `connection.update` - Mudança de status de conexão+- Entre outros++---++## NATS++Sistema de mensageria para eventos distribuídos.++### NATS_URL++URL do servidor NATS.++```env+NATS_URL=nats://localhost:4222+```++### NATS_GLOBAL_ENABLED++Habilita publicação de eventos via NATS.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+NATS_GLOBAL_ENABLED=true+```++---++## MinIO/S3++Armazenamento de objetos para mídia.++### MINIO_ENABLED++Habilita integração com MinIO/S3.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+MINIO_ENABLED=true+```++### MINIO_ENDPOINT++Endpoint do servidor de objetos.++```env+# MinIO local+MINIO_ENDPOINT=localhost:9000++# AWS S3+MINIO_ENDPOINT=s3.amazonaws.com+```++### MINIO_ACCESS_KEY++Access Key para autenticação.++```env+MINIO_ACCESS_KEY=minioadmin+```++### MINIO_SECRET_KEY++Secret Key para autenticação.++```env+MINIO_SECRET_KEY=minioadmin+```++### MINIO_BUCKET++Nome do bucket para armazenamento de mídia.++```env+MINIO_BUCKET=evolution-media+```++**Nota**: O bucket deve existir antes de habilitar a integração.++### MINIO_USE_SSL++Utiliza HTTPS para conexões ao S3/MinIO.++- **Tipo**: Boolean+- **Padrão**: `false`++```env+MINIO_USE_SSL=true+```++### MINIO_REGION++Região do bucket S3 (AWS).++- **Padrão**: `us-east-1`++```env+MINIO_REGION=us-east-1+```++---++## Proxy++Configuração de proxy HTTP para instâncias WhatsApp.++### PROXY_HOST++Hostname do servidor proxy.++```env+PROXY_HOST=proxy.empresa.com+```++### PROXY_PORT++Porta do proxy.++```env+PROXY_PORT=8080+```++### PROXY_USERNAME++Usuário para autenticação (se requerido).++```env+PROXY_USERNAME=usuario+```++### PROXY_PASSWORD++Senha para autenticação (se requerido).++```env+PROXY_PASSWORD=senha+```++---++## Recursos Adicionais++### API_AUDIO_CONVERTER++URL de serviço externo para conversão de áudio.++```env+API_AUDIO_CONVERTER=https://converter.seudominio.com+```++### API_AUDIO_CONVERTER_KEY++Chave de autenticação do serviço de conversão.++```env+API_AUDIO_CONVERTER_KEY=chave-do-servico+```++---++## Versão WhatsApp (Avançado)++**⚠️ Atenção**: Modificar a versão do WhatsApp pode resultar em bloqueio de conta. Use apenas quando estritamente necessário.++### WHATSAPP_VERSION_MAJOR++```env+WHATSAPP_VERSION_MAJOR=2+```++### WHATSAPP_VERSION_MINOR++```env+WHATSAPP_VERSION_MINOR=2412+```++### WHATSAPP_VERSION_PATCH++```env+WHATSAPP_VERSION_PATCH=54+```++**Recomendação**: Deixar não configurado para utilizar versão automática da biblioteca whatsmeow.++---++## Exemplo de Configuração Mínima++```env+# Obrigatórias+GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db+DATABASE_SAVE_MESSAGES=false++# Servidor+SERVER_PORT=4000+CLIENT_NAME=evolution+OS_NAME=Linux++# Banco de Dados+POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable++# Logs+WADEBUG=INFO+LOGTYPE=console++# Comportamento+CONNECT_ON_STARTUP=false+WEBHOOKFILES=true+CHECK_USER_EXISTS=true+EVENT_IGNORE_STATUS=true+```++---++## Referências++- **[Instalação](./installation.md)** - Guia de instalação+- **[Início Rápido](./quickstart.md)** - Primeiro uso+- **[.env.example](../../../docker/examples/.env.example)** - Exemplo completo com todas variáveis++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/fundamentos/installation.md b/docs/wiki/fundamentos/installation.mdnew file mode 100644index 0000000..ec05c03--- /dev/null+++ b/docs/wiki/fundamentos/installation.md@@ -0,0 +1,491 @@+# Guia de Instalação++Métodos de instalação do Evolution GO para diferentes ambientes.++## Índice++- [Requisitos](#requisitos)+- [Instalação com Docker (Recomendado)](#instalação-com-docker-recomendado)+- [Instalação Local](#instalação-local)+- [Instalação com Docker Swarm](#instalação-com-docker-swarm)+- [Stack Completa](#stack-completa)+- [Verificação](#verificação)+- [Solução de Problemas](#solução-de-problemas)++---++## Requisitos++### Docker (Recomendado)++- Docker 20.10++- Docker Compose 2.0++- PostgreSQL 12+ (containerizado)+- Mínimo 1GB RAM+- Mínimo 2GB disco++### Instalação Local++- Go 1.24++- PostgreSQL 12++- Git+- Mínimo 1GB RAM+- Mínimo 2GB disco++### Opcionais++- RabbitMQ - Sistema de filas+- NATS - Mensageria distribuída+- MinIO - Storage S3-compatible++---++## Instalação com Docker (Recomendado)++Método mais simples e adequado para produção.++### 1. Obter Arquivos++**Opção A: Clonar repositório**++```bash+git clone https://git.evoai.app/Evolution/evolution-go.git+cd evolution-go+```++**Opção B: Download direto**++```bash+mkdir evolution-go-deploy && cd evolution-go-deploy++curl -o docker-compose.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.yml+curl -o init-db.sql https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/init-db.sql+```++### 2. Configurar API Key++Gere uma chave segura:++```bash+# Linux/Mac+uuidgen++# Python+python3 -c "import uuid; print(uuid.uuid4())"++# Resultado exemplo: df16caad-d0d2-41b2-bec5-75b90048a0db+```++Edite `docker-compose.yml`:++```bash+nano docker-compose.yml+```++Localize e substitua:+```yaml+GLOBAL_API_KEY: "SUA-CHAVE-API-SEGURA-AQUI"+```++Por:+```yaml+GLOBAL_API_KEY: "df16caad-d0d2-41b2-bec5-75b90048a0db"+```++### 3. Iniciar Serviços++```bash+docker-compose up -d+```++Aguarde ~30 segundos para inicialização completa.++### 4. Verificar Logs++```bash+# Evolution GO+docker-compose logs -f evolution-go++# PostgreSQL+docker-compose logs -f postgres+```++### 5. Acessar Aplicação++- **API**: http://localhost:4000+- **Swagger**: http://localhost:4000/swagger/index.html+- **Health Check**: http://localhost:4000/server/ok++---++## Instalação Local++Para ambientes de desenvolvimento.++### 1. Instalar PostgreSQL++**Ubuntu/Debian:**+```bash+sudo apt-get update+sudo apt-get install postgresql postgresql-contrib+```++**macOS:**+```bash+brew install postgresql@15+brew services start postgresql@15+```++**Windows:**+Download: https://www.postgresql.org/download/windows/++### 2. Configurar Banco de Dados++```bash+sudo -u postgres psql+```++```sql+CREATE DATABASE evogo_auth;+CREATE DATABASE evogo_users;+\q+```++### 3. Instalar Go++Download: https://go.dev/dl/++Verificar:+```bash+go version+```++### 4. Clonar Repositório++```bash+git clone https://git.evoai.app/Evolution/evolution-go.git+cd evolution-go+```++### 5. Instalar Dependências++```bash+go mod download+```++Ou:+```bash+make deps+```++### 6. Configurar Ambiente++```bash+cp .env.example .env+nano .env+```++Configuração mínima:++```env+SERVER_PORT=4000+GLOBAL_API_KEY=sua-chave-gerada++POSTGRES_AUTH_DB=postgresql://postgres:postgres@localhost:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:postgres@localhost:5432/evogo_users?sslmode=disable+DATABASE_SAVE_MESSAGES=false++WADEBUG=DEBUG+LOGTYPE=console+CONNECT_ON_STARTUP=false+WEBHOOKFILES=true+OS_NAME=Linux+```++### 7. Executar++**Modo desenvolvimento:**+```bash+make dev+```++Ou:+```bash+go run cmd/evolution-go/main.go -dev+```++**Build produção:**+```bash+make build-local+./build/evolution-go+```++---++## Instalação com Docker Swarm++Para ambientes com alta disponibilidade.++### 1. Inicializar Swarm++```bash+docker swarm init+```++### 2. Criar Recursos++```bash+docker volume create evolution_go_data+docker volume create evolution_go_logs+docker network create --driver overlay network_public+```++### 3. Configurar Stack++```bash+cp docker/examples/docker-compose.swarm.yml ./docker-compose.swarm.yml+nano docker-compose.swarm.yml+```++Configure:+- `GLOBAL_API_KEY`+- `POSTGRES_AUTH_DB`+- `POSTGRES_USERS_DB`+- Labels Traefik (se aplicável)++### 4. Deploy++```bash+docker stack deploy -c docker-compose.swarm.yml evolution+```++### 5. Verificar++```bash+docker service ls+docker service logs evolution_evolution_go -f+```++---++## Stack Completa++Incluindo RabbitMQ, MinIO e NATS.++```bash+curl -o docker-compose-full.yml https://raw.githubusercontent.com/EvolutionAPI/evolution-go/main/docker/examples/docker-compose.full.yml++nano docker-compose-full.yml # Configurar API Key++docker-compose -f docker-compose-full.yml up -d+```++**Serviços incluídos:**++| Serviço | Porta | Função |+|---------|-------|--------|+| Evolution GO | 4000 | API principal |+| PostgreSQL | 5432 | Banco de dados |+| RabbitMQ | 5672, 15672 | Filas de mensagens |+| MinIO | 9000, 9001 | Storage de objetos |+| NATS | 4222 | Mensageria (opcional) |++**Acessos:**++- Evolution GO: http://localhost:4000+- Swagger: http://localhost:4000/swagger/index.html+- RabbitMQ: http://localhost:15672 (admin/admin)+- MinIO: http://localhost:9001 (minioadmin/minioadmin)++**Configuração MinIO (primeira vez):**++1. Acesse http://localhost:9001+2. Login: minioadmin / minioadmin+3. Create bucket: `evolution-media`+4. Configurar política de acesso++---++## Verificação++### Health Check++```bash+curl http://localhost:4000/server/ok+```++Resposta esperada:+```json+{+ "status": "ok"+}+```++### Swagger UI++Acesse: http://localhost:4000/swagger/index.html++### Criar Instância de Teste++```bash+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: sua-chave-api-global" \+ -d '{+ "name": "teste",+ "token": "token-unico-para-esta-instancia"+ }'+```++> **Nota:** Use a `GLOBAL_API_KEY` no header e forneça `name` + `token` no body.++### Verificar Logs++**Docker:**+```bash+docker-compose logs -f evolution-go+```++**Local:**+```bash+tail -f logs/evolution-go.log+```++---++## Solução de Problemas++### Connection Refused (PostgreSQL)++**Diagnóstico:**+```bash+docker-compose ps postgres+# Ou local:+sudo systemctl status postgresql+```++**Verificar databases:**+```bash+docker-compose exec postgres psql -U postgres -c "\l"+```++### Porta em Uso++Alterar porta no `docker-compose.yml`:+```yaml+ports:+ - "4001:4000"+```++Acesso via: http://localhost:4001++### Container Reiniciando++**Ver logs:**+```bash+docker-compose logs evolution-go+```++**Causas comuns:**+- `GLOBAL_API_KEY` não definida+- PostgreSQL não acessível+- Credenciais incorretas++### Permissões de Volume++```bash+mkdir -p logs dbdata+chmod 777 logs dbdata+```++Ou usar bind mounts:+```yaml+volumes:+ - ./logs:/app/logs+ - ./dbdata:/app/dbdata+```++### MinIO Bucket Não Existe++1. Acessar console: http://localhost:9001+2. Login: minioadmin / minioadmin+3. Criar bucket: `evolution-media`++Ou via CLI:+```bash+docker-compose exec minio mc mb /data/evolution-media+```++---++## Comandos Úteis++### Docker Compose++```bash+# Iniciar+docker-compose up -d++# Parar+docker-compose stop++# Reiniciar+docker-compose restart++# Status+docker-compose ps++# Logs+docker-compose logs -f++# Remover+docker-compose down++# Atualizar+docker-compose pull+docker-compose up -d+```++### Docker Swarm++```bash+# Listar serviços+docker service ls++# Logs+docker service logs evolution_evolution_go -f++# Escalar+docker service scale evolution_evolution_go=3++# Atualizar+docker service update --image evoapicloud/evolution-go:latest evolution_evolution_go++# Remover+docker stack rm evolution+```++---++## Próximos Passos++- **[Configuração](./configuration.md)** - Variáveis de ambiente+- **[Início Rápido](./quickstart.md)** - Primeira instância+- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API+- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy avançado++---++## Arquivos de Exemplo++Disponíveis em `docker/examples/`:++- [docker-compose.yml](../../../docker/examples/docker-compose.yml)+- [docker-compose.swarm.yml](../../../docker/examples/docker-compose.swarm.yml)+- [docker-compose.full.yml](../../../docker/examples/docker-compose.full.yml)+- [init-db.sql](../../../docker/examples/init-db.sql)+- [.env.example](../../../docker/examples/.env.example)++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/fundamentos/introduction.md b/docs/wiki/fundamentos/introduction.mdnew file mode 100644index 0000000..05138df--- /dev/null+++ b/docs/wiki/fundamentos/introduction.md@@ -0,0 +1,242 @@+# Introdução ao Evolution GO++## Visão Geral++Evolution GO é um gateway de API WhatsApp construído em Go que fornece uma interface RESTful para integração com o protocolo WhatsApp Web. Funciona como camada de abstração entre aplicações e o WhatsApp, permitindo automação de mensagens, gerenciamento de múltiplas instâncias e integração através de APIs padronizadas.++O projeto utiliza a biblioteca [whatsmeow](https://github.com/tulir/whatsmeow), uma implementação Go do protocolo WhatsApp Web Multi-Device, e adiciona sobre ela recursos empresariais como APIs REST, sistema de eventos, persistência de dados e gerenciamento multi-instância.++## O que o Evolution GO oferece++### Comunicação via API REST++Envie e receba mensagens do WhatsApp através de requisições HTTP padrão:+- Mensagens de texto com formatação+- Mídia (imagens, vídeos, áudios, documentos)+- Localização, contatos e stickers+- Mensagens interativas (botões, listas, enquetes)+- Grupos e comunidades++### Gerenciamento Multi-Instância++- Conecte múltiplas contas WhatsApp simultaneamente+- Cada instância opera de forma independente+- Gerenciamento de ciclo de vida completo+- Configuração de proxy por instância+- Logs isolados por instância++### Sistema de Eventos++Receba notificações em tempo real através de:+- **Webhooks** - Callbacks HTTP para serviços externos+- **RabbitMQ** - Filas de mensagens para processamento assíncrono+- **NATS** - Mensageria leve para eventos distribuídos+- **WebSocket** - Conexões em tempo real++### Armazenamento Empresarial++- **Dual Database** - Separação entre dados de autenticação e usuários+- **PostgreSQL** - Banco principal para produção+- **SQLite** - Alternativa para desenvolvimento+- **MinIO/S3** - Armazenamento de mídia escalável+- Pool de conexões otimizado++## Arquitetura++O Evolution GO segue arquitetura em camadas:++```+┌─────────────────────────────────────────┐+│ Camada Handler (HTTP) │+│ Validação e Roteamento de Requests │+├─────────────────────────────────────────┤+│ Camada Service │+│ Lógica de Negócio e Regras │+├─────────────────────────────────────────┤+│ Camada Repository │+│ Persistência e Acesso a Dados │+└─────────────────────────────────────────┘+```++### Componentes Principais++- **Instance Manager** - Gerencia ciclo de vida das sessões WhatsApp+- **Whatsmeow Service** - Wrapper sobre a biblioteca whatsmeow+- **Message Service** - Processamento e entrega de mensagens+- **Event System** - Propagação multi-canal de eventos+- **Storage Service** - Gerenciamento de mídia+- **User Service** - Perfis, contatos e configurações+- **Group Service** - Administração de grupos+- **Community Service** - Gerenciamento de comunidades++### Biblioteca Whatsmeow++A [whatsmeow](https://github.com/tulir/whatsmeow) implementa o protocolo WhatsApp Web Multi-Device:+- Comunicação direta com servidores WhatsApp+- Criptografia end-to-end+- Suporte a multi-dispositivos+- Sincronização de mensagens+- Gerenciamento de sessões++O Evolution GO utiliza a whatsmeow como base e adiciona camada empresarial com APIs REST, gerenciamento de múltiplas instâncias, sistema de eventos e persistência.++## Casos de Uso++**Automação de Atendimento**+- Chatbots com respostas automáticas+- Integração com sistemas de tickets+- Roteamento inteligente de conversas++**Notificações Transacionais**+- Confirmações de pedidos+- Alertas de pagamento+- Atualizações de status+- Lembretes automáticos++**Marketing e Campanhas**+- Envio de mensagens em massa+- Segmentação de públicos+- Tracking de engajamento++**Integração com CRM**+- Canal WhatsApp no CRM+- Histórico unificado+- Automação de fluxos++**Comunicação Corporativa**+- Notificações internas+- Alertas de sistemas+- Integração com ERPs++## Stack Tecnológico++- **Linguagem**: Go 1.24++- **Framework Web**: Gin+- **Protocolo WhatsApp**: whatsmeow+- **ORM**: GORM+- **Banco de Dados**: PostgreSQL / SQLite+- **Filas**: RabbitMQ (AMQP), NATS+- **Storage**: MinIO (S3-compatible)+- **Documentação**: Swagger/OpenAPI+- **Containers**: Docker multi-stage builds++## Endpoints Disponíveis++### Instâncias+- Criar, conectar e gerenciar instâncias+- QR Code para autenticação+- Status e informações de conexão+- Configuração de proxy++### Mensagens+- Envio de texto, mídia, localização+- Botões, listas e enquetes+- Reações e respostas+- Histórico de conversas++### Usuários+- Gerenciamento de perfil+- Contatos e privacidade+- Bloqueios e configurações++### Grupos+- Criação e administração+- Gerenciamento de participantes+- Configurações e permissões++### Chats+- Pin, mute, archive+- Marcação de leitura+- Busca e filtros++### Outros+- Labels (etiquetas)+- Chamadas+- Comunidades+- Newsletters/Canais++## Segurança e Privacidade++- Criptografia end-to-end mantida (protocolo WhatsApp)+- Autenticação via API Key+- Suporte a HTTPS+- Logs de auditoria+- Secrets management+- Isolamento de instâncias++## Telemetria++O sistema coleta métricas anônimas para melhorias:+- Rotas mais utilizadas+- Versão da API em uso+- Estatísticas de performance++**Não são coletados**: mensagens, números de telefone, nomes ou dados pessoais.++## Primeiros Passos++### Requisitos++- Go 1.24+ (instalação local) ou Docker 20.10++- PostgreSQL 12+ ou SQLite+- Chave de API para autenticação++### Instalação Rápida++```bash+# Clonar repositório+git clone https://git.evoai.app/Evolution/evolution-go.git+cd evolution-go++# Configurar ambiente+cp .env.example .env++# Executar com Docker+docker-compose up -d++# Ou executar localmente+make dev+```++O servidor estará disponível em `http://localhost:4000` com documentação Swagger em `/swagger/index.html`.++## Diferencial++| Aspecto | Evolution GO | WhatsApp Business API |+|---------|--------------|----------------------|+| Licença | Apache 2.0 | Proprietária |+| Custo | Gratuito | Pago por mensagem |+| Aprovação | Não requer | Requer aprovação Meta |+| Setup | Minutos | Semanas/meses |+| Multi-instância | Ilimitado | Limitado por contrato |+| Flexibilidade | Total | Limitada por políticas |+| Recursos | Completo | Subconjunto aprovado |++## Documentação++- **[Instalação](./installation.md)** - Guia completo de instalação+- **[Configuração](./configuration.md)** - Variáveis de ambiente+- **[Início Rápido](./quickstart.md)** - Primeiro uso prático+- **[API Overview](../guias-api/api-overview.md)** - Estrutura da API+- **[Arquitetura](../conceitos-core/architecture.md)** - Design do sistema++## Suporte++- **Grupo WhatsApp**: [evolution-api.com/whatsapp](https://evolution-api.com/whatsapp)+- **Discord**: [evolution-api.com/discord](https://evolution-api.com/discord)+- **GitHub Issues**: [github.com/EvolutionAPI/evolution-go](https://github.com/EvolutionAPI/evolution-go/issues)+- **Documentação**: [doc.evolution-api.com](https://doc.evolution-api.com)++## Licença++Apache License 2.0 com condições adicionais:++1. Logo e informações de copyright não podem ser removidas das interfaces+2. Uso do Evolution GO deve ser notificado/creditado no sistema que o utiliza++Detalhes completos: [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)++---++**Versão**: 1.0.0+**Mantido por**: Equipe Evolution APIdiff --git a/docs/wiki/fundamentos/quickstart.md b/docs/wiki/fundamentos/quickstart.mdnew file mode 100644index 0000000..1950ae3--- /dev/null+++ b/docs/wiki/fundamentos/quickstart.md@@ -0,0 +1,336 @@+# Início Rápido++Tutorial prático para configurar sua primeira instância WhatsApp e enviar mensagens via Evolution GO.++## Pré-requisitos++- Evolution GO instalado e em execução+- Chave de API configurada (GLOBAL_API_KEY)+- Smartphone com WhatsApp ativo++Se ainda não instalou, consulte o [Guia de Instalação](./installation.md).++---++## 1. Verificar API++Confirme que o servidor está respondendo:++```bash+curl http://localhost:4000/server/ok+```++**Resposta esperada:**+```json+{+ "status": "ok"+}+```++---++## 2. Criar Instância++Uma instância representa uma conexão única do WhatsApp. Crie sua primeira:++```bash+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-GLOBAL-API-KEY" \+ -d '{+ "name": "minha-instancia",+ "token": "token-secreto-da-instancia"+ }'+```++> **Importante:**+> - `apikey` header: Use a `GLOBAL_API_KEY` configurada no servidor+> - `token`: Crie um token único para esta instância (será usado para autenticar requisições desta instância)+> - `name`: Nome identificador da instância++**Resposta:**+```json+{+ "message": "success",+ "data": {+ "instanceId": "uuid-gerado",+ "name": "minha-instancia",+ "token": "token-secreto-da-instancia",+ "status": "created"+ }+}+```++A instância foi criada mas ainda não está autenticada no WhatsApp.++---++## 3. Autenticar via QR Code++### Iniciar Conexão++```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia"+```++> **Nota:** Agora use o `token` da instância no header `apikey` (não mais a GLOBAL_API_KEY).++### Obter QR Code++**Via navegador:**+```+http://localhost:4000/instance/qr+```+(com o header `apikey: token-secreto-da-instancia`)++**Via API:**+```bash+curl "http://localhost:4000/instance/qr" \+ -H "apikey: token-secreto-da-instancia"+```++### Escanear no WhatsApp++1. Abra o WhatsApp no smartphone+2. Acesse **Mais opções (⋮)** → **Aparelhos conectados**+3. Toque em **Conectar um aparelho**+4. Escaneie o QR Code exibido++A conexão deve ser estabelecida em aproximadamente 10 segundos.++---++## 4. Verificar Status++Confirme que a instância está conectada:++```bash+curl "http://localhost:4000/instance/status" \+ -H "apikey: token-secreto-da-instancia"+```++**Resposta quando conectado:**+```json+{+ "message": "success",+ "data": {+ "instanceId": "uuid-da-instancia",+ "name": "minha-instancia",+ "status": "open",+ "profilePictureUrl": "https://...",+ "profileName": "Nome do Perfil"+ }+}+```++**Status possíveis:**+- `created` - Instância criada, aguardando autenticação+- `connecting` - Processo de conexão em andamento+- `open` - Conectado e operacional+- `close` - Desconectado++---++## 5. Enviar Mensagem++### Mensagem de Texto++```bash+curl -X POST http://localhost:4000/send/text \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia" \+ -d '{+ "number": "5511999999999",+ "text": "Mensagem de teste via Evolution GO"+ }'+```++> **Nota:** A instância é identificada pelo token no header `apikey`. Não é necessário enviar `instanceName` no body.++**Formato do número:**+- DDI + DDD + Número (apenas dígitos)+- Exemplo Brasil: `5511999999999` (55=Brasil, 11=São Paulo)++**Resposta:**+```json+{+ "message": "success",+ "data": {+ "messageId": "3EB0...",+ "status": "sent"+ }+}+```++### Mensagem com Mídia++```bash+curl -X POST http://localhost:4000/send/media \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia" \+ -d '{+ "number": "5511999999999",+ "mediaUrl": "https://exemplo.com/imagem.jpg",+ "caption": "Legenda da imagem"+ }'+```++### Mensagem com Documento++```bash+curl -X POST http://localhost:4000/send/media \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia" \+ -d '{+ "number": "5511999999999",+ "mediaUrl": "https://exemplo.com/documento.pdf",+ "fileName": "relatorio.pdf"+ }'+```++---++## Operações de Gerenciamento++### Listar Instâncias++```bash+curl "http://localhost:4000/instance/all" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++> **Nota:** Use a `GLOBAL_API_KEY` para listar todas as instâncias.++### Detalhes da Instância++```bash+curl "http://localhost:4000/instance/info/uuid-da-instancia" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++> **Nota:** Use o `instanceId` (UUID) da instância na URL.++### Desconectar++```bash+curl -X POST http://localhost:4000/instance/disconnect \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia"+```++### Reconectar (novo QR Code)++```bash+curl -X POST http://localhost:4000/instance/reconnect \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia"+```++### Deletar++```bash+curl -X DELETE "http://localhost:4000/instance/delete/uuid-da-instancia" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++> **Nota:** Use a `GLOBAL_API_KEY` e o `instanceId` (UUID) para deletar.++---++## Documentação Interativa (Swagger)++Acesse a interface Swagger para explorar e testar todos os endpoints:++```+http://localhost:4000/swagger/index.html+```++**Passos:**+1. Clique em **Authorize** no topo da página+2. Insira sua chave de API+3. Confirme a autenticação+4. Explore e teste os endpoints disponíveis++---++## Resolução de Problemas++### QR Code Expira++QR Code possui validade limitada (~60 segundos). Se expirar:++```bash+curl -X POST http://localhost:4000/instance/reconnect \+ -H "Content-Type: application/json" \+ -H "apikey: token-secreto-da-instancia"+```++### Instância Não Encontrada++Verifique se está usando o token correto:++```bash+# Listar todas as instâncias+curl "http://localhost:4000/instance/all" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++### Mensagem Não Entregue++**Verificações:**++1. **Status da conexão:**+```bash+curl "http://localhost:4000/instance/status" \+ -H "apikey: token-secreto-da-instancia"+```+Status deve ser `open`.++2. **Formato do número:**+ - Apenas dígitos (sem espaços, hífens ou símbolos)+ - Incluir DDI e DDD+ - Validar se o número existe no WhatsApp++3. **Logs do servidor:**+```bash+docker-compose logs -f evolution-go+```++### Erro de Autenticação++Verifique se está enviando o header correto:+```bash+-H "apikey: sua-chave-aqui"+```++Confirme a chave configurada no `docker-compose.yml` ou `.env`.++---++## Próximos Passos++### Documentação da API++- **[API de Mensagens](../guias-api/api-messages.md)** - Todos os tipos de mensagens+- **[API de Grupos](../guias-api/api-groups.md)** - Gerenciamento de grupos+- **[API de Usuários](../guias-api/api-users.md)** - Perfis e contatos+- **[Referência Completa](../guias-api/api-overview.md)** - Todos os endpoints++### Recursos Avançados++- **[Sistema de Eventos](../recursos-avancados/events-system.md)** - Webhooks e filas+- **[Webhooks](../recursos-avancados/webhooks.md)** - Receber notificações+- **[RabbitMQ](../recursos-avancados/rabbitmq.md)** - Processamento assíncrono+- **[MinIO/S3](../recursos-avancados/minio.md)** - Armazenamento de mídia++### Deploy e Segurança++- **[Configuração](./configuration.md)** - Variáveis de ambiente+- **[Docker Deployment](../deploy-producao/docker-deployment.md)** - Deploy em produção+- **[Segurança](../deploy-producao/security.md)** - Boas práticas de segurança++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-call.md b/docs/wiki/guias-api/api-call.mdnew file mode 100644index 0000000..cc4fd97--- /dev/null+++ b/docs/wiki/guias-api/api-call.md@@ -0,0 +1,223 @@+# API de Chamadas++Documentação do endpoint para gerenciar chamadas WhatsApp.++## 📋 Índice++- [Rejeitar Chamada](#rejeitar-chamada)++---++## Rejeitar Chamada++Rejeita uma chamada recebida no WhatsApp.++**Endpoint**: `POST /call/reject`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "callCreator": "[email protected]",+ "callId": "ABC123XYZ"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `callCreator` | string (JID) | ✅ Sim | JID de quem está ligando |+| `callId` | string | ✅ Sim | ID da chamada |++**Nota**: Os dados da chamada (`callCreator` e `callId`) são recebidos via webhook quando uma chamada chega. Você deve capturar esses dados do evento `call` para usar este endpoint.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Resposta de Erro (400)**:+```json+{+ "error": "invalid request body"+}+```++**Resposta de Erro (500)**:+```json+{+ "error": "instance not found"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/call/reject \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "callCreator": "[email protected]",+ "callId": "ABC123XYZ"+ }'+```++---++## Fluxo Completo de Rejeição Automática++### 1. Receber Evento de Chamada via Webhook++Quando alguém liga para sua instância, você recebe um webhook:++```json+{+ "event": "call",+ "instance": "minha-instancia",+ "data": {+ "id": "ABC123XYZ",+ "from": "[email protected]",+ "timestamp": "2025-11-11T10:30:00Z",+ "isVideo": false,+ "isGroup": false+ }+}+```++### 2. Rejeitar Automaticamente++No seu servidor que recebe webhooks, quando chegar um evento de chamada:+1. Capture o `id` e o `from` do evento+2. Faça uma requisição POST para `/call/reject`+3. Use os dados capturados como `callId` e `callCreator`++Dessa forma, chamadas são rejeitadas automaticamente assim que chegam.++### 3. Rejeição Seletiva++Para rejeitar apenas chamadas de números não autorizados:+1. Mantenha uma lista de números permitidos+2. Ao receber evento de chamada, verifique se o número está na lista+3. Se não estiver, rejeite a chamada usando o endpoint `/call/reject`+4. Se estiver autorizado, não faça nada (deixe tocar)++---++## Casos de Uso++### 1. Rejeitar Todas as Chamadas++Útil para contas de atendimento que só respondem via mensagens:+1. Configure seu webhook para receber eventos de chamada+2. Quando receber evento `call`, rejeite imediatamente+3. Envie uma mensagem de texto explicando que não atende chamadas++### 2. Horário Comercial++Rejeitar chamadas fora do horário de trabalho:+1. Ao receber evento de chamada, verifique o horário atual+2. Se estiver fora do horário comercial (ex: Segunda a Sexta, 9h-18h), rejeite+3. Envie mensagem informando o horário de atendimento++### 3. Rejeitar Chamadas de Vídeo++Aceitar apenas chamadas de áudio:+1. Verifique o campo `isVideo` no evento de chamada+2. Se for `true`, rejeite a chamada+3. Envie mensagem pedindo para ligar com chamada de voz++---++## Limitações e Observações++### Limitações do WhatsApp++1. **Não é possível aceitar chamadas via API**: A API do WhatsApp Multi-Device não permite aceitar chamadas programaticamente. Você só pode rejeitá-las.++2. **Chamadas em grupos**: Chamadas em grupos também disparam o evento, mas o campo `isGroup` será `true`.++3. **Timing**: A rejeição deve ser feita rapidamente. Se demorar muito, a chamada pode cair antes da rejeição.++### Boas Práticas++1. **Sempre responda ao webhook rapidamente**: Rejeite a chamada em menos de 2 segundos para evitar timeout.++2. **Envie mensagem explicativa**: Após rejeitar, informe o usuário o motivo via mensagem de texto.++3. **Log de chamadas rejeitadas**: Mantenha registro para análise, salvando data/hora, número, ID da chamada e motivo da rejeição.++4. **Tratamento de erros**: Sempre trate possíveis erros na rejeição para evitar que seu webhook trave ao falhar em rejeitar uma chamada.++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `invalid request body` | Verifique formato do JSON |+| 500 | `instance not found` | Instância não conectada |+| 500 | `error reject call` | Chamada não existe ou já expirou |++---++## Estrutura do Evento de Chamada++Quando você recebe um webhook de chamada, a estrutura é:++```json+{+ "event": "call",+ "instance": "minha-instancia",+ "data": {+ "id": "ABC123XYZ",+ "from": "[email protected]",+ "timestamp": "2025-11-11T10:30:00Z",+ "isVideo": false,+ "isGroup": false,+ "status": "ringing"+ }+}+```++**Campos**:+- `id`: ID único da chamada (use como `callId`)+- `from`: JID de quem está ligando (use como `callCreator`)+- `timestamp`: Quando a chamada foi iniciada+- `isVideo`: Se é chamada de vídeo (true) ou áudio (false)+- `isGroup`: Se é chamada em grupo+- `status`: Status da chamada (ringing, timeout, reject)++---++## Configuração de Webhooks++Para receber eventos de chamada, configure o webhook:++```env+WEBHOOK_URL=https://seu-servidor.com/webhook+```++Certifique-se de que seu servidor:+1. Aceita requisições POST+2. Responde rapidamente (< 5 segundos)+3. Retorna status 200 para confirmar recebimento++---++## Próximos Passos++- [Sistema de Eventos](../recursos-avancados/events-system.md) - Configurar webhooks+- [API de Mensagens](./api-messages.md) - Enviar mensagem após rejeitar+- [API de Usuários](./api-user.md) - Gerenciar contatos+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-chats.md b/docs/wiki/guias-api/api-chats.mdnew file mode 100644index 0000000..ec672fa--- /dev/null+++ b/docs/wiki/guias-api/api-chats.md@@ -0,0 +1,467 @@+# API de Chats++Documentação completa dos endpoints para gerenciar conversas (pin, arquivo, mute).++## 📋 Índice++- [Fixar Conversa](#fixar-conversa)+- [Desfixar Conversa](#desfixar-conversa)+- [Arquivar Conversa](#arquivar-conversa)+- [Desarquivar Conversa](#desarquivar-conversa)+- [Silenciar Conversa](#silenciar-conversa)+- [Dessilenciar Conversa](#dessilenciar-conversa)+- [Sincronizar Histórico](#sincronizar-histórico)++---++## Fixar Conversa++Fixa uma conversa no topo da lista de chats.++**Endpoint**: `POST /chat/pin`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat (individual ou grupo) |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+# Fixar chat individual+curl -X POST http://localhost:4000/chat/pin \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'++# Fixar grupo+curl -X POST http://localhost:4000/chat/pin \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Desfixar Conversa++Remove a fixação de uma conversa.++**Endpoint**: `POST /chat/unpin`++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/unpin \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Arquivar Conversa++Move uma conversa para o arquivo.++**Endpoint**: `POST /chat/archive`++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |++**Nota**: Conversas arquivadas não aparecem na lista principal, mas ainda recebem mensagens.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/archive \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Desarquivar Conversa++Restaura uma conversa arquivada para a lista principal.++**Endpoint**: `POST /chat/unarchive`++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/unarchive \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Silenciar Conversa++Silencia notificações de uma conversa por 1 hora.++**Endpoint**: `POST /chat/mute`++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |++**Nota**: O silenciamento é fixo por **1 hora** (hard-coded no código: `1*time.Hour`). Para silenciar permanentemente, use o aplicativo WhatsApp.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/mute \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Dessilenciar Conversa++Remove o silenciamento de uma conversa.++**Endpoint**: `POST /chat/unmute`++**Body**:+```json+{+ "chat": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/unmute \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]"+ }'+```++---++## Sincronizar Histórico++Solicita sincronização de histórico de mensagens antigas (WhatsApp Multi-Device).++**Endpoint**: `POST /chat/history-sync`++**Body**:+```json+{+ "messageInfo": {+ "Chat": "[email protected]",+ "IsFromMe": false,+ "IsGroup": false,+ "ID": "3EB0C5A277F7F9B6C599",+ "Timestamp": "2025-11-11T10:00:00Z"+ },+ "count": 50+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `messageInfo` | object | ✅ Sim | Informações da mensagem de referência |+| `messageInfo.Chat` | string | ✅ Sim | JID do chat |+| `messageInfo.IsFromMe` | bool | ✅ Sim | Se a mensagem foi enviada por você |+| `messageInfo.IsGroup` | bool | ✅ Sim | Se é um grupo |+| `messageInfo.ID` | string | ✅ Sim | ID da mensagem de referência |+| `messageInfo.Timestamp` | string | ✅ Sim | Timestamp da mensagem |+| `count` | int | ✅ Sim | Número de mensagens para sincronizar |++**Nota**: Este endpoint é usado para sincronizar mensagens antigas do histórico do WhatsApp Multi-Device. Requer uma mensagem de referência válida.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Timestamp": "2025-11-11T10:30:00Z",+ "ID": "abc123",+ "ServerID": 12345+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/chat/history-sync \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "messageInfo": {+ "Chat": "[email protected]",+ "IsFromMe": false,+ "IsGroup": false,+ "ID": "3EB0C5A277F7F9B6C599",+ "Timestamp": "2025-11-11T10:00:00Z"+ },+ "count": 50+ }'+```++---++## Fluxos de Uso Comuns++### Organizar Conversas Prioritárias++```bash+# 1. Fixar conversas importantes+curl -X POST http://localhost:4000/chat/pin \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"chat": "[email protected]"}'++# 2. Arquivar conversas antigas+curl -X POST http://localhost:4000/chat/archive \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"chat": "[email protected]"}'+```++### Gerenciar Notificações++```bash+# Silenciar grupo temporariamente (1 hora)+curl -X POST http://localhost:4000/chat/mute \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"chat": "[email protected]"}'++# Reativar notificações+curl -X POST http://localhost:4000/chat/unmute \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"chat": "[email protected]"}'+```++### Limpar Lista de Chats++```bash+# Arquivar múltiplas conversas++for chat in "\${CHATS[@]}"; do+ curl -X POST http://localhost:4000/chat/archive \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{"chat": "$chat"}"+done+```++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `chat is required` | Forneça o campo `chat` |+| 500 | `instance not found` | Instância não conectada |+| 500 | `invalid phone number` | JID inválido (formato incorreto) |++---++## Boas Práticas++### 1. Validar JID+Sempre use JIDs no formato correto:+- Chat individual: `[email protected]`+- Grupo: `[email protected]`++### 2. Gerenciar Estado+Mantenha controle do estado dos chats na sua aplicação:+- Registre quais chats estão fixados, arquivados e silenciados+- Lembre-se: um chat não pode estar fixado e arquivado ao mesmo tempo+- Ao fixar um chat, ele é automaticamente desarquivado pelo WhatsApp++### 3. Silenciamento Temporário+Lembre-se que o mute dura apenas 1 hora. Para silenciamento permanente:+- Use o aplicativo WhatsApp nativo+- Ou implemente lógica para re-silenciar periodicamente++### 4. Limite de Chats Fixados+O WhatsApp permite fixar até **3 chats** no topo. Não há validação na API, mas isso é uma limitação do WhatsApp.++### 5. Sincronização de Histórico+Use com cuidado - sincronizar histórico consome recursos. Recomendações:+- Sincronize no máximo **100 mensagens** por vez+- Aguarde resposta antes de nova sincronização+- Use apenas quando necessário (nova instalação, restauração)++---++## Diferenças de Comportamento++### Fixar vs Arquivar+- **Fixar**: Mantém conversa no topo (máx 3)+- **Arquivar**: Remove da lista principal, mas mantém notificações++### Mute vs Archive+- **Mute**: Silencia notificações, mas chat permanece visível+- **Archive**: Oculta chat, mas notificações continuam (a menos que também esteja mutado)++### Para Combinar+```bash+# Arquivar E silenciar (para "esconder" completamente)+curl -X POST http://localhost:4000/chat/archive ...+curl -X POST http://localhost:4000/chat/mute ...++# Fixar (automaticamente desarquiva)+curl -X POST http://localhost:4000/chat/pin ...+```++---++## Próximos Passos++- [API de Labels](./api-labels.md) - Organizar chats com etiquetas+- [API de Mensagens](./api-messages.md) - Gerenciar mensagens+- [API de Grupos](./api-groups.md) - Gerenciar grupos+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-community.md b/docs/wiki/guias-api/api-community.mdnew file mode 100644index 0000000..4eb0a65--- /dev/null+++ b/docs/wiki/guias-api/api-community.md@@ -0,0 +1,376 @@+# API de Comunidades++Documentação dos endpoints para gerenciar Comunidades WhatsApp.++## 📋 Índice++- [Criar Comunidade](#criar-comunidade)+- [Adicionar Grupos](#adicionar-grupos)+- [Remover Grupos](#remover-grupos)++---++## O que são Comunidades?++**Comunidades** são um recurso do WhatsApp que permite agrupar vários grupos relacionados sob uma única estrutura. É como um "grupo de grupos".++**Características**:+- Uma comunidade pode conter **até 50 grupos**+- Cada comunidade tem um **canal de anúncios** (grupo pai)+- Membros da comunidade veem todos os grupos vinculados+- Facilita organização de organizações, escolas, condomínios, etc.++---++## Criar Comunidade++Cria uma nova comunidade WhatsApp.++**Endpoint**: `POST /community/create`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "communityName": "Escola ABC"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `communityName` | string | ✅ Sim | Nome da comunidade |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "JID": "[email protected]",+ "OwnerJID": "[email protected]",+ "GroupName": {+ "Name": "Escola ABC",+ "NameSetAt": "2025-11-11T10:30:00Z",+ "NameSetBy": "[email protected]"+ },+ "GroupCreated": "2025-11-11T10:30:00Z",+ "GroupParent": {+ "IsParent": true+ }+ }+}+```++**Campos da Resposta**:+- `JID`: ID único da comunidade (formato de grupo @g.us)+- `OwnerJID`: Criador da comunidade+- `GroupName`: Nome e metadados+- `GroupParent.IsParent`: true (indica que é uma comunidade)++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/community/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "communityName": "Condomínio Residencial"+ }'+```++---++## Adicionar Grupos++Adiciona (vincula) grupos existentes a uma comunidade.++**Endpoint**: `POST /community/add`++**Body**:+```json+{+ "communityJid": "[email protected]",+ "groupJid": [+ "[email protected]",+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `communityJid` | string | ✅ Sim | JID da comunidade |+| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para adicionar |++**Nota**: Os grupos devem **já existir** e você deve ser **admin** de ambos (comunidade e grupos).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "success": [+ "[email protected]",+ ],+ "failed": []+ }+}+```++**Campos da Resposta**:+- `success`: Array de grupos adicionados com sucesso+- `failed`: Array de grupos que falharam (não existe, sem permissão, etc)++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/community/add \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "communityJid": "[email protected]",+ "groupJid": [+ ]+ }'+```++---++## Remover Grupos++Remove (desvincula) grupos de uma comunidade.++**Endpoint**: `POST /community/remove`++**Body**:+```json+{+ "communityJid": "[email protected]",+ "groupJid": [+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `communityJid` | string | ✅ Sim | JID da comunidade |+| `groupJid` | array | ✅ Sim | Array de JIDs de grupos para remover |++**Nota**: Remover um grupo da comunidade **não deleta o grupo**, apenas o desvincula.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "success": [+ ],+ "failed": []+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/community/remove \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "communityJid": "[email protected]",+ "groupJid": [+ ]+ }'+```++---++## Fluxo Completo de Gerenciamento++### 1. Criar Comunidade e Organizar Grupos++**Fluxo completo**:++1. **Criar a comunidade** usando `POST /community/create`+2. **Criar os grupos** que farão parte da comunidade usando `POST /group/create`+3. **Adicionar os grupos à comunidade** usando `POST /community/add` com os JIDs obtidos nos passos anteriores++Exemplo:+- Primeiro, crie uma comunidade "Escola Municipal" e guarde o `JID` retornado+- Depois, crie dois grupos "1º Ano A" e "2º Ano B" e guarde os JIDs+- Por fim, adicione os grupos à comunidade usando os JIDs++### 2. Reorganizar Comunidade++Para reorganizar uma comunidade (remover grupos antigos e adicionar novos):++1. Use `POST /community/remove` para remover grupos que não fazem mais parte+2. Use `POST /community/add` para adicionar novos grupos++Exemplo: Se você precisa substituir o grupo "[email protected]" por dois novos grupos, primeiro remova o antigo e depois adicione os novos usando os respectivos endpoints.++---++## Casos de Uso++### 1. Escola / Universidade++```+Comunidade: "Universidade XYZ"+├── Grupo: Administração+├── Grupo: Engenharia - 1º Ano+├── Grupo: Engenharia - 2º Ano+├── Grupo: Medicina - 1º Ano+└── Grupo: Eventos+```++### 2. Condomínio++```+Comunidade: "Condomínio Residencial"+├── Grupo: Síndico e Zeladores+├── Grupo: Bloco A+├── Grupo: Bloco B+├── Grupo: Churrasqueira (Reservas)+└── Grupo: Comunicados Gerais+```++### 3. Empresa++```+Comunidade: "Empresa LTDA"+├── Grupo: Diretoria+├── Grupo: TI+├── Grupo: Vendas+├── Grupo: Marketing+└── Grupo: RH+```++### 4. Igreja / Instituição Religiosa++```+Comunidade: "Igreja Central"+├── Grupo: Liderança+├── Grupo: Jovens+├── Grupo: Mulheres+├── Grupo: Eventos+└── Grupo: Voluntários+```++---++## Permissões e Limitações++### Permissões Necessárias++Para gerenciar comunidades, você precisa ser:+1. **Criador** da comunidade (para adicionar/remover grupos)+2. **Admin** dos grupos que deseja vincular++### Limitações do WhatsApp++| Limitação | Valor |+|-----------|-------|+| Máximo de grupos por comunidade | 50 |+| Máximo de participantes por grupo | 1024 |+| Máximo de admins por grupo | Ilimitado |++### Comportamento++- **Desvincular grupo**: Não deleta o grupo, apenas remove da comunidade+- **Deletar comunidade**: Não deleta os grupos vinculados+- **Sair da comunidade**: Você sai de todos os grupos vinculados++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `community name is required` | Forneça o nome da comunidade |+| 400 | `community jid is required` | Forneça o JID da comunidade |+| 400 | `group jid is required` | Forneça array de JIDs de grupos |+| 500 | `instance not found` | Instância não conectada |+| 500 | `error parse community jid` | JID inválido |+| 500 | `error link group` | Sem permissão ou grupo não existe |++---++## Boas Práticas++### 1. Planeje a Estrutura++Antes de criar, defina a organização:+```+Comunidade (Tema geral)+├── Grupo 1 (Categoria específica)+├── Grupo 2 (Categoria específica)+└── Grupo 3 (Categoria específica)+```++### 2. Nomeação Clara++Use nomes descritivos:+- ✅ "Escola ABC - 1º Ano A"+- ✅ "Condomínio XYZ - Bloco A"+- ❌ "Grupo 1"+- ❌ "ABC"++### 3. Canal de Anúncios++A comunidade em si funciona como canal de anúncios para todos os grupos. Use-a para:+- Comunicados gerais+- Eventos importantes+- Informações que afetam todos++### 4. Organize por Hierarquia++```+Comunidade (Nível mais alto)+└── Grupos (Nível específico)+ └── Participantes (Nível individual)+```++### 5. Limite de Grupos++Não exceda 50 grupos por comunidade. Se precisar de mais:+- Crie múltiplas comunidades+- Reorganize grupos por temas+- Arquive grupos inativos++---++## Diferenças: Comunidade vs Grupo++| Aspecto | Comunidade | Grupo |+|---------|------------|-------|+| Função | Agrupar grupos relacionados | Conversação direta |+| Limite de membros | 50 grupos × 1024 = 51.200 | 1024 |+| Estrutura | Hierárquica (pais) | Plana (participantes) |+| Mensagens | Canal de anúncios | Conversa completa |+| Admin | Admin da comunidade | Admin do grupo |++---++## Próximos Passos++- [API de Grupos](./api-groups.md) - Criar e gerenciar grupos+- [API de Mensagens](./api-messages.md) - Enviar anúncios+- [API de Usuários](./api-user.md) - Gerenciar contatos+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-groups.md b/docs/wiki/guias-api/api-groups.mdnew file mode 100644index 0000000..de41ed7--- /dev/null+++ b/docs/wiki/guias-api/api-groups.md@@ -0,0 +1,808 @@+# API de Grupos++Documentação completa dos endpoints para gerenciar grupos WhatsApp.++## 📋 Índice++- [Listar Grupos](#listar-grupos)+- [Informações do Grupo](#informações-do-grupo)+- [Link de Convite](#link-de-convite)+- [Criar Grupo](#criar-grupo)+- [Gerenciar Participantes](#gerenciar-participantes)+- [Configurações do Grupo](#configurações-do-grupo)+ - [Alterar Foto](#alterar-foto)+ - [Alterar Nome](#alterar-nome)+ - [Alterar Descrição](#alterar-descrição)+- [Meus Grupos (Admin)](#meus-grupos-admin)+- [Entrar via Link](#entrar-via-link)+- [Sair do Grupo](#sair-do-grupo)++---++## Listar Grupos++Lista todos os grupos que você participa.++**Endpoint**: `GET /group/list`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": [+ {+ "JID": "[email protected]",+ "OwnerJID": "[email protected]",+ "GroupName": {+ "Name": "Equipe de Vendas",+ "NameSetAt": "2025-01-15T10:30:00Z",+ "NameSetBy": "[email protected]"+ },+ "GroupTopic": {+ "Topic": "Discussões sobre vendas e metas",+ "TopicID": "abc123",+ "TopicSetAt": "2025-01-15T10:35:00Z",+ "TopicSetBy": "[email protected]"+ },+ "GroupCreated": "2025-01-15T10:00:00Z",+ "Participants": [+ {+ "JID": "[email protected]",+ "IsAdmin": true,+ "IsSuperAdmin": true+ },+ {+ "JID": "[email protected]",+ "IsAdmin": false,+ "IsSuperAdmin": false+ }+ ],+ "ParticipantVersionID": "abc123"+ }+ ]+}+```++**Campos da Resposta**:+- `JID`: ID único do grupo (sempre termina com @g.us)+- `OwnerJID`: Criador do grupo+- `GroupName`: Nome e metadados+- `GroupTopic`: Descrição do grupo+- `Participants`: Lista de participantes com permissões++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/group/list \+ -H "apikey: SUA-CHAVE-API"+```++---++## Informações do Grupo++Obtém informações detalhadas de um grupo específico.++**Endpoint**: `POST /group/info`++**Body**:+```json+{+ "groupJid": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "JID": "[email protected]",+ "OwnerJID": "[email protected]",+ "GroupName": {+ "Name": "Equipe de Vendas",+ "NameSetAt": "2025-01-15T10:30:00Z",+ "NameSetBy": "[email protected]"+ },+ "GroupTopic": {+ "Topic": "Discussões sobre vendas",+ "TopicID": "abc123",+ "TopicSetAt": "2025-01-15T10:35:00Z",+ "TopicSetBy": "[email protected]"+ },+ "GroupCreated": "2025-01-15T10:00:00Z",+ "Participants": [+ {+ "JID": "[email protected]",+ "IsAdmin": true,+ "IsSuperAdmin": true+ }+ ]+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/group/info \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]"+ }'+```++---++## Link de Convite++Obtém ou regenera o link de convite do grupo.++**Endpoint**: `POST /group/invitelink`++**Body**:+```json+{+ "groupJid": "[email protected]",+ "reset": false+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |+| `reset` | bool | ❌ Não | Se true, gera um novo link (invalida o anterior) |++**Nota**: Apenas admins podem obter/resetar links de convite.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"+}+```++**Exemplo cURL**:+```bash+# Obter link existente+curl -X POST http://localhost:4000/group/invitelink \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "reset": false+ }'++# Gerar novo link+curl -X POST http://localhost:4000/group/invitelink \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "reset": true+ }'+```++---++## Criar Grupo++Cria um novo grupo WhatsApp.++**Endpoint**: `POST /group/create`++**Body**:+```json+{+ "groupName": "Equipe de Vendas",+ "participants": [+ "5511999999999",+ "5511888888888",+ "5511777777777"+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupName` | string | ✅ Sim | Nome do grupo |+| `participants` | array | ✅ Sim | Array de números dos participantes (mínimo 1) |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "jid": "[email protected]",+ "name": "Equipe de Vendas",+ "owner": "[email protected]",+ "added": [+ "[email protected]",+ ],+ "failed": [+ ]+ }+}+```++**Campos da Resposta**:+- `jid`: ID do grupo criado+- `name`: Nome do grupo+- `owner`: Criador (você)+- `added`: Participantes adicionados com sucesso+- `failed`: Participantes que falharam (número inválido, bloqueado, etc)++**Nota**: É normal que alguns participantes falhem (números inexistentes, bloqueados, etc).++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/group/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupName": "Meu Grupo",+ "participants": ["5511999999999", "5511888888888"]+ }'+```++---++## Gerenciar Participantes++Adiciona, remove ou promove participantes do grupo.++**Endpoint**: `POST /group/participant`++**Body**:+```json+{+ "groupJid": "[email protected]",+ "action": "add",+ "participants": ["5511999999999", "5511888888888"]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |+| `action` | string | ✅ Sim | Ação a executar |+| `participants` | array | ✅ Sim | Array de números |++**Ações Disponíveis**:++| Action | Descrição | Requer Admin |+|--------|-----------|--------------|+| `add` | Adicionar participantes | ✅ Sim |+| `remove` | Remover participantes | ✅ Sim |+| `promote` | Promover a admin | ✅ Sim |+| `demote` | Remover admin | ✅ Sim |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Resposta de Erro (500)**:+```json+{+ "error": "error create group: 403 forbidden"+}+```++**Exemplos cURL**:++```bash+# Adicionar participantes+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "add",+ "participants": ["5511999999999"]+ }'++# Remover participantes+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "remove",+ "participants": ["5511888888888"]+ }'++# Promover a admin+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "promote",+ "participants": ["5511999999999"]+ }'++# Remover admin (rebaixar)+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "demote",+ "participants": ["5511999999999"]+ }'+```++---++## Configurações do Grupo++### Alterar Foto++Define a foto do grupo.++**Endpoint**: `POST /group/photo`++**Body**:+```json+{+ "groupJid": "[email protected]",+ "image": "https://exemplo.com/logo.jpg"+}+```++Ou com base64:++```json+{+ "groupJid": "[email protected]",+ "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |+| `image` | string | ✅ Sim | URL ou base64 da imagem |++**Formatos Aceitos**:+- URL (http:// ou https://)+- Base64 (data:image/jpeg;base64,... ou data:image/png;base64,...)++**Nota**: Apenas admins podem alterar a foto.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": "abc123"+}+```++O campo `data` contém o ID da nova foto.++**Exemplo cURL**:+```bash+# Com URL+curl -X POST http://localhost:4000/group/photo \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "image": "https://exemplo.com/logo.jpg"+ }'++# Com base64+curl -X POST http://localhost:4000/group/photo \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg..."+ }'+```++---++### Alterar Nome++Altera o nome do grupo.++**Endpoint**: `POST /group/name`++**Body**:+```json+{+ "groupJid": "[email protected]",+ "name": "Novo Nome do Grupo"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |+| `name` | string | ✅ Sim | Novo nome (máx 25 caracteres) |++**Nota**: Apenas admins podem alterar o nome.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/group/name \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "name": "Equipe Marketing 2025"+ }'+```++---++### Alterar Descrição++Altera a descrição do grupo.++**Endpoint**: `POST /group/description`++**Body**:+```json+{+ "groupJid": "[email protected]",+ "description": "Grupo para discussões sobre marketing e estratégias de vendas."+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |+| `description` | string | ✅ Sim | Nova descrição (máx 512 caracteres) |++**Nota**: Apenas admins podem alterar a descrição.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/group/description \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "description": "Grupo oficial da empresa - Apenas assuntos profissionais"+ }'+```++---++## Meus Grupos (Admin)++Lista apenas os grupos onde você é o **proprietário/criador**.++**Endpoint**: `GET /group/myall`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": [+ {+ "JID": "[email protected]",+ "OwnerJID": "[email protected]",+ "GroupName": {+ "Name": "Meu Grupo",+ "NameSetAt": "2025-01-15T10:30:00Z",+ "NameSetBy": "[email protected]"+ },+ "Participants": [...]+ }+ ]+}+```++**Diferença**:+- `/group/list` - Todos os grupos que você participa+- `/group/myall` - Apenas grupos que você criou (owner)++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/group/myall \+ -H "apikey: SUA-CHAVE-API"+```++---++## Entrar via Link++Entra em um grupo através de um link de convite.++**Endpoint**: `POST /group/join`++**Body**:+```json+{+ "code": "ABCDEFGHIJKLMNOP"+}+```++Ou com URL completa:++```json+{+ "code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `code` | string | ✅ Sim | Código do link ou URL completa |++**Nota**: O código é a parte após `https://chat.whatsapp.com/`.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Resposta de Erro (500)**:+```json+{+ "error": "error create group: 404 not found"+}+```++Erros comuns:+- `404 not found` - Link inválido ou expirado+- `403 forbidden` - Você foi banido ou removido+- `406 not acceptable` - Grupo cheio (256 participantes)++**Exemplo cURL**:+```bash+# Com código+curl -X POST http://localhost:4000/group/join \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "code": "ABCDEFGHIJKLMNOP"+ }'++# Com URL completa+curl -X POST http://localhost:4000/group/join \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "code": "https://chat.whatsapp.com/ABCDEFGHIJKLMNOP"+ }'+```++---++## Sair do Grupo++Sai de um grupo WhatsApp.++**Endpoint**: `POST /group/leave`++**Body**:+```json+{+ "groupJid": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupJid` | string | ✅ Sim | JID do grupo |++**Nota**: Se você for o único admin, o grupo ficará sem admins até que outro seja promovido ou o grupo seja excluído.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/group/leave \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]"+ }'+```++---++## Fluxo Completo de Gerenciamento++### 1. Criar e Configurar Grupo++```bash+# 1. Criar grupo+GROUP_JID=$(curl -X POST http://localhost:4000/group/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupName": "Meu Grupo",+ "participants": ["5511999999999"]+ }' | jq -r '.data.jid')++# 2. Adicionar foto+curl -X POST http://localhost:4000/group/photo \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{+ "groupJid": "$GROUP_JID",+ "image": "https://exemplo.com/logo.jpg"+ }"++# 3. Adicionar descrição+curl -X POST http://localhost:4000/group/description \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{+ "groupJid": "$GROUP_JID",+ "description": "Grupo oficial da empresa"+ }"++# 4. Obter link de convite+curl -X POST http://localhost:4000/group/invitelink \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{+ "groupJid": "$GROUP_JID",+ "reset": false+ }"+```++### 2. Gerenciar Participantes++```bash+# Adicionar novos membros+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "add",+ "participants": ["5511888888888", "5511777777777"]+ }'++# Promover a admin+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "promote",+ "participants": ["5511888888888"]+ }'+```++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `groupJid is required` | Forneça o JID do grupo |+| 400 | `groupName is required` | Forneça o nome do grupo |+| 400 | `participants are required` | Forneça array de participantes |+| 400 | `action is required` | Especifique a ação (add/remove/promote/demote) |+| 500 | `invalid group jid` | JID de grupo inválido (deve terminar com @g.us) |+| 500 | `403 forbidden` | Sem permissão (não é admin) |+| 500 | `404 not found` | Grupo não existe ou link inválido |++---++## Boas Práticas++### 1. Verificar Permissões+Sempre verifique se você é admin antes de tentar alterar configurações:+```bash+# 1. Obter info do grupo+INFO=$(curl -s -X POST http://localhost:4000/group/info \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"groupJid": "[email protected]"}')++# 2. Verificar se você é admin+echo $INFO | jq '.data.Participants[] | select(.IsAdmin == true)'+```++### 2. Validar Números+Valide números antes de adicionar ao grupo:+```bash+# 1. Verificar se número existe+curl -X POST http://localhost:4000/user/check \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"number": ["5511999999999"]}'++# 2. Se IsInWhatsapp=true, adicionar ao grupo+curl -X POST http://localhost:4000/group/participant \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupJid": "[email protected]",+ "action": "add",+ "participants": ["5511999999999"]+ }'+```++### 3. Limites do WhatsApp+Respeite os limites do WhatsApp:+- **256 participantes** por grupo+- **25 caracteres** para nome do grupo+- **512 caracteres** para descrição+- Não adicione mais de **20 participantes de uma vez**++### 4. Tratamento de Falhas+Ao criar grupo, sempre verifique o campo `failed` na resposta:+- O campo `added` contém os participantes adicionados com sucesso+- O campo `failed` contém os que falharam (número inválido, não tem WhatsApp, etc)+- Se houver falhas, você pode tentar adicionar novamente após verificação++---++## Próximos Passos++- [API de Mensagens](./api-messages.md) - Enviar mensagens em grupos+- [API de Usuários](./api-user.md) - Gerenciar contatos+- [API de Chats](./api-chats.md) - Gerenciar conversas+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-instances.md b/docs/wiki/guias-api/api-instances.mdnew file mode 100644index 0000000..946b15f--- /dev/null+++ b/docs/wiki/guias-api/api-instances.md@@ -0,0 +1,853 @@+# API de Instâncias++Documentação completa dos endpoints para gerenciar instâncias WhatsApp.++## Visão Geral++Uma **instância** representa uma conexão individual com o WhatsApp. Cada instância mantém sua própria sessão, autenticação e configurações independentes.++**Importante**: A maioria das rotas identifica a instância automaticamente através do header `apikey` (token da instância). Apenas rotas administrativas usam `:instanceId` na URL e exigem a `GLOBAL_API_KEY` configurada no ambiente.++## Endpoints Disponíveis++### Gerenciamento Básico (Administrativo - usa GLOBAL_API_KEY)+- `POST /instance/create` - Criar nova instância+- `GET /instance/all` - Listar todas as instâncias+- `GET /instance/info/:instanceId` - Informações da instância+- `DELETE /instance/delete/:instanceId` - Deletar instância++### Conexão (usa token da instância)+- `POST /instance/connect` - Conectar via QR Code+- `GET /instance/qr` - Obter QR Code+- `POST /instance/pair` - Conectar via código de pareamento+- `GET /instance/status` - Status da conexão+- `POST /instance/disconnect` - Desconectar+- `POST /instance/reconnect` - Reconectar+- `DELETE /instance/logout` - Fazer logout++### Gerenciamento Avançado (Administrativo - usa GLOBAL_API_KEY)+- `POST /instance/proxy/:instanceId` - Configurar proxy+- `DELETE /instance/proxy/:instanceId` - Remover proxy+- `POST /instance/forcereconnect/:instanceId` - Forçar reconexão+- `GET /instance/logs/:instanceId` - Obter logs+- `GET /instance/:instanceId/advanced-settings` - Configurações avançadas+- `PUT /instance/:instanceId/advanced-settings` - Atualizar configurações++---++## Criar Instância++Cria uma nova instância WhatsApp.++### Endpoint+```+POST /instance/create+```++### Headers+```+Content-Type: application/json+apikey: SUA-GLOBAL-API-KEY+```++**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (variável de ambiente), não o token da instância.++### Body+```json+{+ "name": "vendas",+ "token": "token-seguro-unico",+ "webhook": "https://seu-servidor.com/webhook",+ "webhookEvents": ["messages.upsert", "connection.update"],+ "proxy": {+ "host": "proxy.exemplo.com",+ "port": "8080",+ "username": "usuario",+ "password": "senha"+ }+}+```++### Parâmetros++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| name | string | ✅ Sim | Nome único da instância |+| token | string | ✅ Sim | Token de autenticação da instância |+| webhook | string | ❌ Não | URL para receber webhooks |+| webhookEvents | array | ❌ Não | Eventos específicos para webhook |+| proxy | object | ❌ Não | Configuração de proxy |++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "name": "vendas",+ "token": "token-seguro-unico",+ "webhook": "https://seu-servidor.com/webhook",+ "status": "created",+ "createdAt": "2025-01-15T10:30:00Z"+ }+}+```++### Resposta Erro (400)+```json+{+ "error": "name is required"+}+```++### Exemplo cURL+```bash+curl -X POST http://localhost:4000/instance/create -H "Content-Type: application/json" -H "apikey: SUA-CHAVE-API" -d '{+ "name": "vendas",+ "token": "meu-token-seguro"+ }'+```++---++## Conectar Instância++Inicia o processo de conexão via QR Code.++### Endpoint+```+POST /instance/connect+```++### Headers+```+Content-Type: application/json+apikey: TOKEN-DA-INSTANCIA+```++**⚠️ Atenção**: Use o `token` que você definiu ao criar a instância, NÃO a `GLOBAL_API_KEY`.++### Body+```json+{+ "webhookUrl": "https://seu-servidor.com/webhook",+ "subscribe": ["messages.upsert", "connection.update"]+}+```++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "jid": "[email protected]",+ "webhookUrl": "https://seu-servidor.com/webhook",+ "eventString": "messages.upsert,connection.update"+ }+}+```++### Exemplo cURL+```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "Content-Type: application/json" \+ -H "apikey: token-da-instancia-vendas" \+ -d '{+ "webhookUrl": "https://seu-servidor.com/webhook",+ "subscribe": ["messages.upsert"]+ }'+```++---++## Obter QR Code++Retorna o QR Code para escanear com WhatsApp.++### Endpoint+```+GET /instance/qr+```++### Headers+```+apikey: TOKEN-DA-INSTANCIA+```++**Importante**: A instância é identificada automaticamente pelo token no header.++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "qrcode": "2@abcd1234...",+ "code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..."+ }+}+```++### Exemplo cURL+```bash+curl "http://localhost:4000/instance/qr" \+ -H "apikey: token-da-instancia-vendas"+```++---++## Conectar via Código de Pareamento++Conecta usando código de 8 dígitos em vez de QR Code.++### Endpoint+```+POST /instance/pair+```++### Headers+```+Content-Type: application/json+apikey: TOKEN-DA-INSTANCIA+```++### Body+```json+{+ "phone": "5511999999999"+}+```++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "code": "12345678"+ }+}+```++### Como Usar+1. Faça a requisição com seu número+2. Receba o código de 8 dígitos+3. No WhatsApp: Aparelhos conectados > Conectar dispositivo > Conectar com número de telefone+4. Digite o código recebido++### Exemplo cURL+```bash+curl -X POST http://localhost:4000/instance/pair \+ -H "Content-Type: application/json" \+ -H "apikey: token-da-instancia-vendas" \+ -d '{"phone": "5511999999999"}'+```++---++## Status da Conexão++Verifica o status atual da instância.++### Endpoint+```+GET /instance/status+```++### Headers+```+apikey: TOKEN-DA-INSTANCIA+```++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "connected": true,+ "loggedIn": true,+ "name": "Minha Empresa",+ "myJid": "[email protected]"+ }+}+```++### Status Possíveis+- `connected: false, loggedIn: false` - Instância criada mas não conectada+- `connected: true, loggedIn: false` - Conectando (aguardando QR Code)+- `connected: true, loggedIn: true` - Conectado e ativo+- `connected: false, loggedIn: true` - Sessão válida mas desconectado temporariamente++### Exemplo cURL+```bash+curl "http://localhost:4000/instance/status" \+ -H "apikey: token-da-instancia-vendas"+```++---++## Listar Todas as Instâncias++Retorna todas as instâncias cadastradas.++### Endpoint+```+GET /instance/all+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa).++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": [+ {+ "id": "abc123",+ "name": "vendas",+ "connected": true,+ "jid": "[email protected]"+ },+ {+ "id": "def456",+ "name": "suporte",+ "connected": false,+ "jid": null+ }+ ]+}+```++### Exemplo cURL+```bash+curl "http://localhost:4000/instance/all" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++---++## Informações da Instância++Obtém informações detalhadas de uma instância específica.++### Endpoint+```+GET /instance/info/:instanceId+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa) e o ID da instância no path.++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "id": "abc123",+ "name": "vendas",+ "token": "token-seguro",+ "webhook": "https://seu-servidor.com/webhook",+ "events": "messages.upsert,connection.update",+ "connected": true,+ "jid": "[email protected]",+ "createdAt": "2025-01-15T10:30:00Z"+ }+}+```++### Exemplo cURL+```bash+curl "http://localhost:4000/instance/info/vendas" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++---++## Desconectar Instância++Desconecta a instância mas mantém os dados.++### Endpoint+```+POST /instance/disconnect+```++### Headers+```+apikey: TOKEN-DA-INSTANCIA+```++### Body+```json+{}+```++**Nota**: O body pode ser vazio. A instância é identificada pelo header apikey.++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++### Exemplo cURL+```bash+curl -X POST http://localhost:4000/instance/disconnect \+ -H "Content-Type: application/json" \+ -H "apikey: token-da-instancia-vendas" \+ -d '{}'+```++---++## Reconectar Instância++Reconecta uma instância desconectada.++### Endpoint+```+POST /instance/reconnect+```++### Headers+```+apikey: TOKEN-DA-INSTANCIA+```++### Body+```json+{}+```++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++### Exemplo cURL+```bash+curl -X POST http://localhost:4000/instance/reconnect \+ -H "Content-Type: application/json" \+ -H "apikey: token-da-instancia-vendas" \+ -d '{}'+```++---++## Logout++Faz logout completo, removendo a sessão WhatsApp.++### Endpoint+```+DELETE /instance/logout+```++### Headers+```+apikey: TOKEN-DA-INSTANCIA+```++### Body+```json+{}+```++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++**⚠️ Atenção**: Após logout, será necessário escanear QR Code novamente.++### Exemplo cURL+```bash+curl -X DELETE http://localhost:4000/instance/logout \+ -H "Content-Type: application/json" \+ -H "apikey: token-da-instancia-vendas" \+ -d '{}'+```++---++## Deletar Instância++Remove completamente a instância e todos os seus dados.++### Endpoint+```+DELETE /instance/delete/:instanceId+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++**⚠️ Atenção**: Esta rota usa a `GLOBAL_API_KEY` (administrativa). Esta ação é irreversível!++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++### Exemplo cURL+```bash+curl -X DELETE "http://localhost:4000/instance/delete/vendas" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++---++## Configurar Proxy++Configura proxy HTTP para a instância.++### Endpoint+```+POST /instance/proxy/:instanceId+```++### Headers+```+Content-Type: application/json+apikey: SUA-GLOBAL-API-KEY+```++### Body+```json+{+ "host": "proxy.exemplo.com",+ "port": "8080",+ "username": "usuario",+ "password": "senha"+}+```++### Resposta Sucesso (200)+```json+{+ "message": "success",+ "data": {+ "host": "proxy.exemplo.com",+ "port": "8080",+ "hasAuth": true+ }+}+```++### Exemplo cURL+```bash+curl -X POST "http://localhost:4000/instance/proxy/vendas" \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-GLOBAL-API-KEY" \+ -d '{+ "host": "proxy.exemplo.com",+ "port": "8080",+ "username": "usuario",+ "password": "senha"+ }'+```++---++## Remover Proxy++Remove configuração de proxy da instância.++### Endpoint+```+DELETE /instance/proxy/:instanceId+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++### Exemplo cURL+```bash+curl -X DELETE "http://localhost:4000/instance/proxy/vendas" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++---++## Forçar Reconexão++Força reconexão com número específico (útil para resolver problemas).++### Endpoint+```+POST /instance/forcereconnect/:instanceId+```++### Headers+```+Content-Type: application/json+apikey: SUA-GLOBAL-API-KEY+```++### Body+```json+{+ "number": "5511999999999"+}+```++### Resposta Sucesso (200)+```json+{+ "message": "success"+}+```++### Exemplo cURL+```bash+curl -X POST "http://localhost:4000/instance/forcereconnect/vendas" \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-GLOBAL-API-KEY" \+ -d '{"number": "5511999999999"}'+```++---++## Obter Logs++Obtém logs da instância.++### Endpoint+```+GET /instance/logs/:instanceId?start_date=DATA&end_date=DATA&level=NIVEL&limit=N+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++### Query Parameters+| Parâmetro | Tipo | Obrigatório | Descrição |+|-----------|------|-------------|-----------|+| start_date | string | ❌ Não | Data inicial (YYYY-MM-DD) |+| end_date | string | ❌ Não | Data final (YYYY-MM-DD) |+| level | string | ❌ Não | Nível do log (INFO, DEBUG, ERROR) |+| limit | integer | ❌ Não | Número de registros (padrão: 100) |++### Resposta Sucesso (200)+```json+[+ {+ "timestamp": "2025-01-15T10:30:00Z",+ "level": "INFO",+ "message": "Instance connected successfully",+ "instanceId": "vendas"+ }+]+```++### Exemplo cURL+```bash+curl "http://localhost:4000/instance/logs/vendas?start_date=2025-01-01&limit=50" \+ -H "apikey: SUA-GLOBAL-API-KEY"+```++---++## Configurações Avançadas++### Obter Configurações++```+GET /instance/:instanceId/advanced-settings+```++### Headers+```+apikey: SUA-GLOBAL-API-KEY+```++### Resposta (200)+```json+{+ "rejectCall": false,+ "msgCall": "Não estou disponível para chamadas",+ "groupsIgnore": true,+ "alwaysOnline": false,+ "readMessages": false,+ "readStatus": false,+ "syncFullHistory": false+}+```++### Atualizar Configurações++```+PUT /instance/:instanceId/advanced-settings+```++### Headers+```+Content-Type: application/json+apikey: SUA-GLOBAL-API-KEY+```++### Body+```json+{+ "rejectCall": true,+ "msgCall": "Por favor, envie mensagem",+ "groupsIgnore": false,+ "alwaysOnline": true,+ "readMessages": true,+ "readStatus": true,+ "syncFullHistory": false+}+```++### Exemplo cURL+```bash+curl -X PUT "http://localhost:4000/instance/vendas/advanced-settings" \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-GLOBAL-API-KEY" \+ -d '{+ "rejectCall": true,+ "alwaysOnline": true+ }'+```++---++## Fluxo Completo de Uso++### 1. Criar Instância (Administrativo)+```bash+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-GLOBAL-API-KEY" \+ -d '{+ "name": "vendas",+ "token": "token-vendas-123"+ }'+```++### 2. Conectar (Usando Token da Instância)+```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "Content-Type: application/json" \+ -H "apikey: token-vendas-123" \+ -d '{+ "webhookUrl": "https://meu-servidor.com/webhook",+ "subscribe": ["messages.upsert"]+ }'+```++### 3. Obter QR Code+```bash+curl "http://localhost:4000/instance/qr" \+ -H "apikey: token-vendas-123"+```++### 4. Escanear QR Code com WhatsApp++Abra o WhatsApp → Aparelhos conectados → Conectar um aparelho → Escanear QR Code++### 5. Verificar Status+```bash+curl "http://localhost:4000/instance/status" \+ -H "apikey: token-vendas-123"+```++---++## Boas Práticas++### 1. Gestão de Tokens++**GLOBAL_API_KEY**:+- Use para rotas administrativas (criar, deletar, listar instâncias)+- Mantenha em segredo (variável de ambiente)+- Nunca exponha em código frontend+- Rotacione periodicamente++**Token da Instância**:+- Defina ao criar a instância (`token` no body)+- Use para operações da instância específica (enviar mensagens, obter status)+- Um token único por instância+- Use UUIDs: `uuidgen` ou `python3 -c "import uuid; print(uuid.uuid4())"`++### 2. Nome de Instância+- Use nomes descritivos e únicos+- Apenas letras, números e hífen+- Exemplo: `vendas-empresa`, `suporte-01`++### 3. Webhooks+- Configure webhook para receber eventos em tempo real+- Use HTTPS em produção+- Valide os eventos recebidos+- Retorne status 200 rapidamente++### 4. Gerenciamento+- Monitore o status das instâncias regularmente+- Configure reconexão automática se necessário+- Mantenha logs para debug+- Use configurações avançadas conforme necessário++---++## Erros Comuns++### "not authorized"+**Causa**: API key incorreta ou ausente+**Solução**:+- Rotas administrativas: Use `GLOBAL_API_KEY`+- Rotas de operação: Use token da instância++### "instance not found"+**Causa**: Instância não existe ou token incorreto+**Solução**: Verifique se a instância foi criada e se está usando o token correto++### "name is required"+**Causa**: Campo obrigatório não enviado+**Solução**: Inclua todos os campos obrigatórios no body++### QR Code Expira+**Causa**: QR Code tem validade de ~40 segundos+**Solução**: Use `/instance/reconnect` para gerar novo QR++### "session already logged in"+**Causa**: Tentou obter QR Code de instância já conectada+**Solução**: Instância já está conectada, não precisa de QR Code++---++## Próximos Passos++- [API de Mensagens](./api-messages.md) - Enviar diferentes tipos de mensagens+- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos+- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos+- [Configuração](../fundamentos/configuration.md) - Variáveis de ambiente++---++**Dica**: Use o Swagger em `http://localhost:4000/swagger/index.html` para testar os endpoints interativamente!diff --git a/docs/wiki/guias-api/api-labels.md b/docs/wiki/guias-api/api-labels.mdnew file mode 100644index 0000000..09b275f--- /dev/null+++ b/docs/wiki/guias-api/api-labels.md@@ -0,0 +1,540 @@+# API de Labels++Documentação completa dos endpoints para organizar chats e mensagens com etiquetas (labels).++## 📋 Índice++- [Adicionar Label em Chat](#adicionar-label-em-chat)+- [Adicionar Label em Mensagem](#adicionar-label-em-mensagem)+- [Editar Label](#editar-label)+- [Remover Label de Chat](#remover-label-de-chat)+- [Remover Label de Mensagem](#remover-label-de-mensagem)+- [Listar Todas as Labels](#listar-todas-as-labels)++---++## Adicionar Label em Chat++Adiciona uma etiqueta (label) a um chat.++**Endpoint**: `POST /label/chat`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "jid": "[email protected]",+ "labelId": "1"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string | ✅ Sim | JID do chat (individual ou grupo) |+| `labelId` | string | ✅ Sim | ID da label |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/label/chat \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "[email protected]",+ "labelId": "1"+ }'+```++---++## Adicionar Label em Mensagem++Adiciona uma etiqueta a uma mensagem específica.++**Endpoint**: `POST /label/message`++**Body**:+```json+{+ "jid": "[email protected]",+ "labelId": "2",+ "messageId": "3EB0C5A277F7F9B6C599"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string | ✅ Sim | JID do chat |+| `labelId` | string | ✅ Sim | ID da label |+| `messageId` | string | ✅ Sim | ID da mensagem |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/label/message \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "[email protected]",+ "labelId": "2",+ "messageId": "3EB0C5A277F7F9B6C599"+ }'+```++---++## Editar Label++Edita nome, cor ou deleta uma label existente.++**Endpoint**: `POST /label/edit`++**Body**:+```json+{+ "labelId": "1",+ "name": "Clientes VIP",+ "color": 0,+ "deleted": false+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `labelId` | string | ✅ Sim | ID da label a editar |+| `name` | string | ✅ Sim | Novo nome da label |+| `color` | int | ❌ Não | Código de cor (0-19) |+| `deleted` | bool | ❌ Não | Se true, marca label como deletada |++**Cores Disponíveis** (0-19):++| Código | Cor |+|--------|-----|+| 0 | Azul |+| 1 | Rosa |+| 2 | Roxo |+| 3 | Verde |+| 4 | Laranja |+| 5 | Cinza |+| 6 | Vermelho |+| 7 | Marrom |+| 8 | Verde água |+| 9 | Amarelo |+| 10-19 | Variações |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+# Renomear label+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "labelId": "1",+ "name": "Clientes VIP",+ "color": 3+ }'++# Deletar label+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "labelId": "1",+ "name": "Label antiga",+ "deleted": true+ }'+```++---++## Remover Label de Chat++Remove uma etiqueta de um chat.++**Endpoint**: `POST /unlabel/chat`++**Body**:+```json+{+ "jid": "[email protected]",+ "labelId": "1"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string | ✅ Sim | JID do chat |+| `labelId` | string | ✅ Sim | ID da label a remover |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/unlabel/chat \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "[email protected]",+ "labelId": "1"+ }'+```++---++## Remover Label de Mensagem++Remove uma etiqueta de uma mensagem específica.++**Endpoint**: `POST /unlabel/message`++**Body**:+```json+{+ "jid": "[email protected]",+ "labelId": "2",+ "messageId": "3EB0C5A277F7F9B6C599"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string | ✅ Sim | JID do chat |+| `labelId` | string | ✅ Sim | ID da label |+| `messageId` | string | ✅ Sim | ID da mensagem |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/unlabel/message \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "[email protected]",+ "labelId": "2",+ "messageId": "3EB0C5A277F7F9B6C599"+ }'+```++---++## Listar Todas as Labels++Obtém todas as labels da instância.++**Endpoint**: `GET /label`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+[+ {+ "ID": 1,+ "LabelID": "1",+ "Name": "Clientes VIP",+ "Color": 3,+ "Deleted": false,+ "PredefinedID": 0,+ "InstanceID": "minha-instancia"+ },+ {+ "ID": 2,+ "LabelID": "2",+ "Name": "Suporte",+ "Color": 6,+ "Deleted": false,+ "PredefinedID": 0,+ "InstanceID": "minha-instancia"+ }+]+```++**Campos da Resposta**:+- `ID`: ID interno do banco de dados+- `LabelID`: ID da label no WhatsApp+- `Name`: Nome da label+- `Color`: Código da cor (0-19)+- `Deleted`: Se foi deletada+- `PredefinedID`: ID de label pré-definida (0 se customizada)+- `InstanceID`: ID da instância++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/label \+ -H "apikey: SUA-CHAVE-API"+```++---++## Fluxos Completos de Uso++### 1. Sistema de Categorização de Clientes++```bash+# 1. Listar labels existentes+LABELS=$(curl -s -X GET http://localhost:4000/label \+ -H "apikey: SUA-CHAVE-API")++echo $LABELS | jq '.'++# 2. Criar nova label (via edição)+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "labelId": "10",+ "name": "Lead Qualificado",+ "color": 3,+ "deleted": false+ }'++# 3. Etiquetar chats de clientes+CLIENTES=("[email protected]" "[email protected]")++for cliente in "\${CLIENTES[@]}"; do+ curl -X POST http://localhost:4000/label/chat \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{+ "jid": "$cliente",+ "labelId": "10"+ }"+done+```++### 2. Marcar Mensagens Importantes++```bash+# Etiquetar mensagem específica como "Urgente"+curl -X POST http://localhost:4000/label/message \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "[email protected]",+ "labelId": "5",+ "messageId": "3EB0C5A277F7F9B6C599"+ }'+```++### 3. Gerenciar Labels de Suporte++```bash+# Criar labels de status de atendimento+LABELS=(+ "1:Aguardando:0"+ "2:Em Atendimento:3"+ "3:Resolvido:4"+ "4:Cancelado:6"+)++for label_data in "\${LABELS[@]}"; do+ IFS=':' read -r id name color <<< "$label_data"++ curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{+ "labelId": "$id",+ "name": "$name",+ "color": $color,+ "deleted": false+ }"+done+```++### 4. Reorganizar Labels++```bash+# Renomear label existente+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "labelId": "1",+ "name": "Clientes Premium",+ "color": 1+ }'++# Deletar label obsoleta+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "labelId": "99",+ "name": "Label Antiga",+ "deleted": true+ }'+```++---++## Casos de Uso Práticos++### CRM Simples+Use labels para categorizar clientes:+- **Label 1**: Leads+- **Label 2**: Clientes Ativos+- **Label 3**: Clientes Inativos+- **Label 4**: VIP++### Suporte ao Cliente+Organize tickets por status:+- **Label 1**: Aberto+- **Label 2**: Em Progresso+- **Label 3**: Aguardando Cliente+- **Label 4**: Resolvido++### E-commerce+Categorize conversas por estágio:+- **Label 1**: Interessado+- **Label 2**: Pedido Realizado+- **Label 3**: Enviado+- **Label 4**: Entregue++### Equipes+Atribua conversas para departamentos:+- **Label 1**: Vendas+- **Label 2**: Suporte+- **Label 3**: Financeiro+- **Label 4**: Diretoria++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `jid is required` | Forneça o JID do chat |+| 400 | `label id is required` | Forneça o ID da label |+| 400 | `message id is required` | Forneça o ID da mensagem |+| 400 | `name is required` | Forneça o nome da label (ao editar) |+| 500 | `instance not found` | Instância não conectada |+| 500 | `error parse community jid` | JID inválido |++---++## Boas Práticas++### 1. Planeje suas Labels+Defina um sistema de categorização antes de começar. Exemplo:+- **Label 1**: "Novo Lead" (cor: azul/0)+- **Label 2**: "Qualificado" (cor: verde/3)+- **Label 3**: "Cliente" (cor: rosa/1)+- **Label 4**: "Inativo" (cor: marrom/5)++### 2. Use Cores Consistentes+Mantenha um padrão de cores:+- **Verde (3)**: Status positivo+- **Vermelho (6)**: Urgente/Problema+- **Azul (0)**: Novo/Neutro+- **Laranja (4)**: Em progresso++### 3. Documente IDs+Mantenha uma tabela de referência:+```+ID | Nome | Cor | Descrição+---|------|-----|----------+1 | VIP | 1 | Clientes premium+2 | Lead | 0 | Novos contatos+3 | Urg | 6 | Requer atenção+```++### 4. Não Abuse de Labels+Limite-se a **10-15 labels** no máximo. Muitas labels dificultam a organização.++### 5. Limpe Labels Antigas+Periodicamente, revise e delete labels não utilizadas:+```bash+# Listar todas+curl -s http://localhost:4000/label -H "apikey: KEY" | jq '.'++# Deletar obsoletas+curl -X POST http://localhost:4000/label/edit \+ -H "Content-Type: application/json" \+ -H "apikey: KEY" \+ -d '{"labelId": "99", "name": "Old", "deleted": true}'+```++### 6. Labels em Mensagens+Use labels em mensagens apenas para casos especiais:+- Mensagens com pedidos+- Informações importantes para referência+- Reclamações/Problemas++**Evite**: Etiquetar todas as mensagens (cria poluição visual).++---++## Limitações do WhatsApp++### Limites Conhecidos+- **Máximo de labels**: Não documentado oficialmente, mas recomenda-se não ultrapassar 100+- **Labels por chat**: Sem limite conhecido+- **Labels por mensagem**: 1 label por mensagem++### Sincronização+Labels são sincronizadas entre dispositivos via WhatsApp Multi-Device. Mudanças podem levar alguns segundos para aparecer em outros dispositivos.++### Visibilidade+Labels são **privadas** - apenas você vê suas labels. O destinatário não vê que você etiquetou o chat ou mensagem.++---++## Próximos Passos++- [API de Chats](./api-chats.md) - Gerenciar conversas (pin, archive, mute)+- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens+- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-messages.md b/docs/wiki/guias-api/api-messages.mdnew file mode 100644index 0000000..394c17e--- /dev/null+++ b/docs/wiki/guias-api/api-messages.md@@ -0,0 +1,1261 @@+# API de Mensagens++Documentação completa dos endpoints para enviar e gerenciar mensagens WhatsApp.++## 📋 Índice++### Enviar Mensagens+- [Enviar Texto](#enviar-texto)+- [Enviar Link com Preview](#enviar-link-com-preview)+- [Enviar Mídia](#enviar-mídia)+- [Enviar Enquete (Poll)](#enviar-enquete)+- [Enviar Sticker](#enviar-sticker)+- [Enviar Localização](#enviar-localização)+- [Enviar Contato](#enviar-contato)+- [~~Enviar Botões~~](#enviar-botões) ⚠️ **DEPRECIADO**+- [~~Enviar Lista~~](#enviar-lista) ⚠️ **DEPRECIADO**++### Gerenciar Mensagens+- [Reagir a Mensagem](#reagir-a-mensagem)+- [Marcar como Lida](#marcar-como-lida)+- [Editar Mensagem](#editar-mensagem)+- [Deletar Mensagem](#deletar-mensagem)+- [Presença no Chat](#presença-no-chat)+- [Download de Mídia](#download-de-mídia)+- [Status da Mensagem](#status-da-mensagem)++---++## Enviar Mensagens++### Enviar Texto++Envia uma mensagem de texto simples.++**Endpoint**: `POST /send/text`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "number": "5511999999999",+ "text": "Olá! Como posso ajudar?",+ "id": "msg-custom-123",+ "delay": 1000,+ "mentionedJid": "[email protected]",+ "mentionAll": false,+ "formatJid": true,+ "quoted": {+ "messageId": "BAE5...",+ "participant": "[email protected]"+ }+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário (formato: DDI + DDD + número) |+| `text` | string | ✅ Sim | Texto da mensagem |+| `id` | string | ❌ Não | ID customizado (se vazio, será gerado automaticamente) |+| `delay` | int32 | ❌ Não | Delay em milissegundos antes de enviar |+| `mentionedJid` | string | ❌ Não | JID do usuário a mencionar |+| `mentionAll` | bool | ❌ Não | Mencionar todos os participantes (apenas grupos) |+| `formatJid` | bool | ❌ Não | Formatar número automaticamente (padrão: true) |+| `quoted` | object | ❌ Não | Mensagem a ser citada |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "ServerID": 12345,+ "Timestamp": "2025-11-11T10:30:00Z",+ "Type": "ExtendedTextMessage"+ }+ }+}+```++**Resposta de Erro (400)**:+```json+{+ "error": "phone number is required"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/text \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "text": "Olá! Esta é uma mensagem de teste."+ }'+```++---++### Enviar Link com Preview++Envia uma mensagem com preview de link (título, descrição, imagem).++**Endpoint**: `POST /send/link`++**Body**:+```json+{+ "number": "5511999999999",+ "text": "Confira este artigo: https://example.com/artigo",+ "title": "Título do Link",+ "url": "https://example.com/artigo",+ "description": "Descrição do conteúdo",+ "imgUrl": "https://example.com/imagem.jpg"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `text` | string | ✅ Sim | Texto com URL |+| `title` | string | ❌ Não | Título do preview (extraído automaticamente se vazio) |+| `url` | string | ❌ Não | URL do link |+| `description` | string | ❌ Não | Descrição (extraída automaticamente se vazia) |+| `imgUrl` | string | ❌ Não | URL da imagem de preview |++**Nota**: Se `title`, `description` ou `imgUrl` não forem fornecidos, o sistema tentará extrair automaticamente os metadados Open Graph da URL.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ExtendedTextMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/link \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "text": "Veja esta notícia: https://g1.globo.com/tecnologia"+ }'+```++---++### Enviar Mídia++Envia imagem, vídeo, áudio ou documento. Suporta envio via **URL** ou **arquivo local** (multipart/form-data).++**Endpoint**: `POST /send/media`++#### Opção 1: Enviar por URL++**Body (JSON)**:+```json+{+ "number": "5511999999999",+ "url": "https://example.com/imagem.jpg",+ "type": "image",+ "caption": "Confira esta imagem!",+ "filename": "foto.jpg"+}+```++#### Opção 2: Enviar Arquivo (multipart/form-data)++**Body (form-data)**:+```+number: 5511999999999+type: image+caption: Confira esta imagem!+filename: foto.jpg+file: [arquivo binário]+delay: 0+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `type` | string | ✅ Sim | Tipo: `image`, `video`, `audio`, `document` |+| `url` | string | ✅ Sim (URL) | URL da mídia (se não enviar arquivo) |+| `file` | binary | ✅ Sim (arquivo) | Arquivo binário (se não enviar URL) |+| `caption` | string | ❌ Não | Legenda da mídia |+| `filename` | string | ❌ Não | Nome do arquivo |++**Tipos de Mídia Aceitos**:++| Tipo | Formatos Aceitos | Observações |+|------|------------------|-------------|+| `image` | JPG, PNG, WebP | WebP convertido para JPEG |+| `video` | MP4 | Apenas MP4 |+| `audio` | Qualquer | Convertido para Opus (PTT) automaticamente |+| `document` | Qualquer | Qualquer tipo de arquivo |++**Áudio**: O sistema converte automaticamente qualquer formato de áudio para **Opus** (formato PTT do WhatsApp). Pode usar conversor local (ffmpeg) ou API externa (configurável via `API_AUDIO_CONVERTER`).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ImageMessage"+ }+ }+}+```++**Resposta de Erro (400)**:+```json+{+ "error": "Invalid file format: 'image/gif'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted"+}+```++**Exemplo cURL (URL)**:+```bash+curl -X POST http://localhost:4000/send/media \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "url": "https://exemplo.com/produto.jpg",+ "type": "image",+ "caption": "Novo produto disponível!"+ }'+```++**Exemplo cURL (Arquivo)**:+```bash+curl -X POST http://localhost:4000/send/media \+ -H "apikey: SUA-CHAVE-API" \+ -F "number=5511999999999" \+ -F "type=image" \+ -F "caption=Foto enviada" \+ -F "file=@/caminho/para/imagem.jpg"+```++---++### Enviar Enquete++Cria uma enquete (poll) com múltiplas opções.++**Endpoint**: `POST /send/poll`++**Body**:+```json+{+ "number": "5511999999999",+ "question": "Qual seu horário preferido?",+ "maxAnswer": 1,+ "options": [+ "Manhã (8h-12h)",+ "Tarde (13h-18h)",+ "Noite (19h-22h)"+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `question` | string | ✅ Sim | Pergunta da enquete |+| `options` | array | ✅ Sim | Opções (mínimo 2) |+| `maxAnswer` | int | ❌ Não | Número máximo de respostas permitidas |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "PollCreationMessage"+ }+ }+}+```++**Resposta de Erro (400)**:+```json+{+ "error": "minimum 2 options are required"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/poll \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "question": "Qual plano você prefere?",+ "maxAnswer": 1,+ "options": ["Básico", "Intermediário", "Premium"]+ }'+```++---++### Enviar Sticker++Envia um sticker (figurinha) via URL.++**Endpoint**: `POST /send/sticker`++**Body**:+```json+{+ "number": "5511999999999",+ "sticker": "https://example.com/sticker.webp"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `sticker` | string | ✅ Sim | URL da imagem (convertida para WebP automaticamente) |++**Nota**: O sistema converte automaticamente a imagem para o formato WebP (formato de sticker do WhatsApp).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "StickerMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/sticker \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "sticker": "https://exemplo.com/figurinha.png"+ }'+```++---++### Enviar Localização++Envia uma localização geográfica.++**Endpoint**: `POST /send/location`++**Body**:+```json+{+ "number": "5511999999999",+ "name": "Escritório Central",+ "address": "Av. Paulista, 1000 - São Paulo, SP",+ "latitude": -23.5505199,+ "longitude": -46.6333094+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `latitude` | float64 | ✅ Sim | Latitude da localização |+| `longitude` | float64 | ✅ Sim | Longitude da localização |+| `name` | string | ✅ Sim | Nome do local |+| `address` | string | ✅ Sim | Endereço do local |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "LocationMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/location \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "name": "Teatro Municipal",+ "address": "Praça Ramos de Azevedo, São Paulo",+ "latitude": -23.5454614,+ "longitude": -46.6369813+ }'+```++---++### Enviar Contato++Envia um cartão de contato (VCard).++**Endpoint**: `POST /send/contact`++**Body**:+```json+{+ "number": "5511999999999",+ "vcard": {+ "fullName": "João Silva",+ "phone": "5511888888888",+ "organization": "Empresa LTDA"+ }+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `vcard.fullName` | string | ✅ Sim | Nome completo do contato |+| `vcard.phone` | string | ✅ Sim | Telefone do contato |+| `vcard.organization` | string | ❌ Não | Empresa/organização |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ContactMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/contact \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "vcard": {+ "fullName": "Maria Santos",+ "phone": "5511777777777",+ "organization": "Vendas LTDA"+ }+ }'+```++---++### Enviar Botões++> ⚠️ **ENDPOINT DEPRECIADO**+>+> Este endpoint **não funciona mais**. O WhatsApp descontinuou o suporte a botões interativos para contas que não são Business API oficial.+>+> **Alternativas**:+> - Use **Enquetes (Polls)** para coleta de respostas+> - Use **mensagens de texto** com instruções+> - Para soluções avançadas, migre para WhatsApp Business API oficial++~~Envia mensagem com botões interativos. Suporta diferentes tipos de botões.~~++**Endpoint**: ~~`POST /send/button`~~++**Body**:+```json+{+ "number": "5511999999999",+ "title": "Escolha uma opção",+ "description": "Selecione o que deseja fazer",+ "footer": "Powered by Evolution GO",+ "buttons": [+ {+ "type": "reply",+ "displayText": "Ver Produtos",+ "id": "btn_produtos"+ },+ {+ "type": "url",+ "displayText": "Site Oficial",+ "url": "https://exemplo.com"+ },+ {+ "type": "call",+ "displayText": "Ligar",+ "phoneNumber": "5511999999999"+ }+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `title` | string | ✅ Sim | Título da mensagem |+| `description` | string | ✅ Sim | Descrição/corpo da mensagem |+| `footer` | string | ✅ Sim | Rodapé da mensagem |+| `buttons` | array | ✅ Sim | Array de botões (máx 3 para tipo reply) |++**Tipos de Botões**:++| Tipo | Campos Necessários | Descrição | Limitações |+|------|-------------------|-----------|------------|+| `reply` | `displayText`, `id` | Botão de resposta rápida | Máx 3, não pode misturar com outros tipos |+| `copy` | `displayText`, `copyCode` | Copiar texto | - |+| `url` | `displayText`, `url` | Abrir URL | - |+| `call` | `displayText`, `phoneNumber` | Ligar para número | - |+| `pix` | `name`, `key`, `keyType`, `currency` | Pagamento PIX (Brasil) | Não pode combinar com outros |++**Botão PIX**:+```json+{+ "type": "pix",+ "name": "Loja Exemplo",+ "key": "[email protected]",+ "keyType": "email",+ "currency": "BRL"+}+```++Tipos de chave PIX: `phone`, `email`, `cpf`, `cnpj`, `random` (EVP).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ButtonMessage"+ }+ }+}+```++**Resposta de Erro (400)**:+```json+{+ "error": "máximo de 3 botões do tipo 'reply' permitidos"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/button \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "title": "Atendimento",+ "description": "Como podemos ajudar?",+ "footer": "Suporte 24h",+ "buttons": [+ {"type": "reply", "displayText": "Falar com Vendas", "id": "vendas"},+ {"type": "reply", "displayText": "Suporte Técnico", "id": "suporte"}+ ]+ }'+```++---++### Enviar Lista++> ⚠️ **ENDPOINT DEPRECIADO**+>+> Este endpoint **não funciona mais**. O WhatsApp descontinuou o suporte a listas interativas para contas que não são Business API oficial.+>+> **Alternativas**:+> - Use **Enquetes (Polls)** para seleção de opções+> - Use **mensagens de texto** com numeração+> - Para soluções avançadas, migre para WhatsApp Business API oficial++~~Envia mensagem com menu de lista interativo.~~++**Endpoint**: ~~`POST /send/list`~~++**Body**:+```json+{+ "number": "5511999999999",+ "title": "Nossos Serviços",+ "description": "Selecione um serviço",+ "buttonText": "Ver Opções",+ "footerText": "Atendimento 24h",+ "sections": [+ {+ "title": "Planos",+ "rows": [+ {+ "title": "Plano Básico",+ "description": "R$ 29,90/mês",+ "rowId": "plano_basico"+ },+ {+ "title": "Plano Premium",+ "description": "R$ 59,90/mês",+ "rowId": "plano_premium"+ }+ ]+ },+ {+ "title": "Suporte",+ "rows": [+ {+ "title": "Falar com Atendente",+ "description": "Chat ao vivo",+ "rowId": "atendente"+ }+ ]+ }+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do destinatário |+| `title` | string | ✅ Sim | Título da mensagem |+| `description` | string | ✅ Sim | Descrição/corpo |+| `buttonText` | string | ✅ Sim | Texto do botão que abre a lista |+| `footerText` | string | ✅ Sim | Rodapé da mensagem |+| `sections` | array | ✅ Sim | Seções da lista |++**Estrutura de Section**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `title` | string | ✅ Sim | Título da seção |+| `rows` | array | ✅ Sim | Linhas da seção |++**Estrutura de Row**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `title` | string | ✅ Sim | Título da opção |+| `description` | string | ❌ Não | Descrição da opção |+| `rowId` | string | ✅ Sim | ID único da opção |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ListMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/send/list \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "title": "Menu Principal",+ "description": "Escolha uma categoria",+ "buttonText": "Ver Menu",+ "footerText": "Delivery 24h",+ "sections": [+ {+ "title": "Pratos",+ "rows": [+ {"title": "Pizza", "description": "A partir de R$ 35", "rowId": "pizza"},+ {"title": "Hambúrguer", "description": "A partir de R$ 25", "rowId": "burger"}+ ]+ }+ ]+ }'+```++---++## Gerenciar Mensagens++### Reagir a Mensagem++Adiciona ou remove uma reação (emoji) em uma mensagem.++**Endpoint**: `POST /message/react`++**Body**:+```json+{+ "number": "5511999999999",+ "reaction": "👍",+ "id": "3EB0C5A277F7F9B6C599",+ "fromMe": false,+ "participant": "[email protected]"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do chat (individual ou grupo) |+| `reaction` | string | ✅ Sim | Emoji da reação (ou "remove" para remover) |+| `id` | string | ✅ Sim | ID da mensagem a reagir |+| `fromMe` | bool | ✅ Sim | Se a mensagem foi enviada por você (true/false) |+| `participant` | string | ❌ Não | JID do autor (obrigatório em grupos quando fromMe=false) |++**Nota**: Para remover uma reação, use `"reaction": "remove"`.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Info": {+ "ID": "3EB0C5A277F7F9B6C599",+ "Type": "ReactionMessage"+ }+ }+}+```++**Exemplo cURL**:+```bash+# Adicionar reação+curl -X POST http://localhost:4000/message/react \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "reaction": "❤️",+ "id": "3EB0C5A277F7F9B6C599",+ "fromMe": false+ }'++# Remover reação+curl -X POST http://localhost:4000/message/react \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "reaction": "remove",+ "id": "3EB0C5A277F7F9B6C599",+ "fromMe": false+ }'+```++---++### Marcar como Lida++Marca mensagem(ns) como lida(s).++**Endpoint**: `POST /message/markread`++**Body**:+```json+{+ "number": "5511999999999",+ "id": [+ "3EB0C5A277F7F9B6C599",+ "3EB0C5A277F7F9B6C600"+ ]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do chat |+| `id` | array | ✅ Sim | Array de IDs de mensagens para marcar como lidas |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/message/markread \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "id": ["3EB0C5A277F7F9B6C599"]+ }'+```++---++### Editar Mensagem++Edita o conteúdo de uma mensagem enviada.++**Endpoint**: `POST /message/edit`++**Body**:+```json+{+ "chat": "[email protected]",+ "messageId": "3EB0C5A277F7F9B6C599",+ "message": "Texto editado da mensagem"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |+| `messageId` | string | ✅ Sim | ID da mensagem a editar |+| `message` | string | ✅ Sim | Novo texto da mensagem |++**Nota**: Só é possível editar mensagens de texto enviadas por você (fromMe=true).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "messageId": "3EB0C5A277F7F9B6C599",+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/message/edit \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]",+ "messageId": "3EB0C5A277F7F9B6C599",+ "message": "Mensagem corrigida"+ }'+```++---++### Deletar Mensagem++Deleta uma mensagem para todos (revoke).++**Endpoint**: `POST /message/delete`++**Body**:+```json+{+ "chat": "[email protected]",+ "messageId": "3EB0C5A277F7F9B6C599"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `chat` | string | ✅ Sim | JID do chat |+| `messageId` | string | ✅ Sim | ID da mensagem a deletar |++**Nota**: Só é possível deletar mensagens enviadas por você. O WhatsApp tem limite de tempo para deletar mensagens (geralmente até 1 hora).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "messageId": "3EB0C5A277F7F9B6C599",+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/message/delete \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "chat": "[email protected]",+ "messageId": "3EB0C5A277F7F9B6C599"+ }'+```++---++### Presença no Chat++Define o status de presença no chat (digitando, gravando áudio, online).++**Endpoint**: `POST /message/presence`++**Body**:+```json+{+ "number": "5511999999999",+ "state": "composing",+ "isAudio": false+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do chat |+| `state` | string | ✅ Sim | Estado: `composing`, `paused`, `recording`, `available`, `unavailable` |+| `isAudio` | bool | ❌ Não | Se true, mostra "gravando áudio" (apenas com state=composing) |++**Estados Disponíveis**:+- `composing` - Digitando...+- `paused` - Para de digitar+- `recording` - Gravando áudio (use isAudio=true)+- `available` - Online+- `unavailable` - Offline++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+# Mostrar "digitando..."+curl -X POST http://localhost:4000/message/presence \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "state": "composing",+ "isAudio": false+ }'++# Mostrar "gravando áudio..."+curl -X POST http://localhost:4000/message/presence \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "state": "composing",+ "isAudio": true+ }'++# Parar de digitar+curl -X POST http://localhost:4000/message/presence \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "state": "paused"+ }'+```++---++### Download de Mídia++Faz download de mídia de uma mensagem recebida e retorna em base64.++**Endpoint**: `POST /message/downloadimage`++**Body**:+```json+{+ "message": {+ "imageMessage": {+ "url": "...",+ "mimetype": "image/jpeg",+ "fileSha256": "...",+ "fileLength": "..."+ }+ }+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `message` | object | ✅ Sim | Objeto de mensagem completo (do webhook) |++**Tipos de Mídia Suportados**:+- `imageMessage` - Imagens+- `videoMessage` - Vídeos+- `audioMessage` - Áudios+- `documentMessage` - Documentos+- `stickerMessage` - Stickers (convertido para PNG)++**Nota**: O objeto `message` deve ser o mesmo recebido via webhook/event. Contém todas as informações necessárias para download (URL, chaves de criptografia, etc).++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "base64": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/message/downloadimage \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "message": {+ "imageMessage": {+ "url": "https://mmg.whatsapp.net/...",+ "mimetype": "image/jpeg",+ "fileSha256": "...",+ "fileLength": 123456+ }+ }+ }'+```++---++### Status da Mensagem++Consulta o status de entrega/leitura de uma mensagem no banco de dados.++**Endpoint**: `POST /message/status`++**Body**:+```json+{+ "id": "3EB0C5A277F7F9B6C599"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `id` | string | ✅ Sim | ID da mensagem |++**Nota**: Requer `DATABASE_SAVE_MESSAGES=true` para funcionar. O sistema precisa estar salvando mensagens no banco.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "result": {+ "id": "3EB0C5A277F7F9B6C599",+ "remoteJid": "[email protected]",+ "fromMe": true,+ "messageType": "conversation",+ "status": "READ",+ "timestamp": "2025-11-11T10:30:00Z"+ },+ "timestamp": "2025-11-11T10:31:00Z"+ }+}+```++**Status Possíveis**:+- `PENDING` - Enviando+- `SENT` - Enviada+- `DELIVERED` - Entregue+- `READ` - Lida++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/message/status \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "id": "3EB0C5A277F7F9B6C599"+ }'+```++---++## Recursos Adicionais++### Citação de Mensagens (Quoted)++Para citar/responder uma mensagem, adicione o objeto `quoted` em qualquer endpoint de envio:++```json+{+ "number": "5511999999999",+ "text": "Respondendo sua mensagem",+ "quoted": {+ "messageId": "3EB0C5A277F7F9B6C599",+ "participant": "[email protected]"+ }+}+```++### Menções em Grupos++Para mencionar usuários em grupos, use `mentionedJid` ou `mentionAll`:++```json+{+ "number": "[email protected]",+ "text": "Olá @usuario, tudo bem?",+ "mentionedJid": "[email protected]"+}+```++Ou mencionar todos:++```json+{+ "number": "[email protected]",+ "text": "@todos Reunião às 15h!",+ "mentionAll": true+}+```++### Delay e Presença++Simule digitação antes de enviar:++```json+{+ "number": "5511999999999",+ "text": "Mensagem com delay",+ "delay": 3000+}+```++Isso mostrará "digitando..." por 3 segundos antes de enviar a mensagem.++### Verificação de Número++Por padrão, o sistema verifica se o número existe no WhatsApp antes de enviar (configurável via `CHECK_USER_EXISTS`). Se desabilitado, mensagens podem falhar silenciosamente.++### Formatação de Números++O parâmetro `formatJid` (padrão: true) normaliza automaticamente o número:+- Remove caracteres especiais+- Adiciona sufixo @s.whatsapp.net+- Valida formato++Para enviar para JIDs já formatados (grupos, etc), use `formatJid: false`.++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `phone number is required` | Forneça o campo `number` |+| 400 | `message body is required` | Forneça o campo `text` ou conteúdo |+| 400 | `minimum 2 options are required` | Enquetes precisam de pelo menos 2 opções |+| 400 | `Invalid file format` | Formato de arquivo não suportado |+| 500 | `instance not found` | Instância não existe ou não está conectada |+| 500 | `client disconnected` | Instância desconectada, reconecte |+| 500 | `number X is not registered on WhatsApp` | Número não existe no WhatsApp |++---++## Boas Práticas++### 1. Usar Delay em Múltiplas Mensagens+Ao enviar várias mensagens seguidas, use o parâmetro `delay` para parecer mais natural:+- Primeira mensagem: `"delay": 1000` (1 segundo)+- Segunda mensagem: `"delay": 2000` (2 segundos)+- Terceira mensagem: `"delay": 1500` (1.5 segundos)++Isso simula o tempo que uma pessoa levaria para digitar cada mensagem.++### 2. Verificar Status de Conexão+Antes de enviar mensagens em massa, verifique se a instância está conectada:+```bash+curl "http://localhost:4000/instance/status" \+ -H "apikey: TOKEN-DA-INSTANCIA"+```++### 3. Tratamento de Erros+Sempre trate erros HTTP 4xx (validação) e 5xx (servidor):+- **400**: Erro de validação (campos obrigatórios faltando, formato inválido)+- **500**: Erro no servidor (instância desconectada, número inválido, etc)++Sempre verifique o status code da resposta e o campo `error` no JSON retornado.++### 4. Usar Webhooks+Para receber mensagens, configure webhooks em vez de polling:+```env+WEBHOOK_URL=https://seu-servidor.com/webhook+```++### 5. Gerenciar Mídias+Para áudio, configure conversor externo para melhor performance:+```env+API_AUDIO_CONVERTER=https://seu-conversor.com/convert+API_AUDIO_CONVERTER_KEY=sua-chave+```++---++## Próximos Passos++- [API de Usuários](./api-user.md) - Gerenciar perfil e contatos+- [API de Grupos](./api-groups.md) - Criar e administrar grupos+- [Sistema de Eventos](../recursos-avancados/events-system.md) - Receber webhooks+- [Referência Completa da API](../guias-api/api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-newsletter.md b/docs/wiki/guias-api/api-newsletter.mdnew file mode 100644index 0000000..6825ac4--- /dev/null+++ b/docs/wiki/guias-api/api-newsletter.md@@ -0,0 +1,593 @@+# API de Newsletters++Documentação dos endpoints para gerenciar Newsletters (Canais) do WhatsApp.++## 📋 Índice++- [Criar Newsletter](#criar-newsletter)+- [Listar Newsletters Inscritas](#listar-newsletters-inscritas)+- [Informações da Newsletter](#informações-da-newsletter)+- [Obter Newsletter por Link](#obter-newsletter-por-link)+- [Inscrever em Newsletter](#inscrever-em-newsletter)+- [Listar Mensagens](#listar-mensagens)++---++## O que são Newsletters?++**Newsletters** (também chamadas de **Canais**) são um recurso do WhatsApp para transmissão unidirecional de mensagens. Similar a um canal de broadcast.++**Características**:+- **Transmissão unidirecional**: Apenas admins postam, seguidores apenas leem+- **Sem limite de seguidores**: Diferente de grupos (1024) ou listas de transmissão (256)+- **Privacidade**: Seguidores não veem quem mais segue o canal+- **Reações**: Seguidores podem reagir às mensagens+- **Conteúdo público ou privado**: Configurável++---++## Criar Newsletter++Cria um novo canal (newsletter) no WhatsApp.++**Endpoint**: `POST /newsletter/create`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "name": "Notícias da Empresa",+ "description": "Canal oficial de comunicados e novidades"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `name` | string | ✅ Sim | Nome do canal |+| `description` | string | ❌ Não | Descrição do canal |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "ID": "120363XXXXXXXXXX@newsletter",+ "Name": "Notícias da Empresa",+ "Description": "Canal oficial de comunicados e novidades",+ "SubscriberCount": 0,+ "CreationTime": 1699000000,+ "Settings": {+ "ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"]+ },+ "ThreadMetadata": {+ "CreationTime": 1699000000+ }+ }+}+```++**Campos da Resposta**:+- `ID`: JID único do canal (formato @newsletter)+- `Name`: Nome do canal+- `Description`: Descrição+- `SubscriberCount`: Número de seguidores+- `Settings.ReactionCodes`: Reações permitidas++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/newsletter/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "name": "Canal de Ofertas",+ "description": "Promoções e ofertas exclusivas"+ }'+```++---++## Listar Newsletters Inscritas++Lista todos os canais que você está seguindo.++**Endpoint**: `GET /newsletter/list`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": [+ {+ "ID": "120363XXXXXXXXXX@newsletter",+ "Name": "Canal de Ofertas",+ "Description": "Promoções exclusivas",+ "SubscriberCount": 1523,+ "Role": "SUBSCRIBER",+ "Settings": {+ "ReactionCodes": ["👍", "❤️", "😂"]+ }+ },+ {+ "ID": "120363YYYYYYYYYY@newsletter",+ "Name": "Notícias Tech",+ "Description": "Últimas novidades em tecnologia",+ "SubscriberCount": 5420,+ "Role": "OWNER",+ "Settings": {+ "ReactionCodes": ["👍", "❤️"]+ }+ }+ ]+}+```++**Roles Possíveis**:+- `OWNER`: Você é o criador/dono do canal+- `ADMIN`: Você é administrador+- `SUBSCRIBER`: Você é apenas seguidor++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/newsletter/list \+ -H "apikey: SUA-CHAVE-API"+```++---++## Informações da Newsletter++Obtém informações detalhadas de um canal específico.++**Endpoint**: `POST /newsletter/info`++**Body**:+```json+{+ "jid": "120363XXXXXXXXXX@newsletter"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string (JID) | ✅ Sim | JID do canal |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "ID": "120363XXXXXXXXXX@newsletter",+ "State": "ACTIVE",+ "Name": "Canal de Ofertas",+ "Description": "Promoções exclusivas",+ "SubscriberCount": 1523,+ "VerificationState": "VERIFIED",+ "Role": "SUBSCRIBER",+ "Settings": {+ "ReactionCodes": ["👍", "❤️", "😂", "😮", "😢", "🙏"]+ },+ "ThreadMetadata": {+ "CreationTime": 1699000000+ },+ "ViewerMetadata": {+ "MuteState": "UNMUTED",+ "ViewerRole": "SUBSCRIBER"+ }+ }+}+```++**Campos Adicionais**:+- `State`: ACTIVE, SUSPENDED, GEOSUSPENDED+- `VerificationState`: VERIFIED (canal verificado) ou não+- `ViewerMetadata.MuteState`: MUTED ou UNMUTED++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/newsletter/info \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "120363XXXXXXXXXX@newsletter"+ }'+```++---++## Obter Newsletter por Link++Obtém informações de um canal através do link de convite.++**Endpoint**: `POST /newsletter/link`++**Body**:+```json+{+ "key": "ABC123XYZ"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `key` | string | ✅ Sim | Código do link de convite |++**Nota**: O `key` é a parte após `https://whatsapp.com/channel/` no link do canal.++**Exemplo de Link**:+```+https://whatsapp.com/channel/ABC123XYZ+ ↑+ Este é o key+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "ID": "120363XXXXXXXXXX@newsletter",+ "Name": "Canal Público",+ "Description": "Nosso canal oficial",+ "SubscriberCount": 2547,+ "VerificationState": "VERIFIED",+ "Settings": {+ "ReactionCodes": ["👍", "❤️"]+ }+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/newsletter/link \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "key": "ABC123XYZ"+ }'+```++---++## Inscrever em Newsletter++Inscreve-se (segue) um canal do WhatsApp.++**Endpoint**: `POST /newsletter/subscribe`++**Body**:+```json+{+ "jid": "120363XXXXXXXXXX@newsletter"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string (JID) | ✅ Sim | JID do canal |++**Nota**: Para obter o JID, primeiro use `/newsletter/link` com o código do convite.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/newsletter/subscribe \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "120363XXXXXXXXXX@newsletter"+ }'+```++---++## Listar Mensagens++Obtém mensagens de um canal.++**Endpoint**: `POST /newsletter/messages`++**Body**:+```json+{+ "jid": "120363XXXXXXXXXX@newsletter",+ "count": 20,+ "before_id": 0+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `jid` | string (JID) | ✅ Sim | JID do canal |+| `count` | int | ❌ Não | Número de mensagens (padrão: 20, máx: 100) |+| `before_id` | int | ❌ Não | ID da mensagem para paginação (0 = mais recentes) |++**Paginação**: Use o `ServerID` da última mensagem como `before_id` para buscar mensagens mais antigas.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": [+ {+ "MessageServerID": 12345,+ "ViewsCount": 1234,+ "Message": {+ "conversation": "Bem-vindos ao nosso canal!"+ },+ "ReactionCounts": {+ "👍": 45,+ "❤️": 89+ }+ },+ {+ "MessageServerID": 12344,+ "ViewsCount": 2156,+ "Message": {+ "imageMessage": {+ "url": "https://...",+ "caption": "Promoção imperdível!"+ }+ },+ "ReactionCounts": {+ "👍": 124,+ "😮": 23+ }+ }+ ]+}+```++**Campos da Resposta**:+- `MessageServerID`: ID único da mensagem+- `ViewsCount`: Número de visualizações+- `Message`: Conteúdo da mensagem (texto, imagem, etc)+- `ReactionCounts`: Contagem de cada reação++**Exemplo cURL**:+```bash+# Buscar últimas 20 mensagens+curl -X POST http://localhost:4000/newsletter/messages \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "120363XXXXXXXXXX@newsletter",+ "count": 20+ }'++# Buscar 20 mensagens anteriores (paginação)+curl -X POST http://localhost:4000/newsletter/messages \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "jid": "120363XXXXXXXXXX@newsletter",+ "count": 20,+ "before_id": 12340+ }'+```++---++## Fluxos Completos++### 1. Criar e Configurar Canal++```bash+# 1. Criar canal+NEWSLETTER_JID=$(curl -s -X POST http://localhost:4000/newsletter/create \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "name": "Ofertas Especiais",+ "description": "Promoções exclusivas para você"+ }' | jq -r '.data.ID')++echo "Canal criado: $NEWSLETTER_JID"++# 2. Obter informações+curl -X POST http://localhost:4000/newsletter/info \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d "{"jid": "$NEWSLETTER_JID"}"+```++### 2. Inscrever-se via Link++Para se inscrever em um canal usando um link de convite:++1. **Obter informações do canal**:+ - Use `POST /newsletter/link` com a `key` do convite+ - A resposta inclui nome, descrição, contador de seguidores e o JID do canal++2. **Inscrever-se**:+ - Use `POST /newsletter/subscribe` com o JID obtido+ - Se retornar status 200, a inscrição foi bem-sucedida++### 3. Ler Mensagens Recentes++Para buscar mensagens publicadas em um canal:++1. Use `POST /newsletter/messages` com:+ - `jid`: JID do canal+ - `count`: Quantas mensagens buscar (ex: 20)+ - `before_id`: ID da mensagem anterior (use 0 para as mais recentes)++2. A resposta inclui para cada mensagem:+ - `MessageServerID`: ID da mensagem+ - `ViewsCount`: Número de visualizações+ - `Message`: Conteúdo da mensagem+ - `ReactionCounts`: Contadores de reações por emoji++---++## Casos de Uso++### 1. Empresa / Marca++- **Lançamentos**: Anunciar novos produtos+- **Promoções**: Divulgar ofertas exclusivas+- **Novidades**: Comunicados corporativos+- **Blog**: Compartilhar artigos++### 2. Influencer / Criador de Conteúdo++- **Conteúdo exclusivo**: Posts para seguidores+- **Bastidores**: Fotos e vídeos dos bastidores+- **Anúncios**: Novos vídeos, lives, eventos++### 3. Mídia / Jornalismo++- **Notícias**: Breaking news+- **Análises**: Artigos de opinião+- **Entretenimento**: Conteúdo exclusivo++### 4. Educação++- **Dicas**: Conteúdo educativo+- **Aulas**: Links para aulas ao vivo+- **Materiais**: Compartilhar PDFs, links++---++## Enviar Mensagens no Canal++Para enviar mensagens no seu canal, use a **API de Mensagens** normal, passando o JID do canal:++```bash+curl -X POST http://localhost:4000/send/text \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "120363XXXXXXXXXX@newsletter",+ "text": "🔥 Promoção Relâmpago! 50% OFF em todos os produtos!"+ }'+```++Funciona com todos os tipos de mensagem:+- Texto+- Imagem+- Vídeo+- Documento+- Localização+- Poll (enquete)++---++## Limitações e Observações++### Permissões++- **Criar canal**: Qualquer usuário+- **Postar**: Apenas OWNER e ADMIN+- **Ver mensagens**: Todos os seguidores+- **Reagir**: Todos os seguidores (se permitido)++### Limitações do WhatsApp++| Aspecto | Limitação |+|---------|-----------|+| Número de seguidores | Ilimitado |+| Mensagens por dia | Não documentado |+| Tamanho da descrição | ~255 caracteres |+| Reações | Até 7 emojis configuráveis |++### Diferenças: Newsletter vs Grupo vs Lista++| Aspecto | Newsletter | Grupo | Lista de Transmissão |+|---------|-----------|-------|---------------------|+| Seguidores | Ilimitado | 1024 | 256 |+| Comunicação | Unidirecional | Bidirecional | Unidirecional |+| Privacidade | Anônimo | Todos veem todos | Anônimo |+| Reações | Sim | Sim | Não |+| Respostas | Não | Sim | Sim (privado) |++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `name is required` | Forneça o nome do canal |+| 400 | `jid is required` | Forneça o JID do canal |+| 400 | `key is required` | Forneça o código do link |+| 500 | `instance not found` | Instância não conectada |+| 500 | `error create newsletter` | Falha ao criar (tente nome diferente) |+| 500 | `error list newsletter` | Falha ao buscar canais |++---++## Boas Práticas++### 1. Nome e Descrição Claros++```json+{+ "name": "Tech News Daily",+ "description": "Últimas notícias de tecnologia todos os dias às 9h"+}+```++### 2. Consistência de Postagens++- Defina frequência (diária, semanal)+- Mantenha horários regulares+- Avise se houver pausas++### 3. Conteúdo de Qualidade++- Textos concisos+- Imagens de alta qualidade+- Informações relevantes+- Evite spam++### 4. Engajamento++- Use enquetes+- Permita reações relevantes+- Responda dúvidas (em outros canais)++### 5. Divulgação++Compartilhe o link do canal:+```+https://whatsapp.com/channel/ABC123XYZ+```++---++## Próximos Passos++- [API de Mensagens](./api-messages.md) - Enviar conteúdo no canal+- [API de Grupos](./api-groups.md) - Comparar com grupos+- [API de Comunidades](./api-community.md) - Organizar múltiplos canais+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/guias-api/api-overview.md b/docs/wiki/guias-api/api-overview.mdnew file mode 100644index 0000000..978644d--- /dev/null+++ b/docs/wiki/guias-api/api-overview.md@@ -0,0 +1,342 @@+# Visão Geral da API++Guia completo para usar a API REST do Evolution GO.++## Base URL++```+http://localhost:4000+```++## Autenticação++Todas as requisições precisam do header `apikey`:++```bash+curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint+```++**Tipos de API Key**:+- **GLOBAL_API_KEY**: Configurada na variável de ambiente, usada para operações administrativas (criar/deletar instâncias)+- **Token da Instância**: Definido ao criar a instância, usado para operações da instância (enviar mensagens, conectar, etc)++## Formato das Requisições++### Content-Type++```+Content-Type: application/json+```++### Exemplo de Requisição++```bash+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: GLOBAL_API_KEY" \+ -d '{+ "name": "teste",+ "token": "token-teste-123"+ }'+```++## Formato das Respostas++### Sucesso (HTTP 200/201)++```json+{+ "message": "success",+ "data": {+ "id": "uuid-abc-123",+ "name": "teste",+ "token": "token-teste-123",+ "connected": false+ }+}+```++### Erro (HTTP 4xx/5xx)++```json+{+ "error": "Instance not found",+ "message": "A instância especificada não existe"+}+```++## Códigos de Status HTTP++| Código | Significado |+|--------|-------------|+| 200 | OK - Requisição bem-sucedida |+| 201 | Created - Recurso criado com sucesso |+| 400 | Bad Request - Dados inválidos |+| 401 | Unauthorized - API key inválida |+| 404 | Not Found - Recurso não encontrado |+| 500 | Internal Server Error - Erro no servidor |++## Estrutura da API++A API está organizada em módulos:++### Instâncias+Gerenciar conexões WhatsApp+- `POST /instance/create` - Criar instância+- `POST /instance/connect` - Conectar via QR Code+- `GET /instance/status` - Ver status+- `DELETE /instance/delete/:id` - Deletar++### Mensagens+Enviar e gerenciar mensagens+- `POST /send/text` - Texto simples+- `POST /send/link` - Link com preview+- `POST /send/media` - Mídia (imagem, vídeo, áudio, documento)+- `POST /send/sticker` - Sticker/figurinha+- `POST /send/location` - Localização+- `POST /send/contact` - Contato+- `POST /send/poll` - Enquete+- `POST /send/button` - Botões interativos+- `POST /send/list` - Lista de opções++### Gerenciar Mensagens+Interagir com mensagens enviadas/recebidas+- `POST /message/react` - Reagir a mensagem+- `POST /message/markread` - Marcar como lida+- `POST /message/delete` - Deletar para todos+- `POST /message/edit` - Editar mensagem+- `POST /message/presence` - Definir presença (digitando, gravando)+- `POST /message/downloadmedia` - Baixar mídia+- `POST /message/status` - Ver status de entrega++### Usuários+Gerenciar perfil e contatos+- `POST /user/info` - Informações do usuário+- `POST /user/check` - Verificar se número existe+- `POST /user/avatar` - Obter avatar+- `GET /user/contacts` - Listar contatos+- `GET /user/privacy` - Ver configurações de privacidade+- `POST /user/privacy` - Configurar privacidade+- `POST /user/block` - Bloquear contato+- `POST /user/unblock` - Desbloquear contato+- `GET /user/blocklist` - Ver lista de bloqueados+- `POST /user/profilePicture` - Alterar foto de perfil+- `POST /user/profileName` - Alterar nome+- `POST /user/profileStatus` - Alterar status/recado++### Grupos+Gerenciar grupos WhatsApp+- `GET /group/list` - Listar todos os grupos+- `POST /group/create` - Criar grupo+- `POST /group/info` - Informações do grupo+- `POST /group/invitelink` - Obter link de convite+- `POST /group/photo` - Alterar foto do grupo+- `POST /group/name` - Alterar nome+- `POST /group/description` - Alterar descrição+- `POST /group/participant` - Gerenciar participantes (adicionar/remover/promover)+- `POST /group/join` - Entrar via link+- `POST /group/leave` - Sair do grupo++### Chats+Gerenciar conversas+- `POST /chat/pin` - Fixar conversa+- `POST /chat/unpin` - Desfixar conversa+- `POST /chat/archive` - Arquivar conversa+- `POST /chat/unarchive` - Desarquivar+- `POST /chat/mute` - Silenciar notificações+- `POST /chat/unmute` - Reativar notificações+- `POST /chat/history-sync` - Solicitar sincronização de histórico++### Labels (Etiquetas)+Organizar conversas com etiquetas+- `POST /label/chat` - Adicionar etiqueta a chat+- `POST /label/message` - Adicionar etiqueta a mensagem+- `POST /label/edit` - Criar/editar etiqueta+- `GET /label/list` - Listar todas as etiquetas+- `POST /unlabel/chat` - Remover etiqueta de chat+- `POST /unlabel/message` - Remover etiqueta de mensagem++### Chamadas+Gerenciar chamadas+- `POST /call/reject` - Rejeitar chamada++### Newsletter (Canais)+Gerenciar newsletters/canais+- `POST /newsletter/create` - Criar newsletter+- `GET /newsletter/list` - Listar newsletters+- `POST /newsletter/info` - Informações da newsletter+- `POST /newsletter/link` - Obter link de convite+- `POST /newsletter/subscribe` - Inscrever-se+- `POST /newsletter/messages` - Ver mensagens++### Community (Comunidades)+Gerenciar comunidades+- `POST /community/create` - Criar comunidade+- `POST /community/add` - Adicionar grupo à comunidade+- `POST /community/remove` - Remover grupo da comunidade++## Parâmetros Comuns++### number+Número do WhatsApp (DDI + DDD + Número)+- Formato: Apenas dígitos+- Exemplo: `"5511999999999"` (Brasil)+- Exemplo: `"1234567890"` (EUA)++## Formato de Números++### Número Individual+```json+{+ "number": "5511999999999"+}+```++### Grupo+```json+{+ "number": "[email protected]"+}+```++O Evolution GO formata automaticamente números quando necessário.++## Paginação++Endpoints que retornam listas suportam paginação:++```bash+GET /endpoint?page=1&limit=50+```++## WebSocket++Para receber eventos em tempo real via WebSocket:++```+ws://localhost:4000/ws?token=SUA-CHAVE-API&instanceId=minha-instancia+```++## Webhooks++Configure webhooks via variável de ambiente:++```env+WEBHOOK_URL=https://seu-servidor.com/webhook+```++Eventos serão enviados via POST para a URL configurada.++## Rate Limiting++Atualmente não há rate limiting configurado, mas é recomendado:+- Máximo 50 requisições por segundo por instância+- Aguarde resposta antes de enviar próxima mensagem++## Swagger/OpenAPI++Documentação interativa disponível em:++```+http://localhost:4000/swagger/index.html+```++Recursos do Swagger:+- Testar endpoints diretamente+- Ver todos os parâmetros+- Exemplos de request/response+- Autenticação integrada++## Exemplos Práticos++### Criar e Conectar Instância++```bash+# 1. Criar instância (usa GLOBAL_API_KEY)+curl -X POST http://localhost:4000/instance/create \+ -H "Content-Type: application/json" \+ -H "apikey: GLOBAL_API_KEY" \+ -d '{+ "name": "vendas",+ "token": "token-vendas-123"+ }'++# 2. Conectar (usa token da instância)+curl -X POST http://localhost:4000/instance/connect \+ -H "Content-Type: application/json" \+ -H "apikey: token-vendas-123" \+ -d '{+ "webhookUrl": "https://meu-servidor.com/webhook"+ }'++# 3. Ver QR Code (usa token da instância)+curl -X GET http://localhost:4000/instance/qr \+ -H "apikey: token-vendas-123"+```++### Enviar Mensagem com Mídia++```bash+curl -X POST http://localhost:4000/send/media \+ -H "Content-Type: application/json" \+ -H "apikey: token-vendas-123" \+ -d '{+ "number": "5511999999999",+ "url": "https://exemplo.com/produto.jpg",+ "type": "image",+ "caption": "Confira nosso produto!"+ }'+```++### Criar Grupo++```bash+curl -X POST http://localhost:4000/group/create \+ -H "Content-Type: application/json" \+ -H "apikey: token-vendas-123" \+ -d '{+ "name": "Equipe de Vendas",+ "participants": ["5511999999999", "5511888888888"]+ }'+```++## Boas Práticas++### 1. Validar Números+Use `/user/check` para verificar se número existe no WhatsApp++### 2. Gerenciar Erros+Sempre trate erros HTTP 4xx e 5xx++### 3. Usar Webhooks+Para receber mensagens, configure webhooks em vez de polling++### 4. Múltiplas Instâncias+Use uma instância por número WhatsApp++### 5. Logs+Configure logs adequadamente para debug++## Troubleshooting++### Erro 401 Unauthorized+Verifique se a `apikey` está correta++### Erro 404 Instance not found+Certifique-se de que criou a instância primeiro++### Mensagem não enviada+1. Verifique status da conexão+2. Confirme formato do número+3. Verifique se número existe no WhatsApp++## Próximos Passos++- [API de Instâncias](./api-instances.md) - Gerenciar instâncias+- [API de Mensagens](./api-messages.md) - Enviar mensagens+- [API de Grupos](./api-groups.md) - Gerenciar grupos+- [Sistema de Eventos](../recursos-avancados/events-system.md) - Webhooks e eventos++---++**Dica**: Use o Swagger para explorar todos os endpoints disponíveis!diff --git a/docs/wiki/guias-api/api-user.md b/docs/wiki/guias-api/api-user.mdnew file mode 100644index 0000000..748b301--- /dev/null+++ b/docs/wiki/guias-api/api-user.md@@ -0,0 +1,755 @@+# API de Usuários++Documentação completa dos endpoints para gerenciar perfil, contatos e privacidade.++## 📋 Índice++- [Informações do Usuário](#informações-do-usuário)+- [Verificar Usuário no WhatsApp](#verificar-usuário-no-whatsapp)+- [Avatar do Usuário](#avatar-do-usuário)+- [Listar Contatos](#listar-contatos)+- [Privacidade](#privacidade)+ - [Consultar Privacidade](#consultar-privacidade)+ - [Configurar Privacidade](#configurar-privacidade)+- [Bloqueio de Contatos](#bloqueio-de-contatos)+ - [Bloquear Contato](#bloquear-contato)+ - [Desbloquear Contato](#desbloquear-contato)+ - [Listar Bloqueados](#listar-bloqueados)+- [Perfil](#perfil)+ - [Alterar Foto de Perfil](#alterar-foto-de-perfil)+ - [Alterar Nome](#alterar-nome)+ - [Alterar Status/Recado](#alterar-statusrecado)++---++## Informações do Usuário++Obtém informações detalhadas de um ou mais usuários WhatsApp.++**Endpoint**: `POST /user/info`++**Headers**:+```+Content-Type: application/json+apikey: SUA-CHAVE-API+```++**Body**:+```json+{+ "number": ["5511999999999", "5511888888888"]+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | array | ✅ Sim | Array de números a consultar |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Users": {+ "[email protected]": {+ "VerifiedName": {+ "Certificate": {...},+ "Details": {+ "Serial": 123,+ "Issuer": "WhatsApp",+ "VerifiedName": "Empresa Verificada LTDA"+ }+ },+ "Status": "Olá! Estou usando WhatsApp.",+ "PictureID": "abc123",+ "Devices": ["5511999999999.0:[email protected]"],+ "LID": "lid_string"+ }+ }+ }+}+```++**Campos da Resposta**:+- `VerifiedName`: Nome verificado (empresas) ou null+- `Status`: Recado/status do usuário+- `PictureID`: ID da foto de perfil+- `Devices`: Lista de dispositivos conectados+- `LID`: Local ID (se disponível)++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/info \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": ["5511999999999"]+ }'+```++---++## Verificar Usuário no WhatsApp++Verifica se um número existe no WhatsApp e retorna o JID correto para mensagens.++**Endpoint**: `POST /user/check`++**Body**:+```json+{+ "number": ["5511999999999", "11999999999", "+55 11 99999-9999"],+ "formatJid": false+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | array | ✅ Sim | Array de números em qualquer formato |+| `formatJid` | bool | ❌ Não | Formatar número (padrão: false) |++**Nota Importante**: Por padrão, `formatJid=false` para verificação. O sistema tenta automaticamente ambos os formatos se o primeiro falhar.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "Users": [+ {+ "Query": "5511999999999",+ "IsInWhatsapp": true,+ "JID": "[email protected]",+ "RemoteJID": "[email protected]",+ "LID": "lid_string",+ "VerifiedName": "Empresa LTDA"+ },+ {+ "Query": "5511888888888",+ "IsInWhatsapp": false,+ "JID": "",+ "RemoteJID": "5511888888888",+ "LID": null,+ "VerifiedName": ""+ }+ ]+ }+}+```++**Campos da Resposta**:+- `Query`: Número original consultado+- `IsInWhatsapp`: Se existe no WhatsApp+- `JID`: JID do usuário (vazio se não existe)+- `RemoteJID`: JID recomendado para envio de mensagens+- `LID`: Local ID+- `VerifiedName`: Nome verificado (empresas)++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/check \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": ["5511999999999", "11888888888"]+ }'+```++---++## Avatar do Usuário++Obtém a URL da foto de perfil de um usuário.++**Endpoint**: `POST /user/avatar`++**Body**:+```json+{+ "number": "5511999999999",+ "preview": false+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do usuário |+| `preview` | bool | ❌ Não | Se true, retorna preview (menor resolução) |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "URL": "https://pps.whatsapp.net/v/...",+ "ID": "abc123",+ "Type": "image",+ "DirectPath": "/v/..."+ }+}+```++**Resposta de Erro (500)**:+```json+{+ "error": "no profile picture found"+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/avatar \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999",+ "preview": true+ }'+```++---++## Listar Contatos++Obtém todos os contatos salvos na conta WhatsApp.++**Endpoint**: `GET /user/contacts`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": [+ {+ "Jid": "[email protected]",+ "Found": true,+ "FirstName": "João",+ "FullName": "João Silva",+ "PushName": "João",+ "BusinessName": ""+ },+ {+ "Jid": "[email protected]",+ "Found": true,+ "FirstName": "Maria",+ "FullName": "Maria Santos",+ "PushName": "Maria",+ "BusinessName": "Loja da Maria"+ }+ ]+}+```++**Campos da Resposta**:+- `Jid`: JID do contato+- `Found`: Se foi encontrado no WhatsApp+- `FirstName`: Primeiro nome+- `FullName`: Nome completo+- `PushName`: Nome exibido no WhatsApp+- `BusinessName`: Nome da empresa (se for conta comercial)++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/user/contacts \+ -H "apikey: SUA-CHAVE-API"+```++---++## Privacidade++### Consultar Privacidade++Obtém as configurações atuais de privacidade da conta.++**Endpoint**: `GET /user/privacy`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "GroupAdd": "all",+ "LastSeen": "contacts",+ "Status": "contacts",+ "Profile": "all",+ "ReadReceipts": "all",+ "CallAdd": "all",+ "Online": "all"+ }+}+```++**Valores Possíveis**:+- `all` - Todos+- `contacts` - Apenas contatos+- `contact_blacklist` - Meus contatos exceto...+- `none` - Ninguém+- `match_last_seen` - Mesmo de "Visto por último"++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/user/privacy \+ -H "apikey: SUA-CHAVE-API"+```++---++### Configurar Privacidade++Define as configurações de privacidade da conta.++**Endpoint**: `POST /user/privacy`++**Body**:+```json+{+ "groupAdd": "contacts",+ "lastSeen": "contacts",+ "status": "contacts",+ "profile": "all",+ "readReceipts": "all",+ "callAdd": "all",+ "online": "all"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `groupAdd` | string | ✅ Sim | Quem pode me adicionar em grupos |+| `lastSeen` | string | ✅ Sim | Quem vê meu "visto por último" |+| `status` | string | ✅ Sim | Quem vê meu recado/status |+| `profile` | string | ✅ Sim | Quem vê minha foto de perfil |+| `readReceipts` | string | ✅ Sim | Confirmações de leitura |+| `callAdd` | string | ✅ Sim | Quem pode me ligar |+| `online` | string | ✅ Sim | Quem vê quando estou online |++**Valores Permitidos**: `all`, `contacts`, `contact_blacklist`, `none`, `match_last_seen`++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "GroupAdd": "contacts",+ "LastSeen": "contacts",+ "Status": "contacts",+ "Profile": "all",+ "ReadReceipts": "all",+ "CallAdd": "all",+ "Online": "all"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/privacy \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupAdd": "contacts",+ "lastSeen": "contacts",+ "status": "contacts",+ "profile": "all",+ "readReceipts": "all",+ "callAdd": "all",+ "online": "all"+ }'+```++---++## Bloqueio de Contatos++### Bloquear Contato++Bloqueia um contato no WhatsApp.++**Endpoint**: `POST /user/block`++**Body**:+```json+{+ "number": "5511999999999"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do contato a bloquear |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "DHash": "abc123",+ "PrevDHash": "def456",+ "Modifications": [+ {+ "JID": "[email protected]",+ "Action": "block"+ }+ ]+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/block \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999"+ }'+```++---++### Desbloquear Contato++Desbloqueia um contato previamente bloqueado.++**Endpoint**: `POST /user/unblock`++**Body**:+```json+{+ "number": "5511999999999"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `number` | string | ✅ Sim | Número do contato a desbloquear |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "DHash": "abc123",+ "PrevDHash": "def456",+ "Modifications": [+ {+ "JID": "[email protected]",+ "Action": "unblock"+ }+ ]+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/unblock \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "5511999999999"+ }'+```++---++### Listar Bloqueados++Obtém a lista de todos os contatos bloqueados.++**Endpoint**: `GET /user/blocklist`++**Headers**:+```+apikey: SUA-CHAVE-API+```++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "DHash": "abc123",+ "Modifications": [+ {+ "JID": "[email protected]",+ "Action": "block"+ },+ {+ "JID": "[email protected]",+ "Action": "block"+ }+ ]+ }+}+```++**Exemplo cURL**:+```bash+curl -X GET http://localhost:4000/user/blocklist \+ -H "apikey: SUA-CHAVE-API"+```++---++## Perfil++### Alterar Foto de Perfil++Define a foto de perfil da conta WhatsApp.++**Endpoint**: `POST /user/profilePicture`++**Body**:+```json+{+ "image": "https://exemplo.com/foto.jpg"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `image` | string | ✅ Sim | URL da imagem |++**Nota**: A imagem deve ser acessível via HTTP/HTTPS. Formatos aceitos: JPG, PNG.++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "image": "https://exemplo.com/foto.jpg"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/profilePicture \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "image": "https://exemplo.com/minha-foto.jpg"+ }'+```++---++### Alterar Nome++Define o nome de exibição da conta WhatsApp.++**Endpoint**: `POST /user/profileName`++**Body**:+```json+{+ "name": "João Silva"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `name` | string | ✅ Sim | Novo nome de exibição |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "name": "João Silva"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/profileName \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "name": "Meu Novo Nome"+ }'+```++---++### Alterar Status/Recado++Define o recado (status) da conta WhatsApp.++**Endpoint**: `POST /user/profileStatus`++**Body**:+```json+{+ "status": "Disponível para atendimento 24h!"+}+```++**Parâmetros**:++| Campo | Tipo | Obrigatório | Descrição |+|-------|------|-------------|-----------|+| `status` | string | ✅ Sim | Novo recado/status |++**Resposta de Sucesso (200)**:+```json+{+ "message": "success",+ "data": {+ "status": "Disponível para atendimento 24h!"+ }+}+```++**Exemplo cURL**:+```bash+curl -X POST http://localhost:4000/user/profileStatus \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "status": "Olá! Como posso ajudar?"+ }'+```++---++## Casos de Uso Comuns++### Validar Números Antes de Enviar++Sempre verifique se o número existe antes de tentar enviar mensagem:++```bash+# 1. Verificar número+curl -X POST http://localhost:4000/user/check \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": ["5511999999999"]+ }'++# 2. Se IsInWhatsapp=true, use RemoteJID para enviar+curl -X POST http://localhost:4000/send/text \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "number": "[email protected]",+ "text": "Olá!",+ "formatJid": false+ }'+```++### Configurar Privacidade Máxima++```bash+curl -X POST http://localhost:4000/user/privacy \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{+ "groupAdd": "contacts",+ "lastSeen": "none",+ "status": "contacts",+ "profile": "contacts",+ "readReceipts": "all",+ "callAdd": "contacts",+ "online": "none"+ }'+```++### Personalizar Perfil Completo++```bash+# 1. Foto de perfil+curl -X POST http://localhost:4000/user/profilePicture \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"image": "https://exemplo.com/logo.jpg"}'++# 2. Nome+curl -X POST http://localhost:4000/user/profileName \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"name": "Empresa LTDA"}'++# 3. Status+curl -X POST http://localhost:4000/user/profileStatus \+ -H "Content-Type: application/json" \+ -H "apikey: SUA-CHAVE-API" \+ -d '{"status": "Atendimento 24h - (11) 99999-9999"}'+```++---++## Códigos de Erro Comuns++| Código | Erro | Solução |+|--------|------|---------|+| 400 | `phone number is required` | Forneça o campo `number` |+| 400 | `image is required` | Forneça uma URL de imagem válida |+| 500 | `instance not found` | Instância não conectada |+| 500 | `no profile picture found` | Usuário não tem foto de perfil |+| 500 | `invalid phone number` | Formato de número inválido |++---++## Boas Práticas++### 1. Cache de Verificações+Evite verificar o mesmo número múltiplas vezes. Implemente um sistema de cache na sua aplicação:+- Armazene o resultado da verificação por algumas horas+- Antes de chamar a API, verifique se já tem o resultado em cache+- Isso reduz requisições desnecessárias e melhora a performance++### 2. Privacidade Responsável+Configure privacidade adequada para contas comerciais:+- `readReceipts: all` - Envie confirmações de leitura+- `online: contacts` - Evite mostrar online para todos+- `groupAdd: contacts` - Evite spam de grupos++### 3. Validação de Imagens+Ao alterar foto de perfil, certifique-se que a imagem:+- Está acessível publicamente (HTTP/HTTPS)+- É JPG ou PNG+- Tem tamanho adequado (recomendado: 640x640px)++---++## Próximos Passos++- [API de Mensagens](./api-messages.md) - Enviar e gerenciar mensagens+- [API de Grupos](./api-groups.md) - Gerenciar grupos WhatsApp+- [API de Chats](./api-chats.md) - Gerenciar conversas+- [Visão Geral da API](./api-overview.md)++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/recursos-avancados/events-system.md b/docs/wiki/recursos-avancados/events-system.mdnew file mode 100644index 0000000..ef65300--- /dev/null+++ b/docs/wiki/recursos-avancados/events-system.md@@ -0,0 +1,1046 @@+# Sistema de Eventos++Sistema completo de notificações em tempo real do Evolution GO. Receba eventos do WhatsApp através de múltiplos canais: Webhooks, RabbitMQ, NATS e WebSocket.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Canais Disponíveis](#canais-disponíveis)+- [Webhook](#webhook)+- [RabbitMQ](#rabbitmq)+- [NATS](#nats)+- [WebSocket](#websocket)+- [Configuração](#configuração)+- [Tipos de Eventos](#tipos-de-eventos)+- [Formato de Payload](#formato-de-payload)+- [Múltiplos Canais Simultâneos](#múltiplos-canais-simultâneos)+- [Exemplos Práticos](#exemplos-práticos)++---++## Visão Geral++O Evolution GO envia notificações de eventos do WhatsApp em tempo real através de diferentes canais de comunicação:++- **Webhook (HTTP POST)**: Ideal para integração simples com APIs externas+- **RabbitMQ (AMQP)**: Message broker para arquiteturas empresariais e filas confiáveis+- **NATS**: Message broker leve para comunicação de alta performance+- **WebSocket**: Conexão persistente para dashboards e aplicações web++Você pode ativar múltiplos canais simultaneamente - os eventos serão enviados para todos os canais configurados.++### Arquitetura++```+┌─────────────────────────────────────────────────────────┐+│ WhatsApp Event │+│ (mensagem recebida) │+└────────────────────┬────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────┐+│ Whatsmeow Event Handler │+│ (detecta evento do WhatsApp) │+└────────────────────┬────────────────────────────────────┘+ │+ ▼+┌─────────────────────────────────────────────────────────┐+│ Event Router/Dispatcher │+│ (filtra eventos subscritos) │+└─────┬──────┬──────┬──────┬────────────────────────────┘+ │ │ │ │+ │ │ │ │+ ▼ ▼ ▼ ▼+ ┌────┐ ┌────┐ ┌────┐ ┌─────┐+ │Web │ │AMQP│ │NATS│ │Web │+ │hook│ │MQ │ │ │ │Socket│+ └─┬──┘ └─┬──┘ └─┬──┘ └──┬──┘+ │ │ │ │+ │ │ │ │+ ▼ ▼ ▼ ▼+ ┌────┐ ┌────┐ ┌────┐ ┌─────┐+ │HTTP│ │Queue│ │Topic│ │WS │+ │POST│ │ │ │ │ │Conn │+ └────┘ └────┘ └────┘ └─────┘+```++---++## Canais Disponíveis++### Comparação de Canais++| Produtor | Latência | Throughput | Persistência | Complexidade | Caso de Uso |+|----------|----------|------------|--------------|--------------|-------------|+| **Webhook** | Baixa | Média | Não | Baixa | Integração simples com APIs |+| **RabbitMQ** | Média | Alta | Sim | Alta | Arquiteturas distribuídas, filas |+| **NATS** | Muito Baixa | Muito Alta | Opcional | Média | Real-time, pub/sub, microserviços |+| **WebSocket** | Muito Baixa | Alta | Não | Média | Aplicações web, dashboards |++---++## Webhook++### Visão Geral++Envia eventos via HTTP POST para uma URL que você configurar. É o método mais simples para integrar o Evolution GO com suas aplicações.++### Características++- **Retry automático**: 5 tentativas com intervalo de 30 segundos entre cada tentativa+- **Timeout**: Configurável+- **Content-Type**: `application/json`+- **Método**: HTTP POST++### Configuração++**Variáveis de Ambiente**:+```env+# Webhook global (recebe eventos de todas as instâncias)+WEBHOOK_URL=https://meu-servidor.com/webhook+```++**Por instância** (via Connect):+```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "apikey: token-da-instancia" \+ -H "Content-Type: application/json" \+ -d '{+ "webhookUrl": "https://meu-servidor.com/webhook-vendas",+ "subscribe": ["MESSAGE", "READ_RECEIPT", "GROUP", "CALL"],+ "rabbitmqEnabled": "disabled",+ "websocketEnable": "disabled",+ "natsEnabled": "disabled"+ }'+```++> **Nota**: A instância é identificada pelo token no header `apikey`, não por `instanceName` no body.++### Funcionamento++Quando um evento ocorre no WhatsApp:++1. **Webhook Global**: Se configurado via `WEBHOOK_URL`, todos os eventos são enviados para esta URL+2. **Webhook por Instância**: Se configurado no `POST /instance/connect`, eventos daquela instância vão para a URL específica+3. **Retry Automático**: Se a requisição falhar, o Evolution GO tenta novamente até 5 vezes+4. **Intervalo**: 30 segundos entre cada tentativa++### Requisição HTTP++**Headers**:+```+POST /webhook HTTP/1.1+Host: meu-servidor.com+Content-Type: application/json+```++**Body**:+```json+{+ "event": "MESSAGE",+ "instance": "vendas",+ "data": {+ "key": {+ "remoteJid": "[email protected]",+ "fromMe": false,+ "id": "3EB0C5A277F7F9B6C599"+ },+ "message": {+ "conversation": "Olá!"+ },+ "messageTimestamp": "1699999999"+ }+}+```++### Implementação no Servidor Receptor++**Node.js (Express)**:+```javascript+const express = require('express');+const app = express();++app.use(express.json());++app.post('/webhook', (req, res) => {+ const { event, instance, data } = req.body;++ console.log(`Evento recebido: ${event} da instância ${instance}`);+ console.log('Dados:', JSON.stringify(data, null, 2));++ // Processa evento+ if (event === 'MESSAGE') {+ const message = data.message.conversation;+ const from = data.key.remoteJid;+ console.log(`Mensagem de ${from}: ${message}`);+ }++ // IMPORTANTE: Retorne 200 OK rapidamente+ res.status(200).json({ received: true });+});++app.listen(3000, () => console.log('Webhook server rodando na porta 3000'));+```++**Python (Flask)**:+```python+from flask import Flask, request, jsonify++app = Flask(__name__)+[email protected]('/webhook', methods=['POST'])+def webhook():+ data = request.json+ event = data.get('event')+ instance = data.get('instance')+ payload = data.get('data')++ print(f"Evento recebido: {event} da instância {instance}")++ if event == 'MESSAGE':+ message = payload.get('message', {}).get('conversation')+ from_jid = payload.get('key', {}).get('remoteJid')+ print(f"Mensagem de {from_jid}: {message}")++ return jsonify({'received': True}), 200++if __name__ == '__main__':+ app.run(port=3000)+```++---++## RabbitMQ++### Visão Geral++Publica eventos em filas RabbitMQ (AMQP). Ideal para arquiteturas distribuídas que precisam de filas confiáveis e persistentes.++### Características++- **Filas duráveis**: Mensagens não se perdem mesmo após reinicialização do servidor+- **Alta disponibilidade**: Replicação automática entre nós+- **Retry automático**: 3 tentativas com intervalo crescente+- **Confirmações de entrega**: Garantia de que a mensagem foi recebida+- **Heartbeat**: Monitoramento de conexão a cada 30 segundos+- **Reconexão automática**: Reconecta automaticamente em caso de falha++### Configuração++**Variáveis de Ambiente**:+```env+# URL de conexão RabbitMQ+AMQP_URL=amqp://user:password@localhost:5672/++# Habilitar RabbitMQ global+AMQP_GLOBAL_ENABLED=true++# Eventos globais (modo fallback)+AMQP_GLOBAL_EVENTS=MESSAGE,SEND_MESSAGE,GROUP,CALL++# Eventos específicos (prioridade sobre global)+AMQP_SPECIFIC_EVENTS=message,sendmessage,groupinfo,calloffer+```++### Tipos de Filas++#### Modo 1: AMQP_SPECIFIC_EVENTS (Recomendado)++Cria filas específicas para eventos exatos:++```env+AMQP_SPECIFIC_EVENTS=message,sendmessage,receipt,presence+```++**Filas criadas**:+- `message` - Mensagens recebidas+- `sendmessage` - Mensagens enviadas+- `receipt` - Confirmações de leitura+- `presence` - Status online/offline++#### Modo 2: AMQP_GLOBAL_EVENTS (Fallback)++Mapeia eventos globais para múltiplas filas:++```env+AMQP_GLOBAL_EVENTS=MESSAGE,CALL,CONNECTION+```++**Mapeamento de Eventos**:+- `MESSAGE` → fila `message`+- `SEND_MESSAGE` → fila `sendmessage`+- `READ_RECEIPT` → fila `receipt`+- `PRESENCE` → fila `presence`+- `CALL` → filas `calloffer`, `callaccept`, `callterminate`+- `CONNECTION` → filas `connected`, `disconnected`, `loggedout`+- `GROUP` → filas `groupinfo`, `joinedgroup`+- `QRCODE` → filas `qrcode`, `qrtimeout`, `qrsuccess`++### Propriedades das Filas++As filas RabbitMQ criadas pelo Evolution GO são configuradas com:++- **Quorum queues**: Replicação automática para alta disponibilidade+- **Durabilidade**: Mensagens persistem após restart do servidor+- **Persistência**: Todas as mensagens são marcadas como persistentes++### Consumindo Mensagens++**Go (amqp091-go)**:+```go+package main++import (+ "fmt"+ "log"+ amqp "github.com/rabbitmq/amqp091-go"+)++func main() {+ conn, err := amqp.Dial("amqp://user:password@localhost:5672/")+ if err != nil {+ log.Fatal(err)+ }+ defer conn.Close()++ ch, err := conn.Channel()+ if err != nil {+ log.Fatal(err)+ }+ defer ch.Close()++ msgs, err := ch.Consume(+ "message", // queue+ "", // consumer+ true, // auto-ack+ false, // exclusive+ false, // no-local+ false, // no-wait+ nil, // args+ )+ if err != nil {+ log.Fatal(err)+ }++ forever := make(chan bool)++ go func() {+ for d := range msgs {+ fmt.Printf("Recebido: %s+", d.Body)+ }+ }()++ fmt.Println("Aguardando mensagens...")+ <-forever+}+```++**Python (pika)**:+```python+import pika+import json++connection = pika.BlockingConnection(+ pika.ConnectionParameters('localhost'))+channel = connection.channel()++def callback(ch, method, properties, body):+ data = json.loads(body)+ print(f"Evento recebido: {data}")++ if data.get('event') == 'MESSAGE':+ message = data.get('data', {}).get('message', {}).get('conversation')+ print(f"Mensagem: {message}")++channel.basic_consume(queue='message', on_message_callback=callback, auto_ack=True)++print('Aguardando mensagens...')+channel.start_consuming()+```++---++## NATS++### Visão Geral++Publica eventos em tópicos NATS. Ideal para comunicação em tempo real com latência mínima.++### Características++- **Latência ultra-baixa**: Comunicação extremamente rápida+- **Pub/Sub nativo**: Vários consumidores podem receber o mesmo evento+- **Leve e rápido**: Menor overhead que RabbitMQ+- **Clustering**: Suporte nativo a clusters distribuídos++### Configuração++```env+# URL de conexão NATS+NATS_URL=nats://localhost:4222++# Habilitar NATS+NATS_ENABLED=true+```++### Tópicos++Eventos são publicados em tópicos no formato:++```+evolution.{instance}.{event_type}+```++**Exemplos**:+- `evolution.vendas.message` - Mensagens da instância "vendas"+- `evolution.suporte.calloffer` - Chamadas da instância "suporte"+- `evolution.*.message` - Mensagens de todas as instâncias (wildcard)++### Consumindo Eventos++**Go (nats.go)**:+```go+package main++import (+ "fmt"+ "log"+ "github.com/nats-io/nats.go"+)++func main() {+ nc, err := nats.Connect("nats://localhost:4222")+ if err != nil {+ log.Fatal(err)+ }+ defer nc.Close()++ // Subscrever a eventos de mensagens de todas as instâncias+ sub, err := nc.Subscribe("evolution.*.message", func(m *nats.Msg) {+ fmt.Printf("Recebido no tópico %s: %s+", m.Subject, string(m.Data))+ })+ if err != nil {+ log.Fatal(err)+ }+ defer sub.Unsubscribe()++ // Manter rodando+ select {}+}+```++---++## WebSocket++### Visão Geral++Envia eventos através de uma conexão WebSocket persistente. Ideal para dashboards e aplicações web que precisam de atualizações em tempo real.++### Características++- **Conexão bidirecional**: Comunicação em duas vias+- **Baixa latência**: Perfeito para interfaces em tempo real+- **Gerenciamento seguro**: Múltiplas conexões simultâneas+- **Dois modos**: Broadcast (todos os eventos) ou específico por instância++### Tipos de Conexão++#### 1. Conexão Específica (Por Instância)++Recebe apenas eventos de uma instância:++```+ws://localhost:4000/ws?token=TOKEN_DA_INSTANCIA&instanceId=vendas+```++#### 2. Conexão Broadcast++Recebe eventos de **todas as instâncias**:++```+ws://localhost:4000/ws?token=GLOBAL_API_KEY+```++### Gerenciamento de Conexões++O Evolution GO gerencia automaticamente as conexões WebSocket:++- **Conexões específicas**: Cada instância pode ter sua própria conexão+- **Conexões broadcast**: Recebem eventos de todas as instâncias+- **Desconexão automática**: Detecta e remove conexões inativas+- **Thread-safe**: Múltiplas conexões podem ser gerenciadas simultaneamente++### Cliente JavaScript++```javascript+// Conectar a instância específica+const token = 'token-da-instancia-vendas';+const instanceId = 'vendas';+const ws = new WebSocket(`ws://localhost:4000/ws?token=${token}&instanceId=${instanceId}`);++ws.onopen = () => {+ console.log('WebSocket conectado!');+};++ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ console.log('Evento recebido:', data.queue);+ console.log('Payload:', JSON.parse(data.payload));++ if (data.queue === 'message') {+ const message = JSON.parse(data.payload);+ console.log('Nova mensagem:', message.data.message.conversation);+ }+};++ws.onerror = (error) => {+ console.error('Erro no WebSocket:', error);+};++ws.onclose = () => {+ console.log('WebSocket desconectado');+ // Reconectar após 5 segundos+ setTimeout(() => {+ console.log('Reconectando...');+ // Criar nova conexão+ }, 5000);+};+```++### Cliente Python++```python+import asyncio+import websockets+import json++async def listen_events():+ uri = "ws://localhost:4000/ws?token=TOKEN&instanceId=vendas"++ async with websockets.connect(uri) as websocket:+ print("WebSocket conectado!")++ async for message in websocket:+ data = json.loads(message)+ queue = data.get('queue')+ payload = json.loads(data.get('payload'))++ print(f"Evento: {queue}")++ if queue == 'message':+ msg_text = payload.get('data', {}).get('message', {}).get('conversation')+ print(f"Mensagem recebida: {msg_text}")++asyncio.run(listen_events())+```++---++## Configuração++### Exemplo Completo (.env)++```env+# ===== WEBHOOK =====+WEBHOOK_URL=https://meu-servidor.com/webhook-global++# ===== RABBITMQ =====+AMQP_URL=amqp://admin:password@rabbitmq:5672/+AMQP_GLOBAL_ENABLED=true+AMQP_SPECIFIC_EVENTS=message,sendmessage,receipt,presence,calloffer++# ===== NATS =====+NATS_URL=nats://nats:4222+NATS_ENABLED=true++# ===== WEBSOCKET =====+# WebSocket é habilitado automaticamente+# Acesse: ws://localhost:4000/ws+```++### Configuração por Instância++```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "apikey: token-da-instancia-vendas" \+ -H "Content-Type: application/json" \+ -d '{+ "webhookUrl": "https://meu-servidor.com/webhook-vendas",+ "subscribe": ["MESSAGE", "GROUP", "CALL"],+ "rabbitmqEnabled": "enabled",+ "websocketEnable": "disabled",+ "natsEnabled": "enabled"+ }'+```++**Comportamento**:+- `rabbitmqEnabled: "enabled"` ou `"disabled"` - Habilita/desabilita RabbitMQ para esta instância+- `websocketEnable: "disabled"` ou outro valor - Habilita/desabilita WebSocket+- `natsEnabled: "enabled"` ou `"disabled"` - Habilita/desabilita NATS+- `webhookUrl` - URL específica para esta instância+- `subscribe` - Array com categorias de eventos: `MESSAGE`, `READ_RECEIPT`, `PRESENCE`, `HISTORY_SYNC`, `CHAT_PRESENCE`, `CALL`, `CONNECTION`, `QRCODE`, `LABEL`, `CONTACT`, `GROUP`, `NEWSLETTER`, ou `ALL`++---++## Tipos de Eventos++### Categorias vs Eventos Individuais++O Evolution GO usa dois níveis de classificação de eventos:++**Categorias de Eventos** (usadas no `subscribe`):+- São escritas em **MAIÚSCULAS**: `MESSAGE`, `GROUP`, `CALL`, etc.+- Agrupam múltiplos eventos relacionados+- Usadas para filtrar quais categorias você quer receber no `subscribe`++**Eventos Individuais** (nomes dos eventos emitidos):+- São escritos em **minúsculas**: `message`, `groupinfo`, `calloffer`, etc.+- São os eventos específicos que você receberá no webhook/fila+- Cada categoria pode gerar múltiplos eventos individuais++**Exemplo de mapeamento**:++| Categoria (`subscribe`) | Eventos Individuais Emitidos |+|------------------------|------------------------------|+| `MESSAGE` | `Message` (evento recebido no webhook) |+| `SEND_MESSAGE` | `SendMessage` |+| `READ_RECEIPT` | `Receipt` |+| `GROUP` | `GroupInfo`, `JoinedGroup` |+| `CALL` | `CallOffer`, `CallAccept`, `CallTerminate` |+| `CONNECTION` | `Connected`, `Disconnected`, `LoggedOut` |+| `QRCODE` | `PairSuccess`, `Disconnected` (com QR) |+| `ALL` | Todos os eventos |++**Exemplo prático**:+```json+// No connect, você filtra por categoria:+{+ "subscribe": ["MESSAGE", "GROUP", "CALL"]+}++// No webhook, você recebe o evento individual:+{+ "event": "Message", // ou "GroupInfo", "CallOffer", etc+ "data": { ... }+}+```++### Eventos de Mensagens++**Categoria**: `MESSAGE` e `SEND_MESSAGE`++- `Message` - Mensagem recebida+- `SendMessage` - Mensagem enviada+- `Receipt` - Confirmação de leitura (`READ_RECEIPT`)+- Reações, edições, deleções de mensagens++### Eventos de Grupos++**Categoria**: `GROUP`++- `GroupInfo` - Informações do grupo atualizadas (nome, descrição, participantes)+- `JoinedGroup` - Bot adicionado a um grupo++### Eventos de Chamadas++**Categoria**: `CALL`++- `CallOffer` - Chamada recebida+- `CallAccept` - Chamada aceita+- `CallTerminate` - Chamada encerrada++### Eventos de Conexão++**Categoria**: `CONNECTION`++- `Connected` - Instância conectada com sucesso+- `Disconnected` - Instância desconectada+- `LoggedOut` - Logout realizado (por outra sessão ou WhatsApp)+- `TemporaryBan` - Conta temporariamente banida++### Eventos de QR Code++**Categoria**: `QRCODE`++- `PairSuccess` - QR Code escaneado com sucesso+- `Disconnected` - Desconectado (pode incluir informações de QR)++### Eventos de Presença++**Categoria**: `PRESENCE` e `CHAT_PRESENCE`++- `Presence` - Status online/offline de contato+- `ChatPresence` - Digitando/gravando áudio++### Eventos de Contatos++**Categoria**: `CONTACT`++- `Contact` - Informações de contato atualizadas+- `PushName` - Nome do contato alterado++### Eventos de Labels++**Categoria**: `LABEL`++- `LabelEdit` - Label criada/editada/deletada+- `LabelAssociationChat` - Label associada a chat+- `LabelAssociationMessage` - Label associada a mensagem++### Eventos de Newsletter++**Categoria**: `NEWSLETTER`++- `NewsletterJoin` - Inscrito em newsletter+- `NewsletterLeave` - Saiu de newsletter++### Sincronização de Histórico++**Categoria**: `HISTORY_SYNC`++- `HistorySync` - Sincronização de histórico do telefone+- `OfflineSyncCompleted` - Sincronização offline concluída++---++## Formato de Payload++> **📚 Exemplos Detalhados de Webhooks**+>+> Para exemplos completos de JSON de todos os eventos de webhook, consulte nossa documentação detalhada:+>+> 🔗 **[Webhook - Exemplos Completos (Notion)](https://atendai.notion.site/Webhook-11b50bf742da80d99acafe4d92ccd054?pvs=74)**+>+> Este guia contém exemplos reais de payload para todos os tipos de eventos, incluindo mensagens de texto, mídia, grupos, chamadas, e muito mais.++### Estrutura Padrão++```json+{+ "event": "MESSAGE",+ "instance": "nome-da-instancia",+ "data": {+ // ... dados específicos do evento+ }+}+```++### Exemplo: Mensagem Recebida++```json+{+ "event": "MESSAGE",+ "instance": "vendas",+ "data": {+ "key": {+ "remoteJid": "[email protected]",+ "fromMe": false,+ "id": "3EB0C5A277F7F9B6C599"+ },+ "message": {+ "conversation": "Olá! Gostaria de informações sobre produtos."+ },+ "messageTimestamp": "1699999999",+ "pushName": "João Silva"+ }+}+```++### Exemplo: Grupo Criado++```json+{+ "event": "GROUP_UPDATE",+ "instance": "suporte",+ "data": {+ "jid": "[email protected]",+ "subject": "Suporte Técnico",+ "announce": false,+ "participants": [+ "[email protected]",+ ]+ }+}+```++### Exemplo: Chamada Recebida++```json+{+ "event": "CALL",+ "instance": "vendas",+ "data": {+ "id": "ABC123",+ "from": "[email protected]",+ "timestamp": "1699999999",+ "isVideo": false,+ "isGroup": false+ }+}+```++---++## Múltiplos Canais Simultâneos++### Cenário: Todos os Canais Ativos++```env+# Habilitar tudo+WEBHOOK_URL=https://api.exemplo.com/webhook+AMQP_URL=amqp://localhost:5672/+AMQP_GLOBAL_ENABLED=true+NATS_URL=nats://localhost:4222+NATS_ENABLED=true+```++```bash+curl -X POST http://localhost:4000/instance/connect \+ -H "apikey: token-vendas" \+ -H "Content-Type: application/json" \+ -d '{+ "webhookUrl": "https://api.exemplo.com/webhook-vendas",+ "rabbitmqEnabled": "enabled",+ "websocketEnable": "disabled",+ "natsEnabled": "enabled",+ "subscribe": ["MESSAGE"]+ }'+```++**Resultado**: Ao receber 1 mensagem, o evento será enviado para:+1. ✅ Webhook global (`WEBHOOK_URL`)+2. ✅ Webhook da instância (`webhookUrl`)+3. ✅ Fila RabbitMQ `message`+4. ✅ Tópico NATS `evolution.vendas.message`+5. ✅ Clientes WebSocket conectados++**Total**: **5 destinos** para o mesmo evento!++---++## Exemplos Práticos++### 1. Setup Básico com Webhook++```bash+# .env+WEBHOOK_URL=https://meu-dominio.com/webhook++# Conectar instância+curl -X POST http://localhost:4000/instance/connect \+ -H "Content-Type: application/json" \+ -H "apikey: token-bot-123" \+ -d '{+ "subscribe": ["MESSAGE"]+ }'++# Servidor receptor+node webhook-server.js+```++### 2. Arquitetura Distribuída com RabbitMQ++```bash+# Docker Compose+docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management++# .env+AMQP_URL=amqp://guest:guest@localhost:5672/+AMQP_GLOBAL_ENABLED=true+AMQP_SPECIFIC_EVENTS=message,sendmessage++# Consumidor em Python+python rabbitmq-consumer.py+```++### 3. Dashboard em Tempo Real com WebSocket++```html+<!DOCTYPE html>+<html>+<head>+ <title>Evolution GO Dashboard</title>+</head>+<body>+ <h1>Mensagens em Tempo Real</h1>+ <div id="messages"></div>++ <script>+ const ws = new WebSocket('ws://localhost:4000/ws?token=GLOBAL_API_KEY');++ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ const payload = JSON.parse(data.payload);++ if (data.queue === 'message') {+ const message = payload.data.message.conversation;+ const from = payload.data.pushName;++ const div = document.getElementById('messages');+ div.innerHTML += `<p><strong>${from}:</strong> ${message}</p>`;+ }+ };+ </script>+</body>+</html>+```++### 4. Microserviços com NATS++```bash+# Serviço 1: Processar mensagens+nats-consumer-messages.py++# Serviço 2: Processar chamadas+nats-consumer-calls.py++# Serviço 3: Analytics+nats-consumer-analytics.py++# Todos consomem independentemente+```++---++## Boas Práticas++### 1. Escolha o Canal Adequado++**Webhook** é ideal para:+- Integração simples com APIs existentes+- Aplicações que não precisam de garantias de entrega complexas+- Quando você tem controle sobre o servidor receptor++**RabbitMQ** é ideal para:+- Arquiteturas distribuídas com múltiplos consumidores+- Quando precisa garantir que nenhuma mensagem seja perdida+- Sistemas que exigem alta disponibilidade++**NATS** é ideal para:+- Comunicação em tempo real com latência mínima+- Arquiteturas de microserviços+- Quando você precisa de alto volume de mensagens++**WebSocket** é ideal para:+- Dashboards e painéis de controle+- Aplicações web que mostram dados em tempo real+- Quando você precisa de atualização instantânea na interface++### 2. Subscreva Apenas aos Eventos Necessários++Configure apenas os eventos que sua aplicação realmente vai processar:++```javascript+// ❌ Evite: subscrever a todos os eventos+{"subscribe": ["ALL"]}++// ✅ Melhor: especifique apenas o que você precisa+{"subscribe": ["MESSAGE", "GROUP_UPDATE"]}+```++### 3. Implemente Idempotência++Em casos de retry, o mesmo evento pode ser recebido mais de uma vez. Implemente lógica para evitar processamento duplicado:++```python+processed_messages = set()++def process_event(message_id, content):+ # Verifica se já foi processado+ if message_id in processed_messages:+ print(f"Evento {message_id} já processado, ignorando duplicata")+ return++ # Processa o evento+ print(f"Processando evento: {content}")++ # Marca como processado+ processed_messages.add(message_id)+```++### 4. Monitore Filas++**RabbitMQ**:+```bash+# Verificar filas+rabbitmqctl list_queues name messages consumers++# Interface web+http://localhost:15672+```++**NATS**:+```bash+nats server list+nats sub "evolution.>"+```++### 5. Configure Dead Letter Queue++Para RabbitMQ, configure uma fila de mensagens com falha (Dead Letter Queue) para capturar eventos que não puderam ser processados após várias tentativas. Consulte a documentação do RabbitMQ para detalhes de configuração.++---++## Troubleshooting++### Webhook não está sendo chamado++**Diagnóstico**:+```bash+# Verificar logs da instância+GET /instance/logs/:instanceId?level=ERROR+```++**Causas comuns**:+1. URL inválida ou inacessível+2. Firewall bloqueando requisições+3. Servidor não retornando 2xx++**Solução**:+```bash+# Testar URL manualmente+curl -X POST https://seu-webhook.com/endpoint -H "Content-Type: application/json" -d '{"test": true}'+```++### RabbitMQ não conecta++**Erro**: `failed to connect to RabbitMQ`++**Soluções**:+1. Verificar se RabbitMQ está rodando: `docker ps | grep rabbitmq`+2. Testar conexão: `telnet localhost 5672`+3. Verificar credenciais em `AMQP_URL`++### WebSocket desconecta constantemente++**Causas**:+- Proxy/load balancer não suporta WebSocket+- Timeout de idle connection++**Solução (Nginx)**:+```nginx+location /ws {+ proxy_pass http://localhost:4000;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection "upgrade";+ proxy_read_timeout 86400; # 24 horas+}+```++---++## Próximos Passos++- [Armazenamento de Mídia](./media-storage.md) - MinIO/S3 para arquivos+- [Conexão QR Code](./qrcode-connection.md) - Processo de autenticação+- [Multi-Dispositivo](./multi-device.md) - Suporte Multi-Device+- [API de Webhooks](../guias-api/api-webhooks.md) - Configurar webhooks via API++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/recursos-avancados/media-storage.md b/docs/wiki/recursos-avancados/media-storage.mdnew file mode 100644index 0000000..5051c76--- /dev/null+++ b/docs/wiki/recursos-avancados/media-storage.md@@ -0,0 +1,474 @@+# Armazenamento de Mídia++Sistema de armazenamento de arquivos de mídia do Evolution GO. Suporta MinIO, Amazon S3 e outros serviços compatíveis com S3.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Configuração](#configuração)+- [Estrutura de Arquivos](#estrutura-de-arquivos)+- [URLs Presignadas](#urls-presignadas)+- [Provedores Compatíveis](#provedores-compatíveis)+- [Exemplos Práticos](#exemplos-práticos)+- [Boas Práticas](#boas-práticas)++---++## Visão Geral++O Evolution GO armazena arquivos de mídia (imagens, vídeos, áudios, documentos) em **object storage** compatível com S3. Isso inclui serviços como MinIO, Amazon S3, Backblaze B2, DigitalOcean Spaces e outros.++### Por que Object Storage?++**Vantagens**:+- ✅ Escalável: suporta terabytes ou petabytes de dados+- ✅ Distribuído: alta disponibilidade e redundância+- ✅ Custo-efetivo: preços competitivos comparados a armazenamento tradicional+- ✅ Integração com CDN: acesso rápido globalmente+- ✅ Políticas de ciclo de vida: limpeza automática de arquivos antigos++**Comparado com armazenamento local (disco)**:+- ❌ Armazenamento local não escala horizontalmente+- ❌ Risco de perda de dados se o servidor falhar+- ❌ Complica deploys em clusters+- ❌ Sem redundância geográfica++### Arquitetura++```+┌─────────────┐+│ WhatsApp │ Envia mídia+└──────┬──────┘+ │+ ▼+┌──────────────┐+│ Evolution GO │ Recebe arquivo+└──────┬───────┘+ │+ ▼+┌──────────────────────────────────────┐+│ MediaStorage Interface │+└───────────────┬──────────────────────┘+ │+ ▼+┌─────────────────────────────────────┐+│ MinIO Storage Impl │+│ (S3-Compatible Object Storage) │+└───────────────┬─────────────────────┘+ │+ ▼+ ┌───────────────────────┐+ │ MinIO Server │+ │ (ou S3, B2, etc) │+ └───────────────────────┘+ │+ ▼+ ┌──────────────┐+ │ Bucket │+ │ evolution- │+ │ go-medias/ │+ └──────────────┘+```++---++## Configuração++### Variáveis de Ambiente++```env+# MinIO/S3 Endpoint+MINIO_ENDPOINT=s3.amazonaws.com++# Credenciais+MINIO_ACCESS_KEY=sua-access-key+MINIO_SECRET_KEY=sua-secret-key++# Bucket+MINIO_BUCKET=evolution-go-media++# Região (para AWS S3)+MINIO_REGION=us-east-1++# Usar SSL (true/false)+MINIO_USE_SSL=true+```++### Exemplo: MinIO Local (Docker)++```bash+# Rodar MinIO server+docker run -d --name minio -p 9000:9000 -p 9001:9001 -e MINIO_ROOT_USER=admin -e MINIO_ROOT_PASSWORD=password -v minio_data:/data minio/minio server /data --console-address ":9001"++# Criar bucket via mc (MinIO Client)+docker run --rm --network host minio/mc alias set local http://localhost:9000 admin password++docker run --rm --network host minio/mc mb local/evolution-go-media++# .env+MINIO_ENDPOINT=localhost:9000+MINIO_ACCESS_KEY=admin+MINIO_SECRET_KEY=password+MINIO_BUCKET=evolution-go-media+MINIO_REGION=us-east-1+MINIO_USE_SSL=false+```++**Acesso Web Console**: http://localhost:9001++### Exemplo: AWS S3++```env+MINIO_ENDPOINT=s3.amazonaws.com+MINIO_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE+MINIO_SECRET_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY+MINIO_BUCKET=meu-bucket-evolution+MINIO_REGION=us-east-1+MINIO_USE_SSL=true+```++### Exemplo: Backblaze B2++```env+MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com+MINIO_ACCESS_KEY=sua-key-id+MINIO_SECRET_KEY=sua-application-key+MINIO_BUCKET=meu-bucket+MINIO_REGION=us-west-004+MINIO_USE_SSL=true+```++### Exemplo: DigitalOcean Spaces++```env+MINIO_ENDPOINT=nyc3.digitaloceanspaces.com+MINIO_ACCESS_KEY=sua-spaces-key+MINIO_SECRET_KEY=sua-spaces-secret+MINIO_BUCKET=meu-space+MINIO_REGION=nyc3+MINIO_USE_SSL=true+```++---++## Estrutura de Arquivos++### Organização++Arquivos são armazenados com estrutura organizada:++```+bucket-name/+└── evolution-go-medias/+ ├── image-abc123.jpg+ ├── video-def456.mp4+ ├── audio-ghi789.ogg+ └── document-jkl012.pdf+```++### Caminho dos Arquivos++Todos os arquivos são armazenados automaticamente no diretório `evolution-go-medias/`:++**Exemplos**:+- Arquivo: `photo-123.jpg` → Caminho: `evolution-go-medias/photo-123.jpg`+- Arquivo: `video-456.mp4` → Caminho: `evolution-go-medias/video-456.mp4`+- Arquivo: `document-789.pdf` → Caminho: `evolution-go-medias/document-789.pdf`++---++## URLs Presignadas++### O que são?++**URLs presignadas** são URLs temporárias que permitem acesso a arquivos privados sem expor suas credenciais de acesso.++**Características**:+- ✅ Válidas por tempo limitado (padrão: 7 dias)+- ✅ Não requerem autenticação adicional+- ✅ Assinadas criptograficamente para segurança+- ✅ Podem ser compartilhadas publicamente durante o período de validade++### Como Funcionam++Quando você armazena ou solicita acesso a um arquivo, o Evolution GO gera automaticamente uma URL presignada com validade de 7 dias.++**Exemplo de URL presignada**:+```+https://s3.amazonaws.com/evolution-go-media/evolution-go-medias/photo-123.jpg?+X-Amz-Algorithm=AWS4-HMAC-SHA256&+X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20250111%2Fus-east-1%2Fs3%2Faws4_request&+X-Amz-Date=20250111T100000Z&+X-Amz-Expires=604800&+X-Amz-SignedHeaders=host&+X-Amz-Signature=abc123def456...+```++### Validade++**Tempo de expiração**: 7 dias (168 horas)++**Após expiração**:+- A URL retorna erro `403 Forbidden`+- É necessário gerar uma nova URL através da API++---++## Provedores Compatíveis++### Amazon S3++**Configuração**:+```env+MINIO_ENDPOINT=s3.amazonaws.com+MINIO_REGION=us-east-1+MINIO_USE_SSL=true+```++**Vantagens**:+- ✅ Mais confiável e testado+- ✅ Integração com CloudFront (CDN)+- ✅ Lifecycle policies avançadas+- ✅ Versionamento de objetos++**Desvantagens**:+- ❌ Mais caro que alternativas+- ❌ Vendor lock-in++### MinIO (Self-hosted)++**Configuração**:+```env+MINIO_ENDPOINT=minio.meu-dominio.com:9000+MINIO_REGION=us-east-1+MINIO_USE_SSL=true+```++**Vantagens**:+- ✅ Gratuito (self-hosted)+- ✅ Controle total+- ✅ Compatível com S3 API+- ✅ Bom para desenvolvimento++**Desvantagens**:+- ❌ Você gerencia infraestrutura+- ❌ Requer configuração de HA++### Backblaze B2++**Configuração**:+```env+MINIO_ENDPOINT=s3.us-west-004.backblazeb2.com+MINIO_REGION=us-west-004+MINIO_USE_SSL=true+```++**Vantagens**:+- ✅ Muito mais barato que S3 (1/4 do preço)+- ✅ Egress gratuito (até 3x storage)+- ✅ S3-compatible++**Desvantagens**:+- ❌ Não suporta bucket policies (usa presigned URLs)+- ❌ Menos integrações que AWS++### DigitalOcean Spaces++**Configuração**:+```env+MINIO_ENDPOINT=nyc3.digitaloceanspaces.com+MINIO_REGION=nyc3+MINIO_USE_SSL=true+```++**Vantagens**:+- ✅ Preço fixo ($5/mês por 250GB)+- ✅ CDN incluso+- ✅ Fácil configuração++**Desvantagens**:+- ❌ Limite de 250GB no plano básico+- ❌ Menos recursos que S3++### Wasabi++**Configuração**:+```env+MINIO_ENDPOINT=s3.wasabisys.com+MINIO_REGION=us-east-1+MINIO_USE_SSL=true+```++**Vantagens**:+- ✅ Sem custo de egress+- ✅ Preço competitivo+- ✅ S3-compatible++---++## Exemplos Práticos++### 1. Upload de Mídia++Quando o WhatsApp recebe uma imagem, vídeo ou documento:+1. O Evolution GO baixa o arquivo+2. Armazena automaticamente no object storage configurado+3. Gera uma URL presignada de acesso+4. A URL é incluída na resposta da API ou evento++### 2. Acesso a Mídia Armazenada++Para acessar um arquivo já armazenado:+- Use a URL presignada retornada durante o upload+- Se a URL expirou (>7 dias), solicite uma nova através da API++### 3. Limpeza de Arquivos Antigos++Configure lifecycle policies no seu provedor para deletar automaticamente arquivos antigos:+- **AWS S3**: Configure regras de ciclo de vida no console+- **MinIO**: Use o comando `mc ilm` para configurar políticas+- **Outros**: Consulte a documentação do provedor++---++## Boas Práticas++### 1. Use Nomes de Arquivo Únicos++Gere nomes únicos para cada arquivo para evitar sobrescrever arquivos existentes:++**❌ Evite**: Usar nomes genéricos como `photo.jpg`, `video.mp4`++**✅ Recomendado**: Usar identificadores únicos como UUID ou timestamp:+- `photo-abc123-def456-ghi789.jpg`+- `video-20250111-103045.mp4`+- `document-550e8400-e29b-41d4.pdf`++### 2. Configure Content-Type Correto++O Evolution GO configura automaticamente o Content-Type baseado na extensão do arquivo:+- `.jpg`, `.jpeg` → `image/jpeg`+- `.png` → `image/png`+- `.mp4` → `video/mp4`+- `.pdf` → `application/pdf`+- `.ogg` → `audio/ogg`++### 3. Implemente Lifecycle Policies++**AWS S3**:+```json+{+ "Rules": [+ {+ "Id": "delete-old-media",+ "Status": "Enabled",+ "Prefix": "evolution-go-medias/",+ "Expiration": {+ "Days": 30+ }+ }+ ]+}+```++**MinIO**:+```bash+mc ilm add local/evolution-go-media --prefix "evolution-go-medias/" --expiry-days 30+```++### 4. Use CDN para Distribuição++**CloudFront (AWS)**:+1. Crie distribuição CloudFront+2. Aponte origin para bucket S3+3. URLs ficam: `https://d123456.cloudfront.net/evolution-go-medias/photo.jpg`++**DigitalOcean Spaces CDN** (automático):+```+https://bucket-name.nyc3.cdn.digitaloceanspaces.com/file.jpg+```++### 5. Monitore Uso e Custos++```bash+# AWS S3 - Tamanho total do bucket+aws s3 ls s3://bucket-name --recursive --summarize | grep "Total Size"++# MinIO+mc du local/evolution-go-media+```++### 6. Comprima Imagens Quando Possível++Para reduzir custos de armazenamento e transferência:+- Comprima imagens antes de armazenar+- Use formatos modernos como WebP quando possível+- Ajuste a qualidade JPEG para 80-90% (reduz tamanho sem perda significativa de qualidade)++### 7. Monitore Uso e Custos++Acompanhe regularmente:+- Tamanho total do bucket+- Número de arquivos armazenados+- Custos mensais de armazenamento e transferência+- URLs presignadas que expiraram++---++## Troubleshooting++### Erro: "failed to create MinIO client"++**Causa**: Credenciais ou endpoint incorretos.++**Solução**:+```bash+# Testar conexão com mc+mc alias set test https://endpoint access-key secret-key+mc ls test+```++### Erro: "bucket does not exist"++**Causa**: Bucket não foi criado.++**Solução**:+```bash+# Criar bucket+mc mb test/evolution-go-media++# Ou via AWS CLI+aws s3 mb s3://evolution-go-media+```++### URLs retornam 403 Forbidden++**Causa 1**: URL presignada expirou (>7 dias).++**Solução**: Gere nova URL com `GetURL()`.++**Causa 2**: Bucket policy incorreta.++**Solução**: Use presigned URLs (funcionam independente de bucket policy).++### Upload muito lento++**Causa**: Latência de rede para região distante.++**Solução**:+1. Use região mais próxima do servidor+2. Use multipart upload para arquivos grandes (>5MB)+3. Configure timeout adequado++---++## Próximos Passos++- [Sistema de Eventos](./events-system.md) - Receber notificações de uploads+- [Conexão QR Code](./qrcode-connection.md) - Autenticação WhatsApp+- [Multi-Dispositivo](./multi-device.md) - Suporte Multi-Device+- [API de Mensagens](../guias-api/api-messages.md) - Enviar mídias via API++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/recursos-avancados/multi-device.md b/docs/wiki/recursos-avancados/multi-device.mdnew file mode 100644index 0000000..d686f31--- /dev/null+++ b/docs/wiki/recursos-avancados/multi-device.md@@ -0,0 +1,395 @@+# WhatsApp Multi-Device++Entenda como funciona o protocolo Multi-Device do WhatsApp e como o Evolution GO o utiliza.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Arquitetura](#arquitetura)+- [Protocolo Signal](#protocolo-signal)+- [Sincronização de Dados](#sincronização-de-dados)+- [Criptografia](#criptografia)+- [Limitações](#limitações)+- [Vantagens](#vantagens)+- [Comparação com Versão Antiga](#comparação-com-versão-antiga)++---++## Visão Geral++WhatsApp **Multi-Device** é o protocolo que permite conectar até 4 dispositivos simultaneamente, sem necessidade do celular estar online após o pareamento inicial.++### Antes vs Depois++**Legacy (Antigo - Web WhatsApp)**:+```+┌─────────────┐+│ Celular │ ◄── SEMPRE precisa estar online+│ (Primary) │+└──────┬──────┘+ │+ │ Relay+ │+ ▼+┌──────────────┐+│ WhatsApp Web │ ◄── Depende 100% do celular+└──────────────┘+```++**Multi-Device (Atual)**:+```+┌─────────────┐+│ Celular │ ◄── Dispositivo principal+│ (Primary) │+└──────┬──────┘+ │+ │ Peer-to-Peer Sync+ │+ ├────────────┬────────────┬────────────┐+ ▼ ▼ ▼ ▼+┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐+│WhatsApp │ │Evolution │ │WhatsApp │ │WhatsApp │+│Desktop │ │ GO │ │Web │ │Business │+└──────────┘ └──────────┘ └──────────┘ └──────────┘++Todos funcionam INDEPENDENTEMENTE!+```++---++## Arquitetura++### Componentes++1. **Dispositivo Principal (Primary Device)**+ - Celular com WhatsApp instalado+ - Única fonte de verdade para contatos e configurações+ - Pode funcionar offline após sincronização inicial++2. **Dispositivos Companion (Companion Devices)**+ - WhatsApp Web, Desktop, Business API, Evolution GO+ - Até 4 dispositivos simultâneos+ - Funcionam independentemente após pareamento++3. **Servidores WhatsApp**+ - Facilitam comunicação entre devices+ - Armazenam mensagens criptografadas temporariamente+ - Sincronizam estado entre dispositivos++### Diagrama de Comunicação++```+┌──────────────────────────────────────────────────────────┐+│ WhatsApp Servers │+│ - Message Routing │+│ - State Synchronization │+│ - End-to-End Encryption Relay │+└───────────────────┬──────────────────────────────────────┘+ │+ ┌──────────┼──────────┬──────────┬──────────┐+ │ │ │ │ │+ ▼ ▼ ▼ ▼ ▼+ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐+ │Primary │ │Device 1│ │Device 2│ │Device 3│ │Device 4│+ │(Phone) │ │Desktop │ │Evolution│ │ Web │ │Business│+ └────────┘ └────────┘ └────────┘ └────────┘ └────────┘+ │ │ │ │ │+ └──────────┴──────────┴──────────┴──────────┘+ │+ Direct Peer Sync+ (quando ambos online)+```++### Funcionamento++**Enviar Mensagem**:+1. Device 1 (Evolution GO) envia mensagem criptografada para WhatsApp servers+2. Servers encaminham para destinatário+3. Servers **também** sincronizam com outros devices do remetente+4. Primary device e outros companion devices recebem cópia++**Receber Mensagem**:+1. WhatsApp servers recebem mensagem destinada ao seu número+2. Servers replicam para **todos os devices conectados** simultaneamente+3. Cada device descriptografa independentemente++---++## Protocolo Signal++### O que é Signal Protocol?++**Signal Protocol** é o protocolo de criptografia ponta-a-ponta (E2EE) usado pelo WhatsApp Multi-Device.++**Criado por**: Open Whisper Systems (agora Signal Foundation)++**Usado em**:+- Signal Messenger+- Facebook Messenger (Secret Conversations)+- Google Messages (RCS)++### Componentes do Signal Protocol++#### 1. Identity Keys (Chaves de Identidade)++Cada dispositivo tem um par de chaves únicas:+- **Chave Pública**: Compartilhada com outros dispositivos+- **Chave Privada**: Nunca sai do dispositivo, usada para descriptografia++#### 2. Pre-Keys (Chaves Pré-geradas)++Um conjunto de 100 chaves geradas automaticamente quando você conecta um dispositivo pela primeira vez. Essas chaves permitem que outros dispositivos iniciem conversas criptografadas com você, mesmo quando você está offline.++**Renovação**: Novas pre-keys são geradas automaticamente conforme necessário.++#### 3. Signed Pre-Keys (Chaves Assinadas)++Uma pre-key especial assinada pela sua chave de identidade, provando autenticidade.++**Renovação**: A cada 7 dias.++#### 4. Session Keys (Chaves de Sessão)++Chaves únicas para cada conversa que mudam automaticamente a cada mensagem enviada (conceito chamado "ratcheting").++**Segurança**: Se uma chave for comprometida, apenas aquela mensagem específica é afetada - mensagens anteriores e futuras permanecem seguras (Forward Secrecy).++---++## Sincronização de Dados++### Tipos de Sincronização++#### 1. Mensagens++**Histórico Inicial**:+- Últimos **3 meses** de conversas+- Mídia: Apenas thumbnails (mídia completa baixada on-demand)++**Novas Mensagens**:+- Sincronizadas em tempo real+- Todos os dispositivos recebem simultaneamente++#### 2. Contatos++**Sincronização**:+- Lista completa de contatos do celular+- Atualizada automaticamente quando um contato muda nome ou número++#### 3. Grupos++**Informações sincronizadas**:+- Lista de todos os grupos que você participa+- Metadados (nome, descrição, foto, lista de participantes)+- Configurações (silenciado, fixado)++#### 4. Chats++**Estados sincronizados**:+- Chats fixados (pinned)+- Chats arquivados (archived)+- Chats silenciados (muted)+- Mensagens lidas/não lidas++#### 5. Configurações++**Sincronizadas**:+- Foto de perfil+- Nome de exibição+- Recado (status text)+- Configurações de privacidade++**NÃO sincronizadas**:+- Notificações (específico por device)+- Tema/aparência (específico por device)++### History Sync Request++**Solicitação de histórico** (implementado via API):++```bash+POST /chat/history-sync-request+{+ "messageInfo": {+ "Chat": "[email protected]",+ "IsFromMe": false,+ "IsGroup": false,+ "ID": "3EB0C5A277F7F9B6C599",+ "Timestamp": "2025-11-11T10:00:00Z"+ },+ "count": 50+}+```++**Parâmetros**:+- `messageInfo`: Mensagem de referência (ponto de partida)+- `count`: Número de mensagens para buscar (máx 100)++**Uso**: Carregar mensagens antigas de uma conversa.++---++## Criptografia++### End-to-End Encryption (Criptografia Ponta-a-Ponta)++Todas as mensagens são criptografadas no dispositivo do remetente e só podem ser descriptografadas no dispositivo do destinatário.++**Importante**: Os servidores do WhatsApp não conseguem ler o conteúdo das mensagens - eles apenas facilitam a entrega dos dados criptografados.++### Fluxo de Criptografia++```+┌────────────┐ ┌────────────┐+│ Remetente │ │Destinatário│+│ (Device) │ │ (Device) │+└─────┬──────┘ └──────┬─────┘+ │ │+ │ 1. Mensagem: "Olá!" │+ │──────────┐ │+ │ │ │+ │ 2. Criptografa com Session Key │+ │<─────────┘ │+ │ │+ │ 3. Envia encrypted blob │+ │───────────────────────────────────────────────>│+ │ (via WhatsApp Servers) │+ │ │+ │ │ 4. Descriptografa+ │ │────────────┐+ │ │ │+ │ │ 5. "Olá!" │+ │ │<───────────┘+ │ │+```++### Verificação de Segurança++**Código de Segurança (Safety Number)**:+- É um código de 60 dígitos único para cada conversa+- Compara as chaves de identidade dos participantes+- Muda se um dos participantes trocar de dispositivo++**Como verificar no WhatsApp**:+1. Abrir a conversa+2. Tocar no nome do contato+3. Selecionar "Criptografia"+4. Comparar o código com o contato pessoalmente ou por outro canal seguro++---++## Limitações++### Limite de Devices++**Máximo**: 4 companion devices + 1 primary device (celular).++**Exemplo**:+- ✅ Celular (Primary)+- ✅ WhatsApp Web (Device 1)+- ✅ WhatsApp Desktop (Device 2)+- ✅ Evolution GO (Device 3)+- ✅ WhatsApp Business API (Device 4)+- ❌ Outro device → Erro: "Máximo de devices atingido"++**Solução**: Desconectar um device antes de conectar novo.++### Histórico Limitado++**Sincronização inicial**: Apenas últimos **3 meses**.++**Mensagens mais antigas**:+- Não são sincronizadas automaticamente+- Podem ser buscadas via History Sync Request (se disponíveis)+- Mídia completa não é transferida (apenas thumbnails)++### Chamadas++**Limitação atual**: Evolution GO **não suporta atender** chamadas de voz/vídeo.++**Suportado**:+- ✅ Receber notificação de chamada (evento `CALL`)+- ✅ Rejeitar chamada automaticamente++**NÃO suportado**:+- ❌ Atender chamada+- ❌ Áudio/vídeo em tempo real++### Sessão Expira++**Inatividade**: Se device ficar offline por **>14 dias**, sessão expira.++**Solução**: Novo pareamento via QR Code necessário.++---++## Vantagens++### 1. Independência do Celular++**Evolution GO funciona mesmo com celular offline** (após sincronização inicial).++**Casos de uso**:+- Celular sem bateria+- Celular sem internet+- Viagem internacional (celular desligado)++### 2. Sincronização em Tempo Real++**Todas as mensagens** aparecem em todos os devices simultaneamente.++**Exemplo**:+- Enviar mensagem no Evolution GO+- Aparece instantaneamente no WhatsApp Web+- Aparece no celular+- Aparece no Desktop++### 3. Múltiplas Contas Simultâneas++**Com containers Docker**, você pode ter **N instâncias** do Evolution GO, cada uma conectada a um número WhatsApp diferente:++```bash+docker run -d --name evo-vendas evolution-go+docker run -d --name evo-suporte evolution-go+docker run -d --name evo-marketing evolution-go+```++Cada container = 1 número WhatsApp separado.++### 4. Alta Disponibilidade++**Redundância**: Se um device falha, outros continuam funcionando.++**Load Balancing**: Distribua carga entre múltiplos Evolution GO instances.++---++## Comparação com Versão Antiga++| Aspecto | Legacy (Web WhatsApp) | Multi-Device (Atual) |+|---------|----------------------|----------------------|+| **Celular precisa online?** | ✅ Sim, sempre | ❌ Não (após pareamento) |+| **Criptografia** | E2EE | E2EE (melhorada) |+| **Sincronização** | Relay via celular | Peer-to-peer + servers |+| **Histórico** | Depende do celular | 3 meses sincronizados |+| **Latência** | Alta (2 hops) | Baixa (direto) |+| **Devices simultâneos** | 1 (Web) | 4 companions |+| **Chamadas** | Não suportado | Não suportado* |+| **Mídia** | Relay via celular | Direct download |++*Chamadas não suportadas em companion devices (limitação WhatsApp).+++---++## Próximos Passos++- [Conexão QR Code](./qrcode-connection.md) - Processo de pareamento+- [Sistema de Eventos](./events-system.md) - Receber eventos Multi-Device+- [Instâncias WhatsApp](../conceitos-core/instances.md) - Gerenciamento de devices+- [Banco de Dados](../conceitos-core/database.md) - Armazenamento de sessões++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/recursos-avancados/qrcode-connection.md b/docs/wiki/recursos-avancados/qrcode-connection.mdnew file mode 100644index 0000000..23c046c--- /dev/null+++ b/docs/wiki/recursos-avancados/qrcode-connection.md@@ -0,0 +1,679 @@+# Conexão QR Code++Como funciona o processo de autenticação via QR Code no Evolution GO.++## 📋 Índice++- [Visão Geral](#visão-geral)+- [Fluxo de Conexão](#fluxo-de-conexão)+- [Geração do QR Code](#geração-do-qr-code)+- [Leitura do QR Code](#leitura-do-qr-code)+- [Pareamento por Código](#pareamento-por-código)+- [Estados da Conexão](#estados-da-conexão)+- [Reconexão Automática](#reconexão-automática)+- [Troubleshooting](#troubleshooting)+- [Boas Práticas](#boas-práticas)++---++## Visão Geral++O Evolution GO utiliza o protocolo Multi-Device do WhatsApp para autenticar instâncias. O processo é baseado em QR Code, similar ao WhatsApp Web.++### Como Funciona++1. **Gerar QR Code**: O Evolution GO cria um código único+2. **Escanear**: Você escaneia o código com o WhatsApp no celular+3. **Pareamento**: WhatsApp e Evolution GO trocam chaves de criptografia+4. **Sessão Ativa**: Conexão estabelecida e salva no banco de dados++### Por que QR Code?++**Vantagens**:+- ✅ Seguro: chaves criptográficas trocadas de forma protegida+- ✅ Não requer senha ou número de telefone+- ✅ Suporta múltiplos dispositivos conectados simultaneamente+- ✅ Processo simples e rápido++**Importante**: O WhatsApp não oferece login com usuário e senha para APIs. A autenticação é exclusivamente via QR Code ou código de pareamento.++---++## Fluxo de Conexão++### Diagrama Completo++```+┌──────────────┐ ┌──────────────┐+│ Evolution GO │ │ WhatsApp │+│ Client │ │ Servers │+└──────┬───────┘ └──────┬───────┘+ │ │+ │ 1. POST /instance/connect │+ │────────────────────────┐ │+ │ │ │+ │ 2. StartClient() │ │+ │<───────────────────────┘ │+ │ │+ │ 3. Connect WebSocket │+ │──────────────────────────────────────────────────────>│+ │ │+ │ 4. Request QR Code │+ │──────────────────────────────────────────────────────>│+ │ │+ │ 5. QR Code Data (ref + public key) │+ │<──────────────────────────────────────────────────────│+ │ │+ │ 6. Generate PNG QR Code │+ │────────────┐ │+ │ │ │+ │<───────────┘ │+ │ │+ │ 7. Save QR to Database (base64|text) │+ │────────────┐ │+ │ │ │+ │<───────────┘ │+ │ │+ │ 8. Emit QR_CODE Event │+ │────────────┐ │+ │ │ (Webhook/WebSocket) │+ │<───────────┘ │+ │ │+┌──────▼───────┐ │+│ User │ │+│ (Smartphone) │ │+└──────┬───────┘ │+ │ │+ │ 9. Open WhatsApp App │+ │ → Linked Devices │+ │ → Scan QR Code │+ │ │+ │ 10. Send Pairing Data (encrypted) │+ │──────────────────────────────────────────────────────>│+ │ │+ │ 11. Pairing Success │+ │<──────────────────────────────────────────────────────│+ │ │+┌──────▼───────┐ │+│ Evolution GO │ │+└──────┬───────┘ │+ │ │+ │ 12. Receive Pairing Success Event │+ │<──────────────────────────────────────────────────────│+ │ │+ │ 13. Generate Identity & Pre-Keys │+ │────────────┐ │+ │ │ │+ │<───────────┘ │+ │ │+ │ 14. Save Session to Database │+ │────────────┐ │+ │ │ (JID, Keys, Device Info) │+ │<───────────┘ │+ │ │+ │ 15. Update Instance (connected=true, jid=...) │+ │────────────┐ │+ │ │ │+ │<───────────┘ │+ │ │+ │ 16. Emit CONNECTED Event │+ │────────────┐ │+ │ │ │+ │<───────────┘ │+ │ │+ │ 17. Start Message Sync │+ │<─────────────────────────────────────────────────────>│+ │ (bidirectional) │+ │ │+```++### Passos Detalhados++#### 1. Conectar Instância++**API Call**:+```bash+POST /instance/connect+{+ "instanceName": "vendas"+}+```++**Ações**:+- Verifica se instância existe no banco+- Inicia goroutine com whatsmeow client+- Estabelece WebSocket com servidores WhatsApp++#### 2. Solicitação de QR Code++O Evolution GO solicita ao WhatsApp um código QR único, que contém:+- **Ref**: Referência única que identifica esta tentativa de conexão+- **Public Key**: Chave pública para iniciar o pareamento criptografado++#### 3. Geração da Imagem QR++**Formato do texto no QR Code**:+```+versão@ref,chave_pública,segredo,dados_adicionais+```++**Exemplo**:+```+2@ABC123DEF456,GHI789JKL012MNO345,PQR678STU901VWX234,YZA567+```++**Armazenamento**:+O QR Code é convertido em uma imagem PNG, codificada em base64 e salva no banco de dados junto com o texto original.++#### 4. Exibição do QR Code++**Via navegador**:+```+GET /instance/qr?instanceName=vendas+```++**Resposta HTML**:+```html+<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." />+```++**Via API JSON**:+```bash+GET /instance/qr?instanceName=vendas+```++```json+{+ "qrcode": "iVBORw0KGgoAAAANSUhEUgAA...",+ "code": "2@ABC123,DEF456,GHI789,JKL012"+}+```++#### 5. Usuário Escaneia++**No smartphone**:+1. Abre WhatsApp+2. Menu → Aparelhos conectados+3. Conectar um aparelho+4. Escaneia QR Code++**WhatsApp envia**:+- Chaves públicas do device+- JID (WhatsApp ID) do número+- Device info (modelo, OS)++#### 6. Pareamento Concluído++Após o usuário escanear o QR Code:++1. **Evolution GO recebe confirmação** do WhatsApp+2. **Sessão é salva** no banco de dados com:+ - Chaves de identidade+ - Chaves pré-geradas+ - JID (identificador do WhatsApp)+ - Informações do dispositivo+3. **Instância marcada como conectada**+4. **Evento CONNECTED** é publicado++---++## Geração do QR Code++### Evento de QR Code++Quando um QR Code é gerado:++1. **Texto do QR Code** é recebido do WhatsApp+2. **Imagem PNG** é criada a partir do texto+3. **Salvo no banco de dados** em formato base64+4. **Evento QR_CODE** é publicado para webhooks/websockets configurados++### Formato do QR++**Estrutura**:+```+version@ref,pub_key,secret,adv+```++**Componentes**:+- `version`: Versão do protocolo (geralmente `2`)+- `ref`: Referência única (identifica esta tentativa de pareamento)+- `pub_key`: Chave pública do servidor+- `secret`: Segredo compartilhado+- `adv`: Dados de advertising (device info)++**Exemplo real**:+```+2@12345abcdef,67890ghijk,lmnop12345,qrstu67890+```++### Expiração++**Tempo de vida**: ~40 segundos++**Após expiração**:+- Whatsmeow emite novo evento QR+- Novo QR Code é gerado+- Repete até `max_attempts` (padrão: 5 tentativas)++**Evento de timeout**:+```go+case *events.QRTimeout:+ logger.Warn("QR Code expired, generating new one...")+```++---++## Leitura do QR Code++### Endpoint HTTP++**Obter QR Code via API**:+```bash+GET /instance/qr?instanceName=vendas+```++**Response (JSON)**:+```json+{+ "qrcode": "iVBORw0KGgoAAAANSUhEUgAABAA...",+ "code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890"+}+```++**Response (HTML)** - Se aceitar `text/html`:+```html+<!DOCTYPE html>+<html>+<head><title>QR Code - vendas</title></head>+<body>+ <h1>QR Code - Instância: vendas</h1>+ <img src="data:image/png;base64,iVBORw0KG..." />+ <p>Escaneie com WhatsApp</p>+</body>+</html>+```++### Via WebSocket++**Conectar**:+```javascript+const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');++ws.onmessage = (event) => {+ const data = JSON.parse(event.data);++ if (data.queue === 'qrcode') {+ const payload = JSON.parse(data.payload);+ const qrBase64 = payload.qrcode;++ // Exibir QR Code+ document.getElementById('qr-img').src =+ `data:image/png;base64,${qrBase64}`;+ }+};+```++### Via Webhook++**Configurar webhook**:+```bash+POST /instance/connect+{+ "instanceName": "vendas",+ "webhookUrl": "https://meu-servidor.com/webhook",+ "subscribe": ["QRCODE"]+}+```++**Evento recebido**:+```json+{+ "event": "QRCODE",+ "instance": "vendas",+ "data": {+ "qrcode": "iVBORw0KGgoAAAANSUhEUgA...",+ "code": "2@12345abcdef,67890ghijk,lmnop12345,qrstu67890"+ }+}+```++---++## Pareamento por Código++### Alternativa ao QR Code++Além de QR Code, é possível parear via **código de 8 dígitos**.++**Endpoint**:+```bash+POST /instance/pair+{+ "instanceName": "vendas",+ "phone": "5511999999999"+}+```++**Response**:+```json+{+ "pairingCode": "ABCD-1234"+}+```++### Como Usar++**No smartphone**:+1. Abre WhatsApp+2. Menu → Aparelhos conectados+3. Conectar um aparelho+4. Link com código de aparelho+5. Digita `ABCD-1234`++**Vantagens**:+- ✅ Não precisa de camera/QR scanner+- ✅ Mais fácil para compartilhar remotamente++**Desvantagens**:+- ❌ Requer digitação manual+- ❌ Menos visual que QR Code++### Como Funciona++O Evolution GO gera um código de 8 dígitos único e o retorna na API. Esse código é válido por tempo limitado e pode ser usado uma única vez.++---++## Estados da Conexão++### Máquina de Estados++```+┌─────────────┐+│ CREATED │ Instância criada, nunca conectada+└──────┬──────┘+ │ POST /instance/connect+ ▼+┌─────────────┐+│ CONNECTING │ WebSocket iniciando+└──────┬──────┘+ │+ ▼+┌─────────────┐+│ WAITING_QR │ Aguardando usuário escanear+└──────┬──────┘+ │ Usuário escaneia QR+ ▼+┌─────────────┐+│ PAIRING │ Trocando chaves criptográficas+└──────┬──────┘+ │+ ▼+┌─────────────┐+│ OPEN │ Conectado e autenticado+└──────┬──────┘+ │+ │ Erro de conexão ou logout+ ▼+┌─────────────┐+│ DISCONNECTED│+└─────────────┘+```++### Eventos Associados++#### QRCODE+```json+{+ "event": "QRCODE",+ "data": {+ "qrcode": "base64...",+ "code": "2@..."+ }+}+```++#### QR_TIMEOUT+```json+{+ "event": "QR_TIMEOUT",+ "data": {+ "attempts": 1,+ "maxAttempts": 5+ }+}+```++#### QR_SUCCESS+```json+{+ "event": "QR_SUCCESS",+ "data": {+ "jid": "[email protected]"+ }+}+```++#### CONNECTED+```json+{+ "event": "CONNECTED",+ "data": {+ "jid": "[email protected]",+ "name": "João Silva",+ "timestamp": "2025-11-11T10:30:00Z"+ }+}+```++---++## Reconexão Automática++### Após Primeiro Pareamento++Depois do primeiro pareamento bem-sucedido via QR Code:++1. **Sessão é salva** no banco de dados PostgreSQL+2. **Próxima inicialização**: Sessão é carregada automaticamente+3. **Conecta diretamente** sem necessidade de novo QR Code++O Evolution GO mantém várias tabelas para armazenar as informações de sessão e chaves criptográficas necessárias para reconexão.++### Tentativas de Reconexão++Se uma conexão cair, o Evolution GO tenta reconectar automaticamente usando estratégia de intervalo crescente:++- Tentativa 1: 2 segundos+- Tentativa 2: 4 segundos+- Tentativa 3: 8 segundos+- Tentativa 4: 16 segundos+- Tentativa 5: 32 segundos++### Quando é Necessário Novo QR Code++Em alguns cenários, é necessário gerar um novo QR Code:++- ❌ Após logout explícito via API+- ❌ Dispositivo removido manualmente no app WhatsApp+- ❌ Sessão expirada (mais de 14 dias offline)+- ❌ Conta temporariamente ou permanentemente bloqueada++---++## Troubleshooting++### QR Code não aparece++**Diagnóstico**:+```bash+GET /instance/logs/:instanceId?level=ERROR+```++**Causas comuns**:+1. Cliente não conectado ao WebSocket+2. Firewall bloqueando conexão com WhatsApp servers+3. Instância já conectada (não precisa de QR)++**Solução**:+```bash+# Forçar reconexão+POST /instance/reconnect+{+ "instanceName": "vendas"+}+```++### QR Code expira muito rápido++**Causa**: Delay entre geração e exibição.++**Solução**: Use WebSocket para receber QR em tempo real.++```javascript+const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');++ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ if (data.queue === 'qrcode') {+ // Exibir imediatamente+ showQRCode(data.payload.qrcode);+ }+};+```++### Escaneou QR mas não conectou++**Diagnóstico**:+```bash+GET /instance/status?instanceName=vendas+```++**Resposta esperada após scan**:+```json+{+ "connected": true,+ "loggedIn": true,+ "jid": "[email protected]"+}+```++**Se continuar `connected: false`**:+1. Verificar logs de erro+2. Tentar logout e novo QR+3. Verificar se WhatsApp está atualizado++### Erro: "too many attempts"++**Causa**: QR Code expirou 5 vezes.++**Solução**:+```bash+# Desconectar+POST /instance/disconnect++# Aguardar 30 segundos++# Reconectar+POST /instance/connect+```++---++## Boas Práticas++### 1. Exibir QR em Tempo Real++Use WebSocket em vez de polling:++**❌ Ruim** (polling):+```javascript+setInterval(() => {+ fetch('/instance/qr?instanceName=vendas')+ .then(res => res.json())+ .then(data => showQR(data.qrcode));+}, 5000); // A cada 5 segundos+```++**✅ Bom** (WebSocket):+```javascript+const ws = new WebSocket('ws://localhost:4000/ws?token=TOKEN&instanceId=vendas');+ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ if (data.queue === 'qrcode') showQR(data.payload.qrcode);+};+```++### 2. Feedback Visual++Mostre estado da conexão para o usuário:++```javascript+ws.onmessage = (event) => {+ const { queue } = JSON.parse(event.data);++ switch(queue) {+ case 'qrcode':+ showStatus('Escaneie o QR Code');+ break;+ case 'qr_success':+ showStatus('QR Code escaneado! Conectando...');+ break;+ case 'connected':+ showStatus('Conectado com sucesso!');+ break;+ }+};+```++### 3. Timeout de Inatividade++Desconecte se QR não for escaneado em tempo razoável:++```javascript+let qrTimeout;++ws.onmessage = (event) => {+ const data = JSON.parse(event.data);++ if (data.queue === 'qrcode') {+ // Cancela timeout anterior+ clearTimeout(qrTimeout);++ // Timeout de 2 minutos+ qrTimeout = setTimeout(() => {+ alert('QR Code expirou. Por favor, tente novamente.');+ ws.close();+ }, 120000);+ }++ if (data.queue === 'connected') {+ clearTimeout(qrTimeout);+ }+};+```++### 4. Validar Sessão Antes de Solicitar QR++```bash+# Verificar status primeiro+GET /instance/status?instanceName=vendas++# Se já conectado, não precisa de QR+# Se desconectado mas tem sessão, tentar reconnect+# Só gerar QR se não tem sessão+```++---++## Próximos Passos++- [Multi-Dispositivo](./multi-device.md) - Entender protocolo Multi-Device+- [Instâncias WhatsApp](../conceitos-core/instances.md) - Ciclo de vida completo+- [Sistema de Eventos](./events-system.md) - Receber eventos de conexão+- [API de Instâncias](../guias-api/api-instances.md) - Todos os endpoints++---++**Documentação gerada para Evolution GO v1.0**diff --git a/docs/wiki/referencia/api-reference.md b/docs/wiki/referencia/api-reference.mdnew file mode 100644index 0000000..f4f7e81--- /dev/null+++ b/docs/wiki/referencia/api-reference.md@@ -0,0 +1,184 @@+# Referência da API++Referência rápida de endpoints disponíveis na API Evolution GO.++## Autenticação++Todos os endpoints requerem header de autenticação:++```+apikey: SUA-CHAVE-API+```++## Base URL++```+http://localhost:4000+```++---++## Endpoints por Categoria++### Instâncias (16 endpoints)++**Gerenciamento (requer GLOBAL_API_KEY):**+- `POST /instance/create` - Criar nova instância+- `GET /instance/all` - Listar todas as instâncias+- `GET /instance/info/:instanceId` - Detalhes da instância+- `DELETE /instance/delete/:instanceId` - Remover instância++**Operações (requer token da instância):**+- `POST /instance/connect` - Iniciar conexão+- `GET /instance/status` - Status de conexão+- `GET /instance/qr` - Obter QR Code+- `POST /instance/pair` - Parear com código+- `POST /instance/disconnect` - Desconectar+- `POST /instance/reconnect` - Reconectar+- `DELETE /instance/logout` - Fazer logout++**Documentação completa:** [API de Instâncias](../guias-api/api-instances.md)++---++### Mensagens (16 endpoints)++**Envio:**+- `POST /send/text` - Mensagem de texto+- `POST /send/media` - Mídia (imagem/vídeo/áudio/documento)+- `POST /send/link` - Link com preview+- `POST /send/location` - Localização+- `POST /send/contact` - Contato+- `POST /send/poll` - Enquete+- `POST /send/sticker` - Sticker+- `POST /send/button` - Botões interativos+- `POST /send/list` - Lista de opções++**Operações:**+- `POST /message/react` - Reagir à mensagem+- `POST /message/markread` - Marcar como lida+- `POST /message/edit` - Editar mensagem+- `POST /message/delete` - Deletar mensagem+- `POST /message/presence` - Status de presença (digitando/gravando)+- `POST /message/downloadmedia` - Download de mídia+- `POST /message/status` - Status de entrega/leitura++**Documentação completa:** [API de Mensagens](../guias-api/api-messages.md)++---++### Usuários (13 endpoints)++- `POST /user/info` - Informações do usuário+- `POST /user/check` - Verificar número no WhatsApp+- `POST /user/avatar` - Obter avatar+- `GET /user/contacts` - Listar contatos+- `GET /user/privacy` - Configurações de privacidade+- `POST /user/privacy` - Atualizar privacidade+- `POST /user/block` - Bloquear contato+- `POST /user/unblock` - Desbloquear contato+- `GET /user/blocklist` - Lista de bloqueados+- `POST /user/profilePicture` - Atualizar foto de perfil+- `POST /user/profileName` - Atualizar nome+- `POST /user/profileStatus` - Atualizar status/recado++**Documentação completa:** [API de Usuários](../guias-api/api-user.md)++---++### Grupos (11 endpoints)++- `GET /group/list` - Listar grupos+- `POST /group/create` - Criar grupo+- `POST /group/info` - Informações do grupo+- `POST /group/participant` - Gerenciar participantes+- `POST /group/photo` - Atualizar foto+- `POST /group/name` - Atualizar nome+- `POST /group/description` - Atualizar descrição+- `POST /group/invitelink` - Gerar link de convite+- `POST /group/join` - Entrar via link+- `POST /group/leave` - Sair do grupo+- `GET /group/myall` - Grupos do usuário++**Documentação completa:** [API de Grupos](../guias-api/api-groups.md)++---++### Chats (7 endpoints)++- `POST /chat/pin` - Fixar conversa+- `POST /chat/unpin` - Desfixar conversa+- `POST /chat/archive` - Arquivar+- `POST /chat/unarchive` - Desarquivar+- `POST /chat/mute` - Silenciar+- `POST /chat/unmute` - Reativar notificações+- `POST /chat/history-sync` - Sincronizar histórico++**Documentação completa:** [API de Chats](../guias-api/api-chats.md)++---++### Labels (6 endpoints)++- `POST /label/chat` - Adicionar label ao chat+- `POST /label/message` - Adicionar label à mensagem+- `POST /label/edit` - Editar label+- `GET /label/list` - Listar labels+- `POST /unlabel/chat` - Remover label do chat+- `POST /unlabel/message` - Remover label da mensagem++**Documentação completa:** [API de Labels](../guias-api/api-labels.md)++---++### Comunidades (3 endpoints)++- `POST /community/create` - Criar comunidade+- `POST /community/add` - Adicionar grupo+- `POST /community/remove` - Remover grupo++**Documentação completa:** [API de Comunidades](../guias-api/api-community.md)++---++### Newsletters (6 endpoints)++- `POST /newsletter/create` - Criar newsletter/canal+- `GET /newsletter/list` - Listar newsletters+- `POST /newsletter/info` - Informações da newsletter+- `POST /newsletter/link` - Gerar link de convite+- `POST /newsletter/subscribe` - Inscrever-se+- `POST /newsletter/messages` - Listar mensagens++**Documentação completa:** [API de Newsletters](../guias-api/api-newsletter.md)++---++### Chamadas (1 endpoint)++- `POST /call/reject` - Rejeitar chamada recebida++**Documentação completa:** [API de Chamadas](../guias-api/api-call.md)++---++## Recursos Adicionais++### Documentação Interativa++- **Swagger UI**: http://localhost:4000/swagger/index.html (quando servidor estiver rodando)+- Teste endpoints diretamente no navegador+- Visualize payloads de request/response+- Documentação completa com exemplos++### Guias de API++- [Visão Geral da API](../guias-api/api-overview.md)+- [Autenticação](../conceitos-core/authentication.md)+- [Sistema de Eventos](../recursos-avancados/events-system.md)++---++**Total de endpoints disponíveis: 79**++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/referencia/environment-variables.md b/docs/wiki/referencia/environment-variables.mdnew file mode 100644index 0000000..a1abf27--- /dev/null+++ b/docs/wiki/referencia/environment-variables.md@@ -0,0 +1,230 @@+# Variáveis de Ambiente++Referência rápida de variáveis de ambiente do Evolution GO.++Para documentação detalhada, consulte: [Configuração](../fundamentos/configuration.md)++---++## Obrigatórias++| Variável | Descrição | Exemplo |+|----------|-----------|---------|+| `GLOBAL_API_KEY` | Chave de autenticação da API | `df16caad-d0d2-41b2-bec5-75b90048a0db` |+| `DATABASE_SAVE_MESSAGES` | Salvar mensagens no banco | `false` |++---++## Servidor++| Variável | Padrão | Descrição |+|----------|--------|-----------|+| `SERVER_PORT` | `4000` | Porta HTTP |+| `CLIENT_NAME` | `evolution` | Nome identificador |+| `OS_NAME` | `Linux` | Sistema operacional |++---++## Banco de Dados++| Variável | Descrição |+|----------|-----------|+| `POSTGRES_AUTH_DB` | Connection string banco de autenticação |+| `POSTGRES_USERS_DB` | Connection string banco de usuários |++**Formato:**+```env+POSTGRES_AUTH_DB=postgresql://user:pass@host:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://user:pass@host:5432/evogo_users?sslmode=disable+```++---++## Logs++| Variável | Padrão | Valores | Descrição |+|----------|--------|---------|-----------|+| `WADEBUG` | `INFO` | `DEBUG`, `INFO`, `WARN`, `ERROR` | Nível de log |+| `LOGTYPE` | `console` | `console`, `file` | Destino de saída |+| `LOG_DIRECTORY` | `/app/logs` | - | Diretório de arquivos de log |+| `LOG_MAX_SIZE` | `100` | - | Tamanho máximo por arquivo (MB) |+| `LOG_MAX_BACKUPS` | `5` | - | Arquivos de backup a manter |+| `LOG_MAX_AGE` | `30` | - | Retenção em dias |+| `LOG_COMPRESS` | `true` | `true`/`false` | Compressão de logs antigos |++---++## Conexão e Comportamento++| Variável | Padrão | Descrição |+|----------|--------|-----------|+| `CONNECT_ON_STARTUP` | `false` | Conectar instâncias ao iniciar servidor |+| `WEBHOOKFILES` | `true` | Enviar URLs de mídia em webhooks |+| `QRCODE_MAX_COUNT` | `5` | Tentativas máximas de QR Code |+| `CHECK_USER_EXISTS` | `true` | Validar destinatário antes de enviar |++---++## Eventos++| Variável | Padrão | Descrição |+|----------|--------|-----------|+| `EVENT_IGNORE_GROUP` | `false` | Ignorar eventos de grupos |+| `EVENT_IGNORE_STATUS` | `true` | Ignorar eventos de status/stories |+| `WEBHOOK_URL` | - | URL para callbacks HTTP |++---++## RabbitMQ (AMQP)++| Variável | Descrição |+|----------|-----------|+| `AMQP_URL` | URL de conexão RabbitMQ |+| `AMQP_GLOBAL_ENABLED` | Habilitar filas globais |+| `AMQP_GLOBAL_EVENTS` | Eventos a publicar (separados por vírgula) |+| `AMQP_SPECIFIC_EVENTS` | Eventos específicos por instância |++**Exemplo:**+```env+AMQP_URL=amqp://user:pass@rabbitmq:5672/vhost+AMQP_GLOBAL_ENABLED=true+AMQP_GLOBAL_EVENTS=messages.upsert,messages.update,connection.update+```++---++## NATS++| Variável | Descrição |+|----------|-----------|+| `NATS_URL` | URL de conexão NATS |+| `NATS_GLOBAL_ENABLED` | Habilitar publicação global |+| `NATS_GLOBAL_EVENTS` | Eventos a publicar |++**Exemplo:**+```env+NATS_URL=nats://nats:4222+NATS_GLOBAL_ENABLED=true+NATS_GLOBAL_EVENTS=messages.upsert,connection.update+```++---++## MinIO/S3++| Variável | Descrição |+|----------|-----------|+| `MINIO_ENABLED` | Habilitar armazenamento S3-compatible |+| `MINIO_ENDPOINT` | Endpoint do servidor |+| `MINIO_ACCESS_KEY` | Access Key para autenticação |+| `MINIO_SECRET_KEY` | Secret Key para autenticação |+| `MINIO_BUCKET` | Nome do bucket |+| `MINIO_USE_SSL` | Utilizar HTTPS |+| `MINIO_REGION` | Região do bucket (AWS) |++**Exemplo:**+```env+MINIO_ENABLED=true+MINIO_ENDPOINT=localhost:9000+MINIO_ACCESS_KEY=minioadmin+MINIO_SECRET_KEY=minioadmin+MINIO_BUCKET=evolution-media+MINIO_USE_SSL=false+MINIO_REGION=us-east-1+```++---++## Proxy HTTP++| Variável | Descrição |+|----------|-----------|+| `PROXY_HOST` | Hostname do proxy |+| `PROXY_PORT` | Porta do proxy |+| `PROXY_USERNAME` | Usuário (opcional) |+| `PROXY_PASSWORD` | Senha (opcional) |++**Exemplo:**+```env+PROXY_HOST=proxy.empresa.com+PROXY_PORT=8080+PROXY_USERNAME=usuario+PROXY_PASSWORD=senha+```++---++## Recursos Adicionais++| Variável | Descrição |+|----------|-----------|+| `API_AUDIO_CONVERTER` | URL de serviço de conversão de áudio |+| `API_AUDIO_CONVERTER_KEY` | Chave de autenticação do conversor |++---++## Versão WhatsApp (Avançado)++| Variável | Descrição |+|----------|-----------|+| `WHATSAPP_VERSION_MAJOR` | Versão major do WhatsApp Web |+| `WHATSAPP_VERSION_MINOR` | Versão minor do WhatsApp Web |+| `WHATSAPP_VERSION_PATCH` | Versão patch do WhatsApp Web |++**⚠️ Atenção**: Modificar versão do WhatsApp pode resultar em bloqueio. Deixar vazio para usar versão automática.++---++## Exemplo Completo++```env+# Obrigatórias+GLOBAL_API_KEY=df16caad-d0d2-41b2-bec5-75b90048a0db+DATABASE_SAVE_MESSAGES=false++# Servidor+SERVER_PORT=4000+CLIENT_NAME=evolution+OS_NAME=Linux++# Banco de Dados+POSTGRES_AUTH_DB=postgresql://postgres:senha@postgres:5432/evogo_auth?sslmode=disable+POSTGRES_USERS_DB=postgresql://postgres:senha@postgres:5432/evogo_users?sslmode=disable++# Logs+WADEBUG=INFO+LOGTYPE=console++# Comportamento+CONNECT_ON_STARTUP=false+WEBHOOKFILES=true+CHECK_USER_EXISTS=true+EVENT_IGNORE_STATUS=true++# Webhook+WEBHOOK_URL=https://seu-servidor.com/webhook++# RabbitMQ (opcional)+AMQP_URL=amqp://admin:admin@rabbitmq:5672/default+AMQP_GLOBAL_ENABLED=true+AMQP_GLOBAL_EVENTS=messages.upsert,connection.update++# MinIO (opcional)+MINIO_ENABLED=true+MINIO_ENDPOINT=minio:9000+MINIO_ACCESS_KEY=minioadmin+MINIO_SECRET_KEY=minioadmin+MINIO_BUCKET=evolution-media+MINIO_USE_SSL=false+```++---++## Recursos++- **[Configuração Detalhada](../fundamentos/configuration.md)** - Documentação completa de cada variável+- **[.env.example](https://git.evoai.app/Evolution/evolution-go/blob/main/docker/examples/.env.example)** - Arquivo de exemplo com todas as variáveis++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/referencia/error-codes.md b/docs/wiki/referencia/error-codes.mdnew file mode 100644index 0000000..cb2dccd--- /dev/null+++ b/docs/wiki/referencia/error-codes.md@@ -0,0 +1,274 @@+# Códigos de Erro++Referência de códigos de erro HTTP e mensagens da aplicação.++## Códigos HTTP++| Código | Status | Descrição |+|--------|--------|-----------|+| `200` | OK | Requisição processada com sucesso |+| `201` | Created | Recurso criado com sucesso |+| `400` | Bad Request | Requisição inválida ou malformada |+| `401` | Unauthorized | Autenticação ausente ou inválida |+| `403` | Forbidden | Acesso negado ao recurso |+| `404` | Not Found | Recurso não encontrado |+| `409` | Conflict | Conflito com estado atual do recurso |+| `500` | Internal Server Error | Erro interno não tratado |++---++## Erros de Autenticação++### 401 Unauthorized++```json+{+ "error": "Unauthorized"+}+```++**Causa**: Header `apikey` ausente ou valor inválido.++**Resolução**:+```bash+curl -H "apikey: SUA-CHAVE-API" http://localhost:4000/endpoint+```++---++## Erros de Instância++### 404 Instance Not Found++```json+{+ "error": "Instance not found"+}+```++**Causa**: Instância com nome especificado não existe.++**Resolução**: Verificar nome da instância ou criar nova via `POST /instance/create`.++### 409 Instance Already Exists++```json+{+ "error": "Instance already exists"+}+```++**Causa**: Tentativa de criar instância com nome duplicado.++**Resolução**: Utilizar nome único ou deletar instância existente.++### Instance Not Connected++```json+{+ "error": "Instance is not connected"+}+```++**Causa**: Operação requer instância conectada ao WhatsApp.++**Resolução**: Conectar instância via QR Code (`POST /instance/connect`) ou pairing code.++---++## Erros de Validação++### 400 Invalid Phone Number++```json+{+ "error": "Invalid phone number format"+}+```++**Causa**: Formato de número incorreto.++**Resolução**: Utilizar formato internacional sem símbolos.+- Correto: `5511999999999` (DDI + DDD + número)+- Incorreto: `+55 (11) 99999-9999`, `11999999999`++### 400 Required Field Missing++```json+{+ "error": "Field 'instanceName' is required"+}+```++**Causa**: Campo obrigatório ausente no body da requisição.++**Resolução**: Incluir campo obrigatório no payload JSON.++### 400 Invalid JSON++```json+{+ "error": "Invalid JSON"+}+```++**Causa**: Sintaxe JSON inválida ou header Content-Type incorreto.++**Resolução**:+- Validar sintaxe JSON+- Incluir header: `Content-Type: application/json`++---++## Erros de Infraestrutura++### 500 Database Connection Error++```json+{+ "error": "Database connection failed"+}+```++**Causa**: Falha ao conectar com PostgreSQL.++**Diagnóstico**:+```bash+# Verificar status do PostgreSQL+docker-compose ps postgres++# Verificar logs+docker-compose logs postgres++# Testar conectividade+docker-compose exec evolution-go nc -zv postgres 5432+```++**Resolução**:+- Verificar variáveis `POSTGRES_AUTH_DB` e `POSTGRES_USERS_DB`+- Confirmar que PostgreSQL está rodando+- Validar credenciais de acesso++### 500 Queue Connection Error++```json+{+ "error": "Failed to connect to message queue"+}+```++**Causa**: Falha ao conectar com RabbitMQ/NATS.++**Resolução**:+- Verificar variável `AMQP_URL` ou `NATS_URL`+- Confirmar que serviço de fila está rodando+- Validar credenciais e permissões++---++## Erros de Negócio++### User Not Found on WhatsApp++```json+{+ "error": "User not found on WhatsApp"+}+```++**Causa**: Número destinatário não está registrado no WhatsApp.++**Resolução**: Verificar número ou desabilitar validação (`CHECK_USER_EXISTS=false`).++### Message Send Failed++```json+{+ "error": "Failed to send message",+ "details": "..."+}+```++**Causas comuns**:+- Número bloqueou sua instância+- Mensagem violou políticas do WhatsApp+- Instância foi bloqueada/banida+- Problema de conectividade++**Diagnóstico**:+```bash+# Verificar logs detalhados+docker-compose logs -f evolution-go++# Verificar status da instância+curl -H "apikey: SUA-CHAVE" \+ "http://localhost:4000/instance/status?instanceName=NOME"+```++---++## Debugging++### Habilitar Logs Detalhados++```env+WADEBUG=DEBUG+```++### Verificar Logs++```bash+# Docker Compose+docker-compose logs -f evolution-go++# Docker (container específico)+docker logs -f evolution-go --tail=100++# Arquivo (se LOGTYPE=file)+tail -f logs/evolution-go.log+```++### Logs Estruturados++Logs incluem:+- **Timestamp**: Data/hora do evento+- **Level**: DEBUG, INFO, WARN, ERROR+- **Module**: Componente que gerou o log+- **Message**: Descrição do evento+- **Context**: Dados adicionais (instanceName, userId, etc)++---++## Códigos de Erro por Categoria++### Autenticação (401, 403)+- API key inválida+- Token expirado+- Permissões insuficientes++### Validação (400)+- JSON malformado+- Campos obrigatórios ausentes+- Formato inválido++### Recurso (404, 409)+- Instância não encontrada+- Recurso duplicado+- Estado inconsistente++### Servidor (500, 503)+- Erro de banco de dados+- Timeout de operação+- Serviço indisponível++---++## Recursos Adicionais++- **[Debugging](../desenvolvimento/debugging.md)** - Guia completo de debugging+- **[FAQ](./faq.md)** - Problemas comuns e soluções+- **[Logs](../fundamentos/configuration.md#logs-e-debug)** - Configuração de logs++---++**Documentação Evolution GO v1.0**diff --git a/docs/wiki/referencia/faq.md b/docs/wiki/referencia/faq.mdnew file mode 100644index 0000000..8bb0f7b--- /dev/null+++ b/docs/wiki/referencia/faq.md@@ -0,0 +1,274 @@+# FAQ - Perguntas Frequentes++Respostas para questões comuns sobre o Evolution GO.++## Visão Geral++### O que é Evolution GO?++Gateway de API WhatsApp construído em Go que fornece interface RESTful para comunicação com o protocolo WhatsApp Web. Permite automação de mensagens, gerenciamento multi-instância e integração via APIs padronizadas.++### Diferença entre Evolution GO e Evolution API (Node.js)?++- **Evolution GO**: Implementação em Go, foco em performance e baixo consumo de recursos+- **Evolution API V2**: Implementação em Node.js/TypeScript, maior maturidade e conjunto de features++Ambos utilizam a biblioteca whatsmeow para conexão com WhatsApp.++### Suporte a múltiplas instâncias?++Sim. É possível gerenciar quantas instâncias forem necessárias, cada uma representando uma conta WhatsApp independente com sessão isolada.++---++## Instalação++### SQLite vs PostgreSQL++**PostgreSQL** é fortemente recomendado para produção devido a:+- Performance superior em ambientes multiusuário+- Suporte a conexões concorrentes+- Recursos empresariais (replicação, backup incremental)++SQLite é adequado apenas para desenvolvimento/testes.++### Geração de API Key++```bash+# UUID v4 (recomendado)+uuidgen++# OpenSSL+openssl rand -hex 32++# Python+python3 -c "import uuid; print(uuid.uuid4())"+```++---++## Operações++### Processo de Conexão++1. Criar instância: `POST /instance/create`+2. Iniciar conexão: `POST /instance/connect`+3. Obter QR Code: `GET /instance/qr?instanceName=NOME`+4. Escanear QR Code no WhatsApp (Aparelhos Conectados)+5. Aguardar estabelecimento da conexão++### Validade do QR Code++Aproximadamente 40 segundos. Após expiração, novo QR Code é gerado automaticamente até atingir `QRCODE_MAX_COUNT` (padrão: 5 tentativas).++### Envio para Múltiplos Destinatários++Realizar requisições individuais para cada destinatário. Para volume alto:+- Implementar fila de envio+- Adicionar delay entre requisições (2-5 segundos recomendado)+- Utilizar worker pool para paralelização controlada++### Limites de Envio++O WhatsApp não divulga limites oficiais, mas observa-se:+- Aproximadamente 1000 mensagens/dia para números não salvos+- Risco de bloqueio com padrões identificados como spam+- Recomendações:+ - Começar com volume baixo (~100/dia)+ - Escalar gradualmente+ - Personalizar mensagens+ - Evitar conteúdo idêntico em massa+ - Respeitar opt-out de usuários++### Recepção de Mensagens++Configure webhook ao criar instância ou via atualização:++```json+{+ "instanceName": "nome-instancia",+ "webhook": "https://seu-servidor.com/webhook"+}+```++Eventos serão enviados via POST HTTP para o endpoint configurado.++---++## Troubleshooting++### QR Code Não Exibido++**Diagnóstico**:+```bash+docker-compose logs -f evolution-go+```++**Soluções**:+- Verificar conectividade com banco de dados+- Deletar e recriar instância+- Verificar logs para erros específicos++### Falha no Envio de Mensagens++**Verificações**:+1. Status da conexão: `GET /instance/status?instanceName=NOME`+2. Formato do número: DDI + DDD + número (ex: `5511999999999`)+3. Validação do destinatário: `CHECK_USER_EXISTS=true`++### Desconexão Espontânea++**Causas comuns**:+- WhatsApp Web ativo em outro dispositivo+- Bloqueio preventivo do WhatsApp+- Instabilidade de rede+- Versão do protocolo desatualizada++**Resolução**: Reconectar via `POST /instance/reconnect`++### Webhook Não Recebe Eventos++**Verificações**:+- URL acessível publicamente (não localhost)+- Endpoint retorna status 200+- Firewall/proxy não bloqueando+- Logs: `docker-compose logs -f evolution-go | grep webhook`++---++## Performance++### Capacidade por Servidor++Estimativas baseadas em uso típico:++| RAM | CPU | Instâncias Estimadas |+|-----|-----|---------------------|+| 1GB | 1 core | 5-10 |+| 2GB | 2 cores | 20-30 |+| 4GB | 4 cores | 50-100 |+| 8GB | 8 cores | 200+ |++**Fatores de impacto**:+- Volume de mensagens+- Uso de webhook vs filas+- `DATABASE_SAVE_MESSAGES` habilitado+- Processamento de mídia++### Otimização++**Configuração**:+```env+# Desabilitar salvamento de mensagens+DATABASE_SAVE_MESSAGES=false++# Ignorar eventos desnecessários+EVENT_IGNORE_STATUS=true+EVENT_IGNORE_GROUP=false # conforme necessidade++# Usar PostgreSQL+POSTGRES_AUTH_DB=postgresql://...+POSTGRES_USERS_DB=postgresql://...+```++**Infraestrutura**:+- Connection pooling adequado+- Índices de banco otimizados+- Escalabilidade horizontal (múltiplos servidores)+- Load balancer para distribuição++---++## Segurança++### Proteção de API Key++- Não versionar no controle de código+- Utilizar variáveis de ambiente+- Rotação periódica (recomendado: 90 dias)+- HTTPS obrigatório em produção+- Rate limiting por chave++### Armazenamento de Mensagens++Configurar `DATABASE_SAVE_MESSAGES=false` se histórico não for necessário:+- Reduz uso de storage+- Melhora privacidade+- Aumenta performance++### Backup Seguro++```bash+# Backup com criptografia+docker exec postgres pg_dumpall -U postgres | \+ gzip | \+ gpg --encrypt --recipient [email protected] \+ > backup-$(date +%Y%m%d).sql.gz.gpg++# Restauração+gpg --decrypt backup-20250111.sql.gz.gpg | \+ gunzip | \+ docker exec -i postgres psql -U postgres+```++---++## Limitações do WhatsApp++### Envio para Números Não Salvos++WhatsApp limita envios para números não salvos na agenda. Boas práticas:+- Priorizar números salvos+- Aguardar resposta antes de enviar mais mensagens+- Evitar volume alto para números desconhecidos++### Prevenção de Banimento++**Práticas recomendadas**:+- Não enviar spam+- Respeitar opt-out de usuários+- Usar contas WhatsApp Business verificadas+- Adicionar delay entre mensagens+- Personalizar conteúdo++**Em caso de bloqueio**:+- Utilizar número diferente+- Considerar WhatsApp Business API oficial+- Revisar práticas de envio++---++## Desenvolvimento++### Contribuição++Consulte [Guia de Contribuição](../desenvolvimento/contributing.md) para processo de contribuição ao projeto.++### Reporte de Bugs++Utilize [Issues no GitLab](https://git.evoai.app/Evolution/evolution-go/issues) incluindo:+- Versão do Evolution GO+- Ambiente (Docker/local, SO)+- Steps to reproduce+- Logs relevantes+- Comportamento esperado vs observado++---++## Recursos++### Documentação+- [Guia de Instalação](../fundamentos/installation.md)+- [Configuração](../fundamentos/configuration.md)+- [Referência de API](./api-reference.md)+- [Swagger UI](http://localhost:4000/swagger/index.html)++### Suporte+- [Issues GitLab](https://git.evoai.app/Evolution/evolution-go/issues)+- [Documentação Completa](https://git.evoai.app/Evolution/evolution-go/-/wikis)++---++**Não encontrou resposta?** Abra uma [issue](https://git.evoai.app/Evolution/evolution-go/issues) com sua questão.++**Documentação Evolution GO v1.0**diff --git a/go.mod b/go.modnew file mode 100644index 0000000..e877705--- /dev/null+++ b/go.mod@@ -0,0 +1,103 @@+module github.com/EvolutionAPI/evolution-go++go 1.25.0++require (+ github.com/EvolutionAPI/evo-gate v0.1.2+ github.com/chai2010/webp v1.1.1+ github.com/gabriel-vasile/mimetype v1.4.5+ github.com/gin-gonic/gin v1.10.0+ github.com/gomessguii/logger v0.0.3+ github.com/google/uuid v1.6.0+ github.com/gorilla/websocket v1.5.3+ github.com/joho/godotenv v1.5.1+ github.com/lib/pq v1.10.9+ github.com/minio/minio-go/v7 v7.0.80+ github.com/nats-io/nats.go v1.39.0+ github.com/patrickmn/go-cache v2.1.0+incompatible+ github.com/rabbitmq/amqp091-go v1.10.0+ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e+ github.com/swaggo/files v1.0.1+ github.com/swaggo/gin-swagger v1.6.0+ github.com/swaggo/swag v1.16.3+ github.com/vincent-petithory/dataurl v1.0.0+ go.mau.fi/whatsmeow v0.0.0-00010101000000-000000000000+ golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a+ golang.org/x/image v0.0.0-20211028202545-6944b10bf410+ golang.org/x/net v0.50.0+ google.golang.org/protobuf v1.36.11+ gopkg.in/natefinch/lumberjack.v2 v2.2.1+ gorm.io/driver/postgres v1.5.9+ gorm.io/gorm v1.25.10+ modernc.org/sqlite v1.33.1+)++require (+ filippo.io/edwards25519 v1.1.0 // indirect+ github.com/KyleBanks/depth v1.2.1 // indirect+ github.com/beeper/argo-go v1.1.2 // indirect+ github.com/bytedance/sonic v1.12.2 // indirect+ github.com/bytedance/sonic/loader v0.2.0 // indirect+ github.com/cloudwego/base64x v0.1.4 // indirect+ github.com/cloudwego/iasm v0.2.0 // indirect+ github.com/coder/websocket v1.8.14 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirect+ github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect+ github.com/gin-contrib/sse v0.1.0 // indirect+ github.com/go-ini/ini v1.67.0 // indirect+ github.com/go-openapi/jsonpointer v0.21.0 // indirect+ github.com/go-openapi/jsonreference v0.21.0 // indirect+ github.com/go-openapi/spec v0.21.0 // indirect+ github.com/go-openapi/swag v0.23.0 // indirect+ github.com/go-playground/locales v0.14.1 // indirect+ github.com/go-playground/universal-translator v0.18.1 // indirect+ github.com/go-playground/validator/v10 v10.22.0 // indirect+ github.com/goccy/go-json v0.10.3 // indirect+ github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect+ github.com/jackc/pgpassfile v1.0.0 // indirect+ github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect+ github.com/jackc/pgx/v5 v5.5.5 // indirect+ github.com/jackc/puddle/v2 v2.2.1 // indirect+ github.com/jinzhu/inflection v1.0.0 // indirect+ github.com/jinzhu/now v1.1.5 // indirect+ github.com/josharian/intern v1.0.0 // indirect+ github.com/json-iterator/go v1.1.12 // indirect+ github.com/klauspost/compress v1.17.11 // indirect+ github.com/klauspost/cpuid/v2 v2.2.8 // indirect+ github.com/leodido/go-urn v1.4.0 // indirect+ github.com/mailru/easyjson v0.7.7 // indirect+ github.com/mattn/go-colorable v0.1.14 // indirect+ github.com/mattn/go-isatty v0.0.20 // indirect+ github.com/minio/md5-simd v1.1.2 // indirect+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect+ github.com/modern-go/reflect2 v1.0.2 // indirect+ github.com/nats-io/nkeys v0.4.9 // indirect+ github.com/nats-io/nuid v1.0.1 // indirect+ github.com/ncruces/go-strftime v0.1.9 // indirect+ github.com/pelletier/go-toml/v2 v2.2.3 // indirect+ github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect+ github.com/rogpeppe/go-internal v1.12.0 // indirect+ github.com/rs/xid v1.6.0 // indirect+ github.com/rs/zerolog v1.34.0 // indirect+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect+ github.com/ugorji/go/codec v1.2.12 // indirect+ github.com/vektah/gqlparser/v2 v2.5.27 // indirect+ go.mau.fi/libsignal v0.2.1 // indirect+ go.mau.fi/util v0.9.6 // indirect+ golang.org/x/arch v0.10.0 // indirect+ golang.org/x/crypto v0.48.0 // indirect+ golang.org/x/sync v0.19.0 // indirect+ golang.org/x/sys v0.41.0 // indirect+ golang.org/x/text v0.34.0 // indirect+ golang.org/x/tools v0.42.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+ modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect+ modernc.org/libc v1.55.3 // indirect+ modernc.org/mathutil v1.6.0 // indirect+ modernc.org/memory v1.8.0 // indirect+ modernc.org/strutil v1.2.0 // indirect+ modernc.org/token v1.1.0 // indirect+)++replace go.mau.fi/whatsmeow => ./whatsmeow-libdiff --git a/go.sum b/go.sumnew file mode 100644index 0000000..b2d291d--- /dev/null+++ b/go.sum@@ -0,0 +1,283 @@+filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=+filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=+github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=+github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=+github.com/EvolutionAPI/evo-gate v0.1.2 h1:ZPQ9SZ7OlajNU1pbtYqbMg1U/ZiUSKmlrYk0GHWOXkc=+github.com/EvolutionAPI/evo-gate v0.1.2/go.mod h1:48tcAgZ0yVojqLdmLpOSyWDGqPODBYXYRSEs2yIUI/w=+github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=+github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=+github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=+github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=+github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=+github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=+github.com/bytedance/sonic v1.12.2 h1:oaMFuRTpMHYLpCntGca65YWt5ny+wAceDERTkT2L9lg=+github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk=+github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=+github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM=+github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=+github.com/chai2010/webp v1.1.1 h1:jTRmEccAJ4MGrhFOrPMpNGIJ/eybIgwKpcACsrTEapk=+github.com/chai2010/webp v1.1.1/go.mod h1:0XVwvZWdjjdxpUEIf7b9g9VkHFnInUSYujwqTLEuldU=+github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=+github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=+github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=+github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=+github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=+github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=+github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=+github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=+github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4=+github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4=+github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=+github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=+github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=+github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=+github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=+github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=+github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=+github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=+github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=+github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=+github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=+github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=+github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=+github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=+github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=+github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=+github.com/go-playground/validator/v10 v10.22.0 h1:k6HsTZ0sTnROkhS//R0O+55JgM8C4Bx7ia+JlgcnOao=+github.com/go-playground/validator/v10 v10.22.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=+github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=+github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=+github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=+github.com/gomessguii/logger v0.0.3 h1:985MqDkp2Fi6IQ3eQ3NG7VXZo8flbWd+6QUj9hASWJA=+github.com/gomessguii/logger v0.0.3/go.mod h1:JBfDf2h4qUFaIjpE/0T4/jeLpIHopc73k+G9+iu9+ms=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=+github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=+github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=+github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=+github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=+github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=+github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=+github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=+github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=+github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=+github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=+github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=+github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=+github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=+github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=+github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=+github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=+github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=+github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=+github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=+github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=+github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=+github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=+github.com/minio/minio-go/v7 v7.0.80 h1:2mdUHXEykRdY/BigLt3Iuu1otL0JTogT0Nmltg0wujk=+github.com/minio/minio-go/v7 v7.0.80/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=+github.com/nats-io/nats.go v1.39.0 h1:2/yg2JQjiYYKLwDuBzV0FbB2sIV+eFNkEevlRi4n9lI=+github.com/nats-io/nats.go v1.39.0/go.mod h1:MgRb8oOdigA6cYpEPhXJuRVH6UE/V4jblJ2jQ27IXYM=+github.com/nats-io/nkeys v0.4.9 h1:qe9Faq2Gxwi6RZnZMXfmGMZkg3afLLOtrU+gDZJ35b0=+github.com/nats-io/nkeys v0.4.9/go.mod h1:jcMqs+FLG+W5YO36OX6wFIFcmpdAns+w1Wm6D3I/evE=+github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=+github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=+github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=+github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=+github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=+github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=+github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 h1:KPpdlQLZcHfTMQRi6bFQ7ogNO0ltFT4PmtwTLW4W+14=+github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=+github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=+github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=+github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=+github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=+github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=+github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=+github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=+github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=+github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=+github.com/swaggo/gin-swagger v1.6.0 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M=+github.com/swaggo/gin-swagger v1.6.0/go.mod h1:BG00cCEy294xtVpyIAHG6+e2Qzj/xKlRdOqDkvq0uzo=+github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg=+github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk=+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=+github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=+github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=+github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=+github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=+github.com/vincent-petithory/dataurl v1.0.0 h1:cXw+kPto8NLuJtlMsI152irrVw9fRDX8AbShPRpg2CI=+github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9CvnvxyvZy6I1MrG/U=+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=+go.mau.fi/libsignal v0.2.1 h1:vRZG4EzTn70XY6Oh/pVKrQGuMHBkAWlGRC22/85m9L0=+go.mau.fi/libsignal v0.2.1/go.mod h1:iVvjrHyfQqWajOUaMEsIfo3IqgVMrhWcPiiEzk7NgoU=+go.mau.fi/util v0.9.6 h1:2nsvxm49KhI3wrFltr0+wSUBlnQ4CMtykuELjpIU+ts=+go.mau.fi/util v0.9.6/go.mod h1:sIJpRH7Iy5Ad1SBuxQoatxtIeErgzxCtjd/2hCMkYMI=+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=+golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8=+golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=+golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=+golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=+golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a h1:ovFr6Z0MNmU7nH8VaX5xqw+05ST2uO1exVfZPVqRC5o=+golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=+golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ=+golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=+golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=+golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=+golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=+golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=+golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=+golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=+golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=+golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=+golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=+gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=+gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=+gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=+modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=+modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=+modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=+modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=+modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=+modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=+modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=+modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=+modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=+modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=+modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=+modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=+modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=+modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=+modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM=+modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k=+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=+nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=diff --git a/manager/dist/assets/index-BsMXpWP7.css b/manager/dist/assets/index-BsMXpWP7.cssnew file mode 100644index 0000000..e97c33b--- /dev/null+++ b/manager/dist/assets/index-BsMXpWP7.css@@ -0,0 +1 @@+@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-100: oklch(93.6% .032 17.717);--color-red-500: oklch(63.7% .237 25.331);--color-red-600: oklch(57.7% .245 27.325);--color-red-700: oklch(50.5% .213 27.518);--color-red-800: oklch(44.4% .177 26.899);--color-orange-100: oklch(95.4% .038 75.164);--color-orange-500: oklch(70.5% .213 47.604);--color-orange-600: oklch(64.6% .222 41.116);--color-orange-700: oklch(55.3% .195 38.402);--color-yellow-100: oklch(97.3% .071 103.193);--color-yellow-400: oklch(85.2% .199 91.936);--color-yellow-500: oklch(79.5% .184 86.047);--color-yellow-600: oklch(68.1% .162 75.834);--color-yellow-700: oklch(55.4% .135 66.442);--color-green-50: oklch(98.2% .018 155.826);--color-green-100: oklch(96.2% .044 156.743);--color-green-200: oklch(92.5% .084 155.995);--color-green-400: oklch(79.2% .209 151.711);--color-green-500: oklch(72.3% .219 149.579);--color-green-600: oklch(62.7% .194 149.214);--color-green-700: oklch(52.7% .154 150.069);--color-green-800: oklch(44.8% .119 151.328);--color-blue-50: oklch(97% .014 254.604);--color-blue-100: oklch(93.2% .032 255.585);--color-blue-200: oklch(88.2% .059 254.128);--color-blue-400: oklch(70.7% .165 254.624);--color-blue-500: oklch(62.3% .214 259.815);--color-blue-600: oklch(54.6% .245 262.881);--color-blue-700: oklch(48.8% .243 264.376);--color-blue-800: oklch(42.4% .199 265.638);--color-blue-900: oklch(37.9% .146 265.522);--color-purple-50: oklch(97.7% .014 308.299);--color-purple-100: oklch(94.6% .033 307.174);--color-purple-200: oklch(90.2% .063 306.703);--color-purple-500: oklch(62.7% .265 303.9);--color-purple-600: oklch(55.8% .288 302.321);--color-purple-700: oklch(49.6% .265 301.924);--color-purple-900: oklch(38.1% .176 304.987);--color-pink-50: oklch(97.1% .014 343.198);--color-pink-500: oklch(65.6% .241 354.308);--color-pink-600: oklch(59.2% .249 .584);--color-slate-50: oklch(98.4% .003 247.858);--color-slate-800: oklch(27.9% .041 260.031);--color-slate-900: oklch(20.8% .042 265.755);--color-gray-400: oklch(70.7% .022 261.325);--color-gray-600: oklch(44.6% .03 256.802);--color-gray-700: oklch(37.3% .034 259.733);--color-gray-900: oklch(21% .034 264.665);--color-black: #000;--color-white: #fff;--spacing: .25rem;--container-xs: 20rem;--container-sm: 24rem;--container-md: 28rem;--container-lg: 32rem;--container-2xl: 42rem;--container-4xl: 56rem;--container-6xl: 72rem;--text-xs: .75rem;--text-xs--line-height: calc(1 / .75);--text-sm: .875rem;--text-sm--line-height: calc(1.25 / .875);--text-base: 1rem;--text-base--line-height: 1.5 ;--text-lg: 1.125rem;--text-lg--line-height: calc(1.75 / 1.125);--text-xl: 1.25rem;--text-xl--line-height: calc(1.75 / 1.25);--text-2xl: 1.5rem;--text-2xl--line-height: calc(2 / 1.5);--text-3xl: 1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl: 2.25rem;--text-4xl--line-height: calc(2.5 / 2.25);--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--font-weight-bold: 700;--tracking-tight: -.025em;--tracking-widest: .1em;--leading-tight: 1.25;--leading-snug: 1.375;--leading-relaxed: 1.625;--radius-xs: .125rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--animate-pulse: pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--aspect-video: 16 / 9;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-background: var(--background);--color-foreground: var(--foreground);--color-primary: var(--primary);--color-primary-foreground: var(--primary-foreground);--color-secondary: var(--secondary);--color-secondary-foreground: var(--secondary-foreground);--color-muted: var(--muted);--color-muted-foreground: var(--muted-foreground);--color-accent: var(--accent);--color-accent-foreground: var(--accent-foreground);--color-destructive: var(--destructive);--color-destructive-foreground: var(--destructive-foreground);--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring)}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}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;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-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}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor}@supports (color: color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\@container\/card-header{container-type:inline-size;container-name:card-header}.pointer-events-none{pointer-events:none}.invisible{visibility:hidden}.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}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.inset-x-0{inset-inline:calc(var(--spacing) * 0)}.inset-y-0{inset-block:calc(var(--spacing) * 0)}.-top-2{top:calc(var(--spacing) * -2)}.-top-12{top:calc(var(--spacing) * -12)}.top-0{top:calc(var(--spacing) * 0)}.top-1\.5{top:calc(var(--spacing) * 1.5)}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-3\.5{top:calc(var(--spacing) * 3.5)}.top-4{top:calc(var(--spacing) * 4)}.top-\[1px\]{top:1px}.top-\[50\%\]{top:50%}.top-\[60\%\]{top:60%}.top-full{top:100%}.-right-0{right:calc(var(--spacing) * -0)}.-right-2{right:calc(var(--spacing) * -2)}.-right-12{right:calc(var(--spacing) * -12)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.-bottom-0{bottom:calc(var(--spacing) * -0)}.-bottom-12{bottom:calc(var(--spacing) * -12)}.bottom-0{bottom:calc(var(--spacing) * 0)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:calc(var(--spacing) * 0)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.left-\[50\%\]{left:50%}.isolate{isolation:isolate}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[1\]{z-index:1}.col-span-2{grid-column:span 2 / span 2}.col-span-3{grid-column:span 3 / span 3}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2 / span 2}.row-span-3{grid-row:span 3 / span 3}.row-start-1{grid-row-start:1}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-2{margin-inline:calc(var(--spacing) * 2)}.mx-3\.5{margin-inline:calc(var(--spacing) * 3.5)}.mx-auto{margin-inline:auto}.my-0\.5{margin-block:calc(var(--spacing) * .5)}.my-1{margin-block:calc(var(--spacing) * 1)}.my-4{margin-block:calc(var(--spacing) * 4)}.-mt-1{margin-top:calc(var(--spacing) * -1)}.-mt-4{margin-top:calc(var(--spacing) * -4)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.-ml-4{margin-left:calc(var(--spacing) * -4)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-8{margin-left:calc(var(--spacing) * 8)}.ml-12{margin-left:calc(var(--spacing) * 12)}.ml-auto{margin-left:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-row{display:table-row}.field-sizing-content{field-sizing:content}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:var(--aspect-video)}.size-\(--cell-size\){width:var(--cell-size);height:var(--cell-size)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-2\.5{width:calc(var(--spacing) * 2.5);height:calc(var(--spacing) * 2.5)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-auto{width:auto;height:auto}.size-full{width:100%;height:100%}.h-\(--cell-size\){height:var(--cell-size)}.h-1{height:calc(var(--spacing) * 1)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-32{height:calc(var(--spacing) * 32)}.h-48{height:calc(var(--spacing) * 48)}.h-\[1\.15rem\]{height:1.15rem}.h-\[100px\]{height:100px}.h-\[150px\]{height:150px}.h-\[200px\]{height:200px}.h-\[300px\]{height:300px}.h-\[400px\]{height:400px}.h-\[500px\]{height:500px}.h-\[calc\(100\%-1px\)\]{height:calc(100% - 1px)}.h-\[var\(--radix-navigation-menu-viewport-height\)\]{height:var(--radix-navigation-menu-viewport-height)}.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}.h-svh{height:100svh}.max-h-\(--radix-context-menu-content-available-height\){max-height:var(--radix-context-menu-content-available-height)}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.max-h-\[80vh\]{max-height:80vh}.max-h-\[300px\]{max-height:300px}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-4{min-height:calc(var(--spacing) * 4)}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[80px\]{min-height:80px}.min-h-\[100px\]{min-height:100px}.min-h-\[100vh\]{min-height:100vh}.min-h-svh{min-height:100svh}.w-\(--cell-size\){width:var(--cell-size)}.w-0{width:calc(var(--spacing) * 0)}.w-1{width:calc(var(--spacing) * 1)}.w-1\/2{width:50%}.w-2{width:calc(var(--spacing) * 2)}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-2\/3{width:calc(2/3 * 100%)}.w-3{width:calc(var(--spacing) * 3)}.w-3\/4{width:75%}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-18{width:calc(var(--spacing) * 18)}.w-20{width:calc(var(--spacing) * 20)}.w-24{width:calc(var(--spacing) * 24)}.w-32{width:calc(var(--spacing) * 32)}.w-48{width:calc(var(--spacing) * 48)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-72{width:calc(var(--spacing) * 72)}.w-80{width:calc(var(--spacing) * 80)}.w-96{width:calc(var(--spacing) * 96)}.w-\[--radix-dropdown-menu-trigger-width\]{width:--radix-dropdown-menu-trigger-width}.w-\[50px\]{width:50px}.w-\[100px\]{width:100px}.w-\[180px\]{width:180px}.w-\[200px\]{width:200px}.w-\[250px\]{width:250px}.w-\[280px\]{width:280px}.w-\[300px\]{width:300px}.w-\[350px\]{width:350px}.w-\[400px\]{width:400px}.w-\[500px\]{width:500px}.w-\[600px\]{width:600px}.w-\[var\(--sidebar-width\)\]{width:var(--sidebar-width)}.w-auto{width:auto}.w-fit{width:fit-content}.w-full{width:100%}.w-max{width:max-content}.w-px{width:1px}.max-w-\(--skeleton-width\){max-width:var(--skeleton-width)}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.max-w-lg{max-width:var(--container-lg)}.max-w-max{max-width:max-content}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xs{max-width:var(--container-xs)}.min-w-\(--cell-size\){min-width:var(--cell-size)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-8{min-width:calc(var(--spacing) * 8)}.min-w-9{min-width:calc(var(--spacing) * 9)}.min-w-10{min-width:calc(var(--spacing) * 10)}.min-w-56{min-width:calc(var(--spacing) * 56)}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.flex-1{flex:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.origin-\(--radix-context-menu-content-transform-origin\){transform-origin:var(--radix-context-menu-content-transform-origin)}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.origin-\(--radix-hover-card-content-transform-origin\){transform-origin:var(--radix-hover-card-content-transform-origin)}.origin-\(--radix-menubar-content-transform-origin\){transform-origin:var(--radix-menubar-content-transform-origin)}.origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.origin-\(--radix-tooltip-content-transform-origin\){transform-origin:var(--radix-tooltip-content-transform-origin)}.-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-px{--tw-translate-x: -1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-\[-50\%\]{--tw-translate-x: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-px{--tw-translate-x: 1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-0\.5{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[calc\(-50\%_-_2px\)\]{--tw-translate-y: calc(-50% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-45{rotate:45deg}.rotate-90{rotate:90deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-caret-blink{animation:caret-blink 1.25s ease-out infinite}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize-none{resize:none}.scroll-my-1{scroll-margin-block:calc(var(--spacing) * 1)}.scroll-py-1{scroll-padding-block:calc(var(--spacing) * 1)}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.list-none{list-style-type:none}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.auto-rows-min{grid-auto-rows:min-content}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-\[0_1fr\]{grid-template-columns:0 1fr}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.justify-items-start{justify-items:start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-0>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 0) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 0) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 8) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-y-reverse)))}:where(.-space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * -2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * -2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 4) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-6>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 6) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[4px\]{border-radius:4px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:calc(infinity * 1px)}.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:calc(var(--radius) + 4px)}.rounded-xs{border-radius:var(--radius-xs)}.rounded-l-md{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.rounded-r-md{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-\[1\.5px\]{border-style:var(--tw-border-style);border-width:1.5px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style: dashed;border-style:dashed}.border-\(--color-border\){border-color:var(--color-border)}.border-background{border-color:var(--background)}.border-blue-200{border-color:var(--color-blue-200)}.border-border\/50{border-color:var(--border)}@supports (color: color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--border) 50%,transparent)}}.border-current{border-color:currentcolor}.border-destructive{border-color:var(--destructive)}.border-destructive\/20{border-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.border-destructive\/20{border-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.border-gray-700{border-color:var(--color-gray-700)}.border-green-200{border-color:var(--color-green-200)}.border-green-500{border-color:var(--color-green-500)}.border-input{border-color:var(--input)}.border-muted{border-color:var(--muted)}.border-primary{border-color:var(--primary)}.border-purple-100{border-color:var(--color-purple-100)}.border-purple-200{border-color:var(--color-purple-200)}.border-sidebar-border{border-color:var(--sidebar-border)}.border-transparent{border-color:transparent}.border-white{border-color:var(--color-white)}.border-yellow-500{border-color:var(--color-yellow-500)}.border-t-transparent{border-top-color:transparent}.border-l-transparent{border-left-color:transparent}.bg-\(--color-bg\){background-color:var(--color-bg)}.bg-accent{background-color:var(--accent)}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\/50{background-color:color-mix(in srgb,#000 50%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-100{background-color:var(--color-blue-100)}.bg-blue-500{background-color:var(--color-blue-500)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-border{background-color:var(--border)}.bg-card{background-color:var(--card)}.bg-destructive{background-color:var(--destructive)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.bg-foreground{background-color:var(--foreground)}.bg-gray-400{background-color:var(--color-gray-400)}.bg-gray-600{background-color:var(--color-gray-600)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-500{background-color:var(--color-green-500)}.bg-green-600{background-color:var(--color-green-600)}.bg-muted{background-color:var(--muted)}.bg-muted\/50{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.bg-muted\/50{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}.bg-orange-100{background-color:var(--color-orange-100)}.bg-orange-500{background-color:var(--color-orange-500)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-popover{background-color:var(--popover)}.bg-primary{background-color:var(--primary)}.bg-primary\/10{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary) 10%,transparent)}}.bg-primary\/20{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--primary) 20%,transparent)}}.bg-purple-100{background-color:var(--color-purple-100)}.bg-purple-500{background-color:var(--color-purple-500)}.bg-purple-600{background-color:var(--color-purple-600)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500{background-color:var(--color-red-500)}.bg-red-600{background-color:var(--color-red-600)}.bg-secondary{background-color:var(--secondary)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-sidebar-primary{background-color:var(--sidebar-primary)}.bg-slate-50{background-color:var(--color-slate-50)}.bg-transparent{background-color:transparent}.bg-white{background-color:var(--color-white)}.bg-white\/60{background-color:color-mix(in srgb,#fff 60%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white) 60%,transparent)}}.bg-white\/80{background-color:color-mix(in srgb,#fff 80%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/80{background-color:color-mix(in oklab,var(--color-white) 80%,transparent)}}.bg-yellow-100{background-color:var(--color-yellow-100)}.bg-yellow-500{background-color:var(--color-yellow-500)}.bg-yellow-600{background-color:var(--color-yellow-600)}.bg-gradient-to-b{--tw-gradient-position: to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-br{--tw-gradient-position: to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-r{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-400{--tw-gradient-from: var(--color-blue-400);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500{--tw-gradient-from: var(--color-blue-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500\/20{--tw-gradient-from: color-mix(in srgb, oklch(62.3% .214 259.815) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-blue-500\/20{--tw-gradient-from: color-mix(in oklab, var(--color-blue-500) 20%, transparent)}}.from-muted\/50{--tw-gradient-from: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-muted\/50{--tw-gradient-from: color-mix(in oklab, var(--muted) 50%, transparent)}}.from-purple-50{--tw-gradient-from: var(--color-purple-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-purple-500{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-white{--tw-gradient-from: var(--color-white);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-blue-600\/20{--tw-gradient-to: color-mix(in srgb, oklch(54.6% .245 262.881) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.to-blue-600\/20{--tw-gradient-to: color-mix(in oklab, var(--color-blue-600) 20%, transparent)}}.to-gray-900{--tw-gradient-to: var(--color-gray-900);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-muted{--tw-gradient-to: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-50{--tw-gradient-to: var(--color-pink-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-500{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-purple-600{--tw-gradient-to: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-blue-400{fill:var(--color-blue-400)}.fill-current{fill:currentcolor}.fill-primary{fill:var(--primary)}.fill-yellow-400{fill:var(--color-yellow-400)}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing) * 0)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[3px\]{padding:3px}.p-px{padding:1px}.px-\(--cell-size\){padding-inline:var(--cell-size)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-0{padding-top:calc(var(--spacing) * 0)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-1{padding-right:calc(var(--spacing) * 1)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-0{padding-bottom:calc(var(--spacing) * 0)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading, var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading, var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading, var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading, var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading, var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading, var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.text-\[0\.8rem\]{font-size:.8rem}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading: 1;line-height:1}.leading-relaxed{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading: var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading: var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight: var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking: var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-widest{--tw-tracking: var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.break-words{overflow-wrap:break-word}.whitespace-nowrap{white-space:nowrap}.text-accent-foreground{color:var(--accent-foreground)}.text-blue-400{color:var(--color-blue-400)}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-blue-700{color:var(--color-blue-700)}.text-blue-800{color:var(--color-blue-800)}.text-blue-900{color:var(--color-blue-900)}.text-card-foreground{color:var(--card-foreground)}.text-current{color:currentcolor}.text-destructive{color:var(--destructive)}.text-destructive-foreground{color:var(--destructive-foreground)}.text-foreground{color:var(--foreground)}.text-green-400{color:var(--color-green-400)}.text-green-500{color:var(--color-green-500)}.text-green-600{color:var(--color-green-600)}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted-foreground{color:var(--muted-foreground)}.text-orange-600{color:var(--color-orange-600)}.text-orange-700{color:var(--color-orange-700)}.text-pink-600{color:var(--color-pink-600)}.text-popover-foreground{color:var(--popover-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-purple-500{color:var(--color-purple-500)}.text-purple-600{color:var(--color-purple-600)}.text-purple-700{color:var(--color-purple-700)}.text-purple-900{color:var(--color-purple-900)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-sidebar-foreground{color:var(--sidebar-foreground)}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color: color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground) 70%,transparent)}}.text-sidebar-primary-foreground{color:var(--sidebar-primary-foreground)}.text-white{color:var(--color-white)}.text-yellow-400{color:var(--color-yellow-400)}.text-yellow-600{color:var(--color-yellow-600)}.text-yellow-700{color:var(--color-yellow-700)}.capitalize{text-transform:capitalize}.italic{font-style:italic}.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,)}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0%}.opacity-50{opacity:50%}.opacity-70{opacity:70%}.opacity-75{opacity:75%}.opacity-90{opacity:90%}.opacity-100{opacity:100%}.shadow{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-border)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 8px 10px -6px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-0{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-primary{--tw-ring-color: var(--primary)}.ring-ring\/50{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.ring-ring\/50{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.ring-sidebar-ring{--tw-ring-color: var(--sidebar-ring)}.ring-offset-background{--tw-ring-offset-color: var(--background)}.outline-hidden{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline:2px solid transparent;outline-offset:2px}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[margin\,opacity\]{transition-property:margin,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\]{transition-property:width,height;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-none{transition-property:none}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-300{--tw-duration: .3s;transition-duration:.3s}.duration-1000{--tw-duration: 1s;transition-duration:1s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-linear{--tw-ease: linear;transition-timing-function:linear}.fade-in-0{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.outline-none{--tw-outline-style: none;outline-style:none}.select-all{-webkit-user-select:all;user-select:all}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.\[--cell-size\:--spacing\(8\)\]{--cell-size: calc(var(--spacing) * 8)}.group-focus-within\/menu-item\:opacity-100:is(:where(.group\/menu-item):focus-within *){opacity:100%}@media(hover:hover){.group-hover\/menu-item\:opacity-100:is(:where(.group\/menu-item):hover *){opacity:100%}}.group-has-data-\[sidebar\=menu-action\]\/menu-item\:pr-8:is(:where(.group\/menu-item):has(*[data-sidebar=menu-action]) *){padding-right:calc(var(--spacing) * 8)}.group-has-\[\[data-collapsible\=icon\]\]\/sidebar-wrapper\:h-12:is(:where(.group\/sidebar-wrapper):has(*:is([data-collapsible=icon])) *){height:calc(var(--spacing) * 12)}.group-data-\[collapsible\=icon\]\:-mt-8:is(:where(.group)[data-collapsible=icon] *){margin-top:calc(var(--spacing) * -8)}.group-data-\[collapsible\=icon\]\:hidden:is(:where(.group)[data-collapsible=icon] *){display:none}.group-data-\[collapsible\=icon\]\:size-8\!:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--spacing) * 8)!important;height:calc(var(--spacing) * 8)!important}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem)}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\+2px\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group-data-\[collapsible\=icon\]\:w-\[var\(--sidebar-width-icon\)\]:is(:where(.group)[data-collapsible=icon] *){width:var(--sidebar-width-icon)}.group-data-\[collapsible\=icon\]\:overflow-hidden:is(:where(.group)[data-collapsible=icon] *){overflow:hidden}.group-data-\[collapsible\=icon\]\:p-0\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 0)!important}.group-data-\[collapsible\=icon\]\:p-2\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 2)!important}.group-data-\[collapsible\=icon\]\:opacity-0:is(:where(.group)[data-collapsible=icon] *){opacity:0%}.group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){right:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){left:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:w-0:is(:where(.group)[data-collapsible=offcanvas] *){width:calc(var(--spacing) * 0)}.group-data-\[collapsible\=offcanvas\]\:translate-x-0:is(:where(.group)[data-collapsible=offcanvas] *){--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:50%}.group-data-\[focused\=true\]\/day\:relative:is(:where(.group\/day)[data-focused=true] *){position:relative}.group-data-\[focused\=true\]\/day\:z-10:is(:where(.group\/day)[data-focused=true] *){z-index:10}.group-data-\[focused\=true\]\/day\:border-ring:is(:where(.group\/day)[data-focused=true] *){border-color:var(--ring)}.group-data-\[focused\=true\]\/day\:ring-\[3px\]:is(:where(.group\/day)[data-focused=true] *){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.group-data-\[side\=left\]\:-right-4:is(:where(.group)[data-side=left] *){right:calc(var(--spacing) * -4)}.group-data-\[side\=left\]\:border-r:is(:where(.group)[data-side=left] *){border-right-style:var(--tw-border-style);border-right-width:1px}.group-data-\[side\=right\]\:left-0:is(:where(.group)[data-side=right] *){left:calc(var(--spacing) * 0)}.group-data-\[side\=right\]\:rotate-180:is(:where(.group)[data-side=right] *){rotate:180deg}.group-data-\[side\=right\]\:border-l:is(:where(.group)[data-side=right] *){border-left-style:var(--tw-border-style);border-left-width:1px}.group-data-\[state\=open\]\:rotate-180:is(:where(.group)[data-state=open] *){rotate:180deg}.group-data-\[state\=open\]\/collapsible\:rotate-180:is(:where(.group\/collapsible)[data-state=open] *){rotate:180deg}.group-data-\[variant\=floating\]\:rounded-lg:is(:where(.group)[data-variant=floating] *){border-radius:var(--radius)}.group-data-\[variant\=floating\]\:border:is(:where(.group)[data-variant=floating] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[variant\=floating\]\:border-sidebar-border:is(:where(.group)[data-variant=floating] *){border-color:var(--sidebar-border)}.group-data-\[variant\=floating\]\:shadow-sm:is(:where(.group)[data-variant=floating] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:block:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){display:block}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){text-align:center}.group-data-\[vaul-drawer-direction\=top\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=top] *){text-align:center}.group-data-\[viewport\=false\]\/navigation-menu\:top-full:is(:where(.group\/navigation-menu)[data-viewport=false] *){top:100%}.group-data-\[viewport\=false\]\/navigation-menu\:mt-1\.5:is(:where(.group\/navigation-menu)[data-viewport=false] *){margin-top:calc(var(--spacing) * 1.5)}.group-data-\[viewport\=false\]\/navigation-menu\:overflow-hidden:is(:where(.group\/navigation-menu)[data-viewport=false] *){overflow:hidden}.group-data-\[viewport\=false\]\/navigation-menu\:rounded-md:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-radius:calc(var(--radius) - 2px)}.group-data-\[viewport\=false\]\/navigation-menu\:border:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[viewport\=false\]\/navigation-menu\:bg-popover:is(:where(.group\/navigation-menu)[data-viewport=false] *){background-color:var(--popover)}.group-data-\[viewport\=false\]\/navigation-menu\:text-popover-foreground:is(:where(.group\/navigation-menu)[data-viewport=false] *){color:var(--popover-foreground)}.group-data-\[viewport\=false\]\/navigation-menu\:shadow:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[viewport\=false\]\/navigation-menu\:duration-200:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-duration: .2s;transition-duration:.2s}@media(hover:hover){.peer-hover\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button):hover~*){color:var(--sidebar-accent-foreground)}}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:50%}.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button)[data-active=true]~*){color:var(--sidebar-accent-foreground)}.peer-data-\[size\=default\]\/menu-button\:top-1\.5:is(:where(.peer\/menu-button)[data-size=default]~*){top:calc(var(--spacing) * 1.5)}.peer-data-\[size\=lg\]\/menu-button\:top-2\.5:is(:where(.peer\/menu-button)[data-size=lg]~*){top:calc(var(--spacing) * 2.5)}.peer-data-\[size\=sm\]\/menu-button\:top-1:is(:where(.peer\/menu-button)[data-size=sm]~*){top:calc(var(--spacing) * 1)}.selection\:bg-primary *::selection{background-color:var(--primary)}.selection\:bg-primary::selection{background-color:var(--primary)}.selection\:text-primary-foreground *::selection{color:var(--primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);inset:calc(var(--spacing) * -2)}.after\:inset-y-0:after{content:var(--tw-content);inset-block:calc(var(--spacing) * 0)}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:calc(var(--spacing) * 1)}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[collapsible\=offcanvas\]\:after\:left-full:is(:where(.group)[data-collapsible=offcanvas] *):after{content:var(--tw-content);left:100%}.first\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\:border-l:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.last\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}@media(hover:hover){.hover\:border-muted-foreground\/50:hover{border-color:var(--muted-foreground)}@supports (color: color-mix(in lab,red,red)){.hover\:border-muted-foreground\/50:hover{border-color:color-mix(in oklab,var(--muted-foreground) 50%,transparent)}}}@media(hover:hover){.hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}}@media(hover:hover){.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){.hover\:bg-gray-700:hover{background-color:var(--color-gray-700)}}@media(hover:hover){.hover\:bg-green-700:hover{background-color:var(--color-green-700)}}@media(hover:hover){.hover\:bg-muted:hover{background-color:var(--muted)}}@media(hover:hover){.hover\:bg-muted\/50:hover{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}}@media(hover:hover){.hover\:bg-orange-700:hover{background-color:var(--color-orange-700)}}@media(hover:hover){.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){.hover\:bg-purple-700:hover{background-color:var(--color-purple-700)}}@media(hover:hover){.hover\:bg-red-700:hover{background-color:var(--color-red-700)}}@media(hover:hover){.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--secondary) 80%,transparent)}}}@media(hover:hover){.hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.hover\:bg-white:hover{background-color:var(--color-white)}}@media(hover:hover){.hover\:bg-yellow-700:hover{background-color:var(--color-yellow-700)}}@media(hover:hover){.hover\:from-purple-600:hover{--tw-gradient-from: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:to-pink-600:hover{--tw-gradient-to: var(--color-pink-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}@media(hover:hover){.hover\:text-destructive:hover{color:var(--destructive)}}@media(hover:hover){.hover\:text-foreground:hover{color:var(--foreground)}}@media(hover:hover){.hover\:text-muted-foreground:hover{color:var(--muted-foreground)}}@media(hover:hover){.hover\:text-primary:hover{color:var(--primary)}}@media(hover:hover){.hover\:text-sidebar-accent-foreground:hover{color:var(--sidebar-accent-foreground)}}@media(hover:hover){.hover\:underline:hover{text-decoration-line:underline}}@media(hover:hover){.hover\:opacity-90:hover{opacity:90%}}@media(hover:hover){.hover\:opacity-100:hover{opacity:100%}}@media(hover:hover){.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-accent)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:ring-4:hover{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:group-data-\[collapsible\=offcanvas\]\:bg-sidebar:hover:is(:where(.group)[data-collapsible=offcanvas] *){background-color:var(--sidebar)}}@media(hover:hover){.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:var(--sidebar-border)}}.focus\:z-10:focus{z-index:10}.focus\:bg-accent:focus{background-color:var(--accent)}.focus\:text-accent-foreground:focus{color:var(--accent-foreground)}.focus\:shadow-md:focus{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color: var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:z-10:focus-visible{z-index:10}.focus-visible\:border-ring:focus-visible{border-color:var(--ring)}.focus-visible\:ring-1:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-4:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(72.3% .219 149.579) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-green-500) 20%, transparent)}}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: var(--ring)}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(79.5% .184 86.047) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-yellow-500) 20%, transparent)}}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:outline-hidden:focus-visible{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus-visible\:outline-hidden:focus-visible{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:outline-1:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-ring:focus-visible{outline-color:var(--ring)}.focus-visible\:outline-none:focus-visible{--tw-outline-style: none;outline-style:none}.active\:bg-sidebar-accent:active{background-color:var(--sidebar-accent)}.active\:text-sidebar-accent-foreground:active{color:var(--sidebar-accent-foreground)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:50%}:where(*[data-side=left]) .in-data-\[side\=left\]\:cursor-w-resize{cursor:w-resize}:where(*[data-side=right]) .in-data-\[side\=right\]\:cursor-e-resize{cursor:e-resize}.has-focus\:border-ring:has(*:focus){border-color:var(--ring)}.has-focus\:ring-\[3px\]:has(*:focus){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.has-disabled\:opacity-50:has(*:disabled){opacity:50%}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has(*[data-slot=card-action]){grid-template-columns:1fr auto}.has-data-\[variant\=inset\]\:bg-sidebar:has(*[data-variant=inset]){background-color:var(--sidebar)}.has-\[\>svg\]\:grid-cols-\[calc\(var\(--spacing\)\*4\)_1fr\]:has(>svg){grid-template-columns:calc(var(--spacing) * 4) 1fr}.has-\[\>svg\]\:gap-x-3:has(>svg){column-gap:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing) * 4)}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:50%}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.aria-selected\:text-muted-foreground[aria-selected=true]{color:var(--muted-foreground)}.data-\[active\=true\]\:z-10[data-active=true]{z-index:10}.data-\[active\=true\]\:border-ring[data-active=true]{border-color:var(--ring)}.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:var(--sidebar-accent)}.data-\[active\=true\]\:font-medium[data-active=true]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.data-\[active\=true\]\:text-accent-foreground[data-active=true]{color:var(--accent-foreground)}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:var(--sidebar-accent-foreground)}.data-\[active\=true\]\:ring-\[3px\][data-active=true]{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}@media(hover:hover){.data-\[active\=true\]\:hover\:bg-accent[data-active=true]:hover{background-color:var(--accent)}}.data-\[active\=true\]\:focus\:bg-accent[data-active=true]:focus{background-color:var(--accent)}.data-\[active\=true\]\:aria-invalid\:border-destructive[data-active=true][aria-invalid=true]{border-color:var(--destructive)}.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:50%}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true]{pointer-events:none}.data-\[disabled\=true\]\:opacity-50[data-disabled=true]{opacity:50%}.data-\[empty\=true\]\:text-muted-foreground[data-empty=true]{color:var(--muted-foreground)}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing) * 8)}.data-\[motion\=from-end\]\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: calc(52*var(--spacing))}.data-\[motion\=from-start\]\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\=to-end\]\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: calc(52*var(--spacing))}.data-\[motion\=to-start\]\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\^\=from-\]\:animate-in[data-motion^=from-]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=from-\]\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\[motion\^\=to-\]\:animate-out[data-motion^=to-]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=to-\]\:fade-out[data-motion^=to-]{--tw-exit-opacity: 0}.data-\[orientation\=horizontal\]\:h-1\.5[data-orientation=horizontal]{height:calc(var(--spacing) * 1.5)}.data-\[orientation\=horizontal\]\:h-full[data-orientation=horizontal]{height:100%}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[orientation\=vertical\]\:min-h-44[data-orientation=vertical]{min-height:calc(var(--spacing) * 44)}.data-\[orientation\=vertical\]\:w-1\.5[data-orientation=vertical]{width:calc(var(--spacing) * 1.5)}.data-\[orientation\=vertical\]\:w-auto[data-orientation=vertical]{width:auto}.data-\[orientation\=vertical\]\:w-full[data-orientation=vertical]{width:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[orientation\=vertical\]\:flex-col[data-orientation=vertical]{flex-direction:column}.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-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:calc(var(--spacing) * 0)}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:calc(var(--spacing) * 1)}.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-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--muted-foreground)}.data-\[range-end\=true\]\:rounded-md[data-range-end=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:rounded-r-md[data-range-end=true]{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:bg-primary[data-range-end=true]{background-color:var(--primary)}.data-\[range-end\=true\]\:text-primary-foreground[data-range-end=true]{color:var(--primary-foreground)}.data-\[range-middle\=true\]\:rounded-none[data-range-middle=true]{border-radius:0}.data-\[range-middle\=true\]\:bg-accent[data-range-middle=true]{background-color:var(--accent)}.data-\[range-middle\=true\]\:text-accent-foreground[data-range-middle=true]{color:var(--accent-foreground)}.data-\[range-start\=true\]\:rounded-md[data-range-start=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:rounded-l-md[data-range-start=true]{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:bg-primary[data-range-start=true]{background-color:var(--primary)}.data-\[range-start\=true\]\:text-primary-foreground[data-range-start=true]{color:var(--primary-foreground)}.data-\[selected-single\=true\]\:bg-primary[data-selected-single=true]{background-color:var(--primary)}.data-\[selected-single\=true\]\:text-primary-foreground[data-selected-single=true]{color:var(--primary-foreground)}.data-\[selected\=true\]\:rounded-none[data-selected=true]{border-radius:0}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:var(--accent)}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:var(--accent-foreground)}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: calc(2*var(--spacing))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: calc(2*var(--spacing))}.data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing) * 9)}.data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing) * 8)}:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:color-mix(in oklab,var(--destructive) 90%,transparent)}}:is(.\*\*\:data-\[slot\=command-input-wrapper\]\:h-12 *)[data-slot=command-input-wrapper]{height:calc(var(--spacing) * 12)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:ring-0 *)[data-slot=navigation-menu-link]:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:outline-none *)[data-slot=navigation-menu-link]:focus{--tw-outline-style: none;outline-style:none}:is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}:is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}:is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}:is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing) * 2)}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:var(--background)}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[state\=checked\]\:translate-x-\[calc\(100\%-2px\)\][data-state=checked]{--tw-translate-x: calc(100% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=checked\]\:border-primary[data-state=checked]{border-color:var(--primary)}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:var(--primary)}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:var(--primary-foreground)}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:duration-300[data-state=closed]{--tw-duration: .3s;transition-duration:.3s}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:animate-out:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:fade-out-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:zoom-out-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=hidden\]\:animate-out[data-state=hidden]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=hidden\]\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\[state\=on\]\:bg-accent[data-state=on]{background-color:var(--accent)}.data-\[state\=on\]\:text-accent-foreground[data-state=on]{color:var(--accent-foreground)}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--accent)}.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:var(--secondary)}.data-\[state\=open\]\:bg-sidebar-accent[data-state=open]{background-color:var(--sidebar-accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--muted-foreground)}.data-\[state\=open\]\:text-sidebar-accent-foreground[data-state=open]{color:var(--sidebar-accent-foreground)}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:100%}.data-\[state\=open\]\:duration-500[data-state=open]{--tw-duration: .5s;transition-duration:.5s}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.data-\[state\=open\]\:zoom-in-90[data-state=open]{--tw-enter-scale: 90% ;--tw-enter-scale: .9}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:animate-in:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:fade-in-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:zoom-in-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-accent[data-state=open]:hover{background-color:var(--accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-sidebar-accent[data-state=open]:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground[data-state=open]:hover{color:var(--sidebar-accent-foreground)}}.data-\[state\=open\]\:focus\:bg-accent[data-state=open]:focus{background-color:var(--accent)}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:var(--muted)}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:var(--input)}.data-\[state\=visible\]\:animate-in[data-state=visible]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=visible\]\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--destructive)}.data-\[variant\=outline\]\:border-l-0[data-variant=outline]{border-left-style:var(--tw-border-style);border-left-width:0px}.data-\[variant\=outline\]\:shadow-xs[data-variant=outline]{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[variant\=outline\]\:first\:border-l[data-variant=outline]:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=bottom\]\:inset-x-0[data-vaul-drawer-direction=bottom]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:bottom-0[data-vaul-drawer-direction=bottom]{bottom:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:mt-24[data-vaul-drawer-direction=bottom]{margin-top:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=bottom\]\:max-h-\[80vh\][data-vaul-drawer-direction=bottom]{max-height:80vh}.data-\[vaul-drawer-direction\=bottom\]\:rounded-t-lg[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.data-\[vaul-drawer-direction\=bottom\]\:border-t[data-vaul-drawer-direction=bottom]{border-top-style:var(--tw-border-style);border-top-width:1px}.data-\[vaul-drawer-direction\=left\]\:inset-y-0[data-vaul-drawer-direction=left]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:left-0[data-vaul-drawer-direction=left]{left:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:w-3\/4[data-vaul-drawer-direction=left]{width:75%}.data-\[vaul-drawer-direction\=left\]\:border-r[data-vaul-drawer-direction=left]{border-right-style:var(--tw-border-style);border-right-width:1px}.data-\[vaul-drawer-direction\=right\]\:inset-y-0[data-vaul-drawer-direction=right]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:right-0[data-vaul-drawer-direction=right]{right:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:w-3\/4[data-vaul-drawer-direction=right]{width:75%}.data-\[vaul-drawer-direction\=right\]\:border-l[data-vaul-drawer-direction=right]{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=top\]\:inset-x-0[data-vaul-drawer-direction=top]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:top-0[data-vaul-drawer-direction=top]{top:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:mb-24[data-vaul-drawer-direction=top]{margin-bottom:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=top\]\:max-h-\[80vh\][data-vaul-drawer-direction=top]{max-height:80vh}.data-\[vaul-drawer-direction\=top\]\:rounded-b-lg[data-vaul-drawer-direction=top]{border-bottom-right-radius:var(--radius);border-bottom-left-radius:var(--radius)}.data-\[vaul-drawer-direction\=top\]\:border-b[data-vaul-drawer-direction=top]{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}@media(min-width:40rem){.sm\:block{display:block}}@media(min-width:40rem){.sm\:flex{display:flex}}@media(min-width:40rem){.sm\:w-auto{width:auto}}@media(min-width:40rem){.sm\:max-w-\[425px\]{max-width:425px}}@media(min-width:40rem){.sm\:max-w-lg{max-width:var(--container-lg)}}@media(min-width:40rem){.sm\:max-w-md{max-width:var(--container-md)}}@media(min-width:40rem){.sm\:max-w-sm{max-width:var(--container-sm)}}@media(min-width:40rem){.sm\:flex-row{flex-direction:row}}@media(min-width:40rem){.sm\:justify-end{justify-content:flex-end}}@media(min-width:40rem){.sm\:gap-2\.5{gap:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pl-2\.5{padding-left:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:text-left{text-align:left}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=left\]\:sm\:max-w-sm[data-vaul-drawer-direction=left]{max-width:var(--container-sm)}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=right\]\:sm\:max-w-sm[data-vaul-drawer-direction=right]{max-width:var(--container-sm)}}@media(min-width:48rem){.md\:absolute{position:absolute}}@media(min-width:48rem){.md\:block{display:block}}@media(min-width:48rem){.md\:flex{display:flex}}@media(min-width:48rem){.md\:min-h-min{min-height:min-content}}@media(min-width:48rem){.md\:w-\[400px\]{width:400px}}@media(min-width:48rem){.md\:w-\[500px\]{width:500px}}@media(min-width:48rem){.md\:w-\[var\(--radix-navigation-menu-viewport-width\)\]{width:var(--radix-navigation-menu-viewport-width)}}@media(min-width:48rem){.md\:w-auto{width:auto}}@media(min-width:48rem){.md\:basis-1\/2{flex-basis:50%}}@media(min-width:48rem){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:48rem){.md\:flex-row{flex-direction:row}}@media(min-width:48rem){.md\:gap-1\.5{gap:calc(var(--spacing) * 1.5)}}@media(min-width:48rem){.md\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}}@media(min-width:48rem){.md\:opacity-0{opacity:0%}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:m-2:is(:where(.peer)[data-variant=inset]~*){margin:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:ml-0:is(:where(.peer)[data-variant=inset]~*){margin-left:calc(var(--spacing) * 0)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:rounded-xl:is(:where(.peer)[data-variant=inset]~*){border-radius:calc(var(--radius) + 4px)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:shadow-sm:is(:where(.peer)[data-variant=inset]~*){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:peer-data-\[state\=collapsed\]\:ml-2:is(:where(.peer)[data-variant=inset]~*):is(:where(.peer)[data-state=collapsed]~*){margin-left:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:after\:hidden:after{content:var(--tw-content);display:none}}@media(min-width:64rem){.lg\:w-\[500px\]{width:500px}}@media(min-width:64rem){.lg\:w-\[600px\]{width:600px}}@media(min-width:64rem){.lg\:basis-1\/3{flex-basis:calc(1/3 * 100%)}}@media(min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-\[\.75fr_1fr\]{grid-template-columns:.75fr 1fr}}.dark\:border-input:is(.dark *){border-color:var(--input)}.dark\:bg-destructive\/60:is(.dark *){background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-destructive\/60:is(.dark *){background-color:color-mix(in oklab,var(--destructive) 60%,transparent)}}.dark\:bg-input\/30:is(.dark *){background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-input\/30:is(.dark *){background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:bg-slate-800:is(.dark *){background-color:var(--color-slate-800)}.dark\:bg-slate-900:is(.dark *){background-color:var(--color-slate-900)}.dark\:text-muted-foreground:is(.dark *){color:var(--muted-foreground)}@media(hover:hover){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--input) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:text-accent-foreground:is(.dark *):hover{color:var(--accent-foreground)}}.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[state\=active\]\:border-input:is(.dark *)[data-state=active]{border-color:var(--input)}.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:data-\[state\=active\]\:text-foreground:is(.dark *)[data-state=active]{color:var(--foreground)}.dark\:data-\[state\=checked\]\:bg-primary:is(.dark *)[data-state=checked]{background-color:var(--primary)}.dark\:data-\[state\=checked\]\:bg-primary-foreground:is(.dark *)[data-state=checked]{background-color:var(--primary-foreground)}.dark\:data-\[state\=unchecked\]\:bg-foreground:is(.dark *)[data-state=unchecked]{background-color:var(--foreground)}.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:color-mix(in oklab,var(--input) 80%,transparent)}}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:var(--muted-foreground)}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:var(--border)}@supports (color: color-mix(in lab,red,red)){.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:color-mix(in oklab,var(--border) 50%,transparent)}}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:var(--border)}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector{fill:var(--muted)}.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:var(--muted)}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{outline:2px solid transparent;outline-offset:2px}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--muted-foreground)}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:calc(var(--spacing) * 0)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:calc(var(--spacing) * 12)}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-block:calc(var(--spacing) * 3)}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:calc(var(--spacing) * 5)}.\[\&_p\]\:leading-relaxed p{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--muted-foreground)}.\[\&_tr\]\:border-b tr{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-style:var(--tw-border-style);border-width:0px}.\[\&\:\:-webkit-calendar-picker-indicator\]\:hidden::-webkit-calendar-picker-indicator{display:none}.\[\&\:\:-webkit-calendar-picker-indicator\]\:appearance-none::-webkit-calendar-picker-indicator{-webkit-appearance:none;-moz-appearance:none;appearance:none}.\[\&\:first-child\[data-selected\=true\]_button\]\:rounded-l-md:first-child[data-selected=true] button{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:calc(var(--spacing) * 0)}.\[\.border-b\]\:pb-6:is(.border-b){padding-bottom:calc(var(--spacing) * 6)}.\[\.border-t\]\:pt-6:is(.border-t){padding-top:calc(var(--spacing) * 6)}:is(.rtl\:\*\*\:\[\.rdp-button\\_next\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_next>svg){rotate:180deg}:is(.rtl\:\*\*\:\[\.rdp-button\\_previous\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_previous>svg){rotate:180deg}:is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}:is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}:is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing) * 2)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:\!text-destructive[data-variant=destructive]>*):is(svg){color:var(--destructive)!important}.\[\&\:last-child\[data-selected\=true\]_button\]\:rounded-r-md:last-child[data-selected=true] button{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y: 2px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>div\]\:bg-blue-500>div{background-color:var(--color-blue-500)}.\[\&\>div\]\:bg-green-500>div{background-color:var(--color-green-500)}.\[\&\>div\]\:bg-orange-500>div{background-color:var(--color-orange-500)}.\[\&\>div\]\:bg-red-500>div{background-color:var(--color-red-500)}.\[\&\>div\]\:bg-yellow-500>div{background-color:var(--color-yellow-500)}.\[\&\>div\]\:bg-gradient-to-r>div{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.\[\&\>div\]\:from-purple-500>div{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>div\]\:to-pink-500>div{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>span\]\:text-xs>span{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&\>span\]\:opacity-70>span{opacity:70%}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:size-3>svg{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:size-3\.5>svg{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.\[\&\>svg\]\:size-4>svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&\>svg\]\:h-2\.5>svg{height:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:h-3>svg{height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:w-2\.5>svg{width:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:w-3>svg{width:calc(var(--spacing) * 3)}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:translate-y-0\.5>svg{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>svg\]\:text-current>svg{color:currentcolor}.\[\&\>svg\]\:text-muted-foreground>svg{color:var(--muted-foreground)}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:var(--sidebar-accent-foreground)}.\[\&\>tr\]\:last\:border-b-0>tr:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{rotate:90deg}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{rotate:180deg}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:calc(var(--spacing) * -2)}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:calc(var(--spacing) * -2)}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-slot=card-content] .\[\[data-slot\=card-content\]_\&\]\:bg-transparent{background-color:transparent}[data-slot=popover-content] .\[\[data-slot\=popover-content\]_\&\]\:bg-transparent{background-color:transparent}@media(hover:hover){a.\[a\&\]\:hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:color-mix(in oklab,var(--secondary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}}@property --tw-animation-delay{syntax: "*"; inherits: false; initial-value: 0s;}@property --tw-animation-direction{syntax: "*"; inherits: false; initial-value: normal;}@property --tw-animation-duration{syntax: "*"; inherits: false;}@property --tw-animation-fill-mode{syntax: "*"; inherits: false; initial-value: none;}@property --tw-animation-iteration-count{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-translate-y{syntax: "*"; inherits: false; initial-value: 0;}:root{--background: oklch(1 0 0);--foreground: oklch(.145 0 0);--card: oklch(1 0 0);--card-foreground: oklch(.145 0 0);--popover: oklch(1 0 0);--popover-foreground: oklch(.145 0 0);--primary: oklch(67.35% .153 159.64);--primary-foreground: oklch(.985 0 0);--secondary: oklch(.97 0 0);--secondary-foreground: oklch(.205 0 0);--muted: oklch(.97 0 0);--muted-foreground: oklch(.556 0 0);--accent: oklch(.97 0 0);--accent-foreground: oklch(.205 0 0);--destructive: oklch(.577 .245 27.325);--destructive-foreground: oklch(.577 .245 27.325);--border: oklch(.922 0 0);--input: oklch(.922 0 0);--ring: oklch(.708 0 0);--chart-1: oklch(.646 .222 41.116);--chart-2: oklch(.6 .118 184.704);--chart-3: oklch(.398 .07 227.392);--chart-4: oklch(.828 .189 84.429);--chart-5: oklch(.769 .188 70.08);--radius: .625rem;--sidebar: oklch(.985 0 0);--sidebar-foreground: oklch(.145 0 0);--sidebar-primary: oklch(.205 0 0);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.97 0 0);--sidebar-accent-foreground: oklch(.205 0 0);--sidebar-border: oklch(.922 0 0);--sidebar-ring: oklch(.708 0 0)}.dark{--background: oklch(.145 0 0);--foreground: oklch(.985 0 0);--card: oklch(.145 0 0);--card-foreground: oklch(.985 0 0);--popover: oklch(.145 0 0);--popover-foreground: oklch(.985 0 0);--primary: oklch(88.18% .202 159.34);--primary-foreground: oklch(.205 0 0);--secondary: oklch(.269 0 0);--secondary-foreground: oklch(.985 0 0);--muted: oklch(.269 0 0);--muted-foreground: oklch(.708 0 0);--accent: oklch(.269 0 0);--accent-foreground: oklch(.985 0 0);--destructive: oklch(.396 .141 25.723);--destructive-foreground: oklch(.637 .237 25.331);--border: oklch(.269 0 0);--input: oklch(.269 0 0);--ring: oklch(.439 0 0);--chart-1: oklch(.488 .243 264.376);--chart-2: oklch(.696 .17 162.48);--chart-3: oklch(.769 .188 70.08);--chart-4: oklch(.627 .265 303.9);--chart-5: oklch(.645 .246 16.439);--sidebar: oklch(.205 0 0);--sidebar-foreground: oklch(.985 0 0);--sidebar-primary: oklch(.488 .243 264.376);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.269 0 0);--sidebar-accent-foreground: oklch(.985 0 0);--sidebar-border: oklch(.269 0 0);--sidebar-ring: oklch(.439 0 0)}@layer base{*{border-color:var(--border);outline-color:var(--ring)}@supports (color: color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}}body{background-color:var(--background);color:var(--foreground)}}@property --tw-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-z{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-rotate-x{syntax: "*"; inherits: false;}@property --tw-rotate-y{syntax: "*"; inherits: false;}@property --tw-rotate-z{syntax: "*"; inherits: false;}@property --tw-skew-x{syntax: "*"; inherits: false;}@property --tw-skew-y{syntax: "*"; inherits: false;}@property --tw-space-y-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-space-x-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-gradient-position{syntax: "*"; inherits: false;}@property --tw-gradient-from{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-via{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-to{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-stops{syntax: "*"; inherits: false;}@property --tw-gradient-via-stops{syntax: "*"; inherits: false;}@property --tw-gradient-from-position{syntax: "<length-percentage>"; inherits: false; initial-value: 0%;}@property --tw-gradient-via-position{syntax: "<length-percentage>"; inherits: false; initial-value: 50%;}@property --tw-gradient-to-position{syntax: "<length-percentage>"; inherits: false; initial-value: 100%;}@property --tw-leading{syntax: "*"; inherits: false;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-tracking{syntax: "*"; inherits: false;}@property --tw-ordinal{syntax: "*"; inherits: false;}@property --tw-slashed-zero{syntax: "*"; inherits: false;}@property --tw-numeric-figure{syntax: "*"; inherits: false;}@property --tw-numeric-spacing{syntax: "*"; inherits: false;}@property --tw-numeric-fraction{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-outline-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@property --tw-content{syntax: "*"; initial-value: ""; inherits: false;}@keyframes pulse{50%{opacity:.5}}@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))}}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}to{height:0}}@keyframes caret-blink{0%,70%,to{opacity:1}20%,50%{opacity:0}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x: 0;--tw-translate-y: 0;--tw-translate-z: 0;--tw-rotate-x: initial;--tw-rotate-y: initial;--tw-rotate-z: initial;--tw-skew-x: initial;--tw-skew-y: initial;--tw-space-y-reverse: 0;--tw-space-x-reverse: 0;--tw-border-style: solid;--tw-gradient-position: initial;--tw-gradient-from: #0000;--tw-gradient-via: #0000;--tw-gradient-to: #0000;--tw-gradient-stops: initial;--tw-gradient-via-stops: initial;--tw-gradient-from-position: 0%;--tw-gradient-via-position: 50%;--tw-gradient-to-position: 100%;--tw-leading: initial;--tw-font-weight: initial;--tw-tracking: initial;--tw-ordinal: initial;--tw-slashed-zero: initial;--tw-numeric-figure: initial;--tw-numeric-spacing: initial;--tw-numeric-fraction: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-outline-style: solid;--tw-duration: initial;--tw-ease: initial;--tw-content: "";--tw-animation-delay: 0s;--tw-animation-direction: normal;--tw-animation-duration: initial;--tw-animation-fill-mode: none;--tw-animation-iteration-count: 1;--tw-enter-opacity: 1;--tw-enter-rotate: 0;--tw-enter-scale: 1;--tw-enter-translate-x: 0;--tw-enter-translate-y: 0;--tw-exit-opacity: 1;--tw-exit-rotate: 0;--tw-exit-scale: 1;--tw-exit-translate-x: 0;--tw-exit-translate-y: 0}}}/*! tailwindcss v4.1.10 | MIT License | https://tailwindcss.com *//*! tailwindcss v4.1.17 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-6xl:3.75rem;--text-6xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--animate-spin:spin 1s linear infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}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;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--border);outline-color:var(--ring)}@supports (color:color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring)50%,transparent)}}html,body{height:100%;margin:0;padding:0}body{background-color:var(--background);color:var(--foreground);font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif}#root{height:100%}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0;border-radius:4px}::-webkit-scrollbar-thumb{background-color:#ffffff26;background-clip:content-box;border:2px solid #0000;border-radius:4px;transition:background-color .2s}::-webkit-scrollbar-thumb:hover{background-color:#ffffff40}::-webkit-scrollbar-thumb:active{background-color:#ffffff59}*{scrollbar-width:thin;scrollbar-color:#ffffff26 transparent}@media(max-width:768px){*{scrollbar-width:none}::-webkit-scrollbar{display:none}}}@layer components;@layer utilities{.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.top-1\/2{top:50%}.left-3{left:calc(var(--spacing)*3)}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing)*.5)}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-12{margin-top:calc(var(--spacing)*12)}.mt-16{margin-top:calc(var(--spacing)*16)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing)*1)}.mr-1\.5{margin-right:calc(var(--spacing)*1.5)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.mb-6{margin-bottom:calc(var(--spacing)*6)}.ml-1{margin-left:calc(var(--spacing)*1)}.ml-2{margin-left:calc(var(--spacing)*2)}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-7{height:calc(var(--spacing)*7)}.h-8{height:calc(var(--spacing)*8)}.h-12{height:calc(var(--spacing)*12)}.h-14{height:calc(var(--spacing)*14)}.h-16{height:calc(var(--spacing)*16)}.h-48{height:calc(var(--spacing)*48)}.h-64{height:calc(var(--spacing)*64)}.h-full{height:100%}.h-screen{height:100vh}.max-h-40{max-height:calc(var(--spacing)*40)}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-60{max-height:calc(var(--spacing)*60)}.max-h-\[90vh\]{max-height:90vh}.min-h-screen{min-height:100vh}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-12{width:calc(var(--spacing)*12)}.w-14{width:calc(var(--spacing)*14)}.w-56{width:calc(var(--spacing)*56)}.w-64{width:calc(var(--spacing)*64)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[150px\]{max-width:150px}.max-w-md{max-width:var(--container-md)}.min-w-0{min-width:calc(var(--spacing)*0)}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x)var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-6{gap:calc(var(--spacing)*6)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1.5)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1.5)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*6)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*6)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*8)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*8)*calc(1 - var(--tw-space-y-reverse)))}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-destructive\/50{border-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.border-destructive\/50{border-color:color-mix(in oklab,var(--destructive)50%,transparent)}}.border-gray-300{border-color:var(--color-gray-300)}.border-input{border-color:var(--input)}.border-primary\/20{border-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--primary)20%,transparent)}}.border-sidebar-border{border-color:var(--sidebar-border)}.bg-background,.bg-background\/80{background-color:var(--background)}@supports (color:color-mix(in lab,red,red)){.bg-background\/80{background-color:color-mix(in oklab,var(--background)80%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black)50%,transparent)}}.bg-blue-600{background-color:var(--color-blue-600)}.bg-card{background-color:var(--card)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive)10%,transparent)}}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.bg-muted{background-color:var(--muted)}.bg-primary,.bg-primary\/10{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary)10%,transparent)}}.bg-red-50{background-color:var(--color-red-50)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-accent,.bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent)50%,transparent)}}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-t{--tw-gradient-position:to top in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-primary\/10{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/10{--tw-gradient-from:color-mix(in oklab,var(--primary)10%,transparent)}}.from-primary\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-primary\/20{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/20{--tw-gradient-from:color-mix(in oklab,var(--primary)20%,transparent)}}.from-primary\/20{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.via-background{--tw-gradient-via:var(--background);--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-background\/95{--tw-gradient-via:var(--background)}@supports (color:color-mix(in lab,red,red)){.via-background\/95{--tw-gradient-via:color-mix(in oklab,var(--background)95%,transparent)}}.via-background\/95{--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-via)var(--tw-gradient-via-position),var(--tw-gradient-to)var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-background{--tw-gradient-to:var(--background);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.p-8{padding:calc(var(--spacing)*8)}.px-0{padding-inline:calc(var(--spacing)*0)}.px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-8{padding-inline:calc(var(--spacing)*8)}.px-\[0\.3rem\]{padding-inline:.3rem}.py-1{padding-block:calc(var(--spacing)*1)}.py-2{padding-block:calc(var(--spacing)*2)}.py-2\.5{padding-block:calc(var(--spacing)*2.5)}.py-3{padding-block:calc(var(--spacing)*3)}.py-4{padding-block:calc(var(--spacing)*4)}.py-6{padding-block:calc(var(--spacing)*6)}.py-12{padding-block:calc(var(--spacing)*12)}.py-16{padding-block:calc(var(--spacing)*16)}.py-\[0\.2rem\]{padding-block:.2rem}.pt-2{padding-top:calc(var(--spacing)*2)}.pt-3{padding-top:calc(var(--spacing)*3)}.pt-4{padding-top:calc(var(--spacing)*4)}.pt-8{padding-top:calc(var(--spacing)*8)}.pr-1{padding-right:calc(var(--spacing)*1)}.pl-2{padding-left:calc(var(--spacing)*2)}.pl-9{padding-left:calc(var(--spacing)*9)}.text-center{text-align:center}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-6xl{font-size:var(--text-6xl);line-height:var(--tw-leading,var(--text-6xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.whitespace-nowrap{white-space:nowrap}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-destructive{color:var(--destructive)}.text-foreground{color:var(--foreground)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-900{color:var(--color-gray-900)}.text-green-500{color:var(--color-green-500)}.text-muted-foreground{color:var(--muted-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-red-400{color:var(--color-red-400)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-800{color:var(--color-red-800)}.text-sidebar-foreground,.text-sidebar-foreground\/40{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/40{color:color-mix(in oklab,var(--sidebar-foreground)40%,transparent)}}.text-sidebar-foreground\/60{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/60{color:color-mix(in oklab,var(--sidebar-foreground)60%,transparent)}}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground)70%,transparent)}}.text-white{color:var(--color-white)}.text-yellow-500{color:var(--color-yellow-500)}.lowercase{text-transform:lowercase}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(1px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.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(var(--blur-sm));-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:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}@media(hover:hover){.group-hover\:translate-x-1:is(:where(.group):hover *){--tw-translate-x:calc(var(--spacing)*1);translate:var(--tw-translate-x)var(--tw-translate-y)}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.placeholder\:text-sidebar-foreground\/50::placeholder{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.placeholder\:text-sidebar-foreground\/50::placeholder{color:color-mix(in oklab,var(--sidebar-foreground)50%,transparent)}}@media(hover:hover){.hover\:border-primary:hover{border-color:var(--primary)}.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-blue-500\/10:hover{background-color:#3080ff1a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-blue-500\/10:hover{background-color:color-mix(in oklab,var(--color-blue-500)10%,transparent)}}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-gray-500\/10:hover{background-color:#6a72821a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-500\/10:hover{background-color:color-mix(in oklab,var(--color-gray-500)10%,transparent)}}.hover\:bg-green-500\/10:hover{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/10:hover{background-color:color-mix(in oklab,var(--color-green-500)10%,transparent)}}.hover\:bg-green-500\/20:hover{background-color:#00c75833}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/20:hover{background-color:color-mix(in oklab,var(--color-green-500)20%,transparent)}}.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary)90%,transparent)}}.hover\:bg-red-500\/10:hover{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/10:hover{background-color:color-mix(in oklab,var(--color-red-500)10%,transparent)}}.hover\:bg-red-500\/20:hover{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/20:hover{background-color:color-mix(in oklab,var(--color-red-500)20%,transparent)}}.hover\:bg-red-700:hover{background-color:var(--color-red-700)}.hover\:bg-sidebar:hover{background-color:var(--sidebar)}.hover\:bg-sidebar-accent:hover,.hover\:bg-sidebar-accent\/30:hover{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-sidebar-accent\/30:hover{background-color:color-mix(in oklab,var(--sidebar-accent)30%,transparent)}}.hover\:bg-transparent:hover{background-color:#0000}.hover\:bg-yellow-500\/10:hover{background-color:#edb2001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-yellow-500\/10:hover{background-color:color-mix(in oklab,var(--color-yellow-500)10%,transparent)}}.hover\:text-blue-400:hover{color:var(--color-blue-400)}.hover\:text-foreground:hover{color:var(--foreground)}.hover\:text-gray-300:hover{color:var(--color-gray-300)}.hover\:text-green-400:hover{color:var(--color-green-400)}.hover\:text-primary:hover{color:var(--primary)}.hover\:text-red-400:hover{color:var(--color-red-400)}.hover\:text-sidebar-foreground:hover{color:var(--sidebar-foreground)}.hover\:text-yellow-400:hover{color:var(--color-yellow-400)}.hover\:shadow-lg:hover{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:shadow-black\/10:hover{--tw-shadow-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:shadow-black\/10:hover{--tw-shadow-color:color-mix(in oklab,color-mix(in oklab,var(--color-black)10%,transparent)var(--tw-shadow-alpha),transparent)}}}.focus\:border-sidebar-border:focus{border-color:var(--sidebar-border)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(2px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-blue-500:focus{--tw-ring-color:var(--color-blue-500)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,)0 0 0 var(--tw-ring-offset-width)var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:opacity-50:disabled{opacity:.5}@media(min-width:40rem){.sm\:w-auto{width:auto}.sm\:max-w-md{max-width:var(--container-md)}.sm\:gap-0{gap:calc(var(--spacing)*0)}}@media(min-width:48rem){.md\:flex{display:flex}.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\:items-center{align-items:center}.md\:items-start{align-items:flex-start}.md\:justify-between{justify-content:space-between}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:80rem){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(prefers-color-scheme:dark){.dark\:bg-red-600{background-color:var(--color-red-600)}.dark\:bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent)50%,transparent)}}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-red-500{color:var(--color-red-500)}.dark\:placeholder\:text-gray-400::placeholder{color:var(--color-gray-400)}@media(hover:hover){.dark\:hover\:bg-red-700:hover{background-color:var(--color-red-700)}.dark\:hover\:bg-sidebar:hover{background-color:var(--sidebar)}.dark\:hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}}}.scrollbar-hidden{scrollbar-width:none!important;-ms-overflow-style:none!important}.scrollbar-hidden::-webkit-scrollbar{display:none!important}.scrollbar-thin::-webkit-scrollbar{width:6px!important;height:6px!important}.scrollbar-thin::-webkit-scrollbar-thumb{background-color:#9ca3af4d!important;border-radius:3px!important}.scrollbar-thin::-webkit-scrollbar-thumb:hover{background-color:#9ca3af80!important}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}diff --git a/manager/dist/assets/index-CRnVAbpY.js b/manager/dist/assets/index-CRnVAbpY.jsnew file mode 100644index 0000000..d466c7c--- /dev/null+++ b/manager/dist/assets/index-CRnVAbpY.js@@ -0,0 +1,340 @@+var iC=Object.defineProperty;var lC=(t,n,r)=>n in t?iC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var tb=(t,n,r)=>lC(t,typeof n!="symbol"?n+"":n,r);function cC(t,n){for(var r=0;r<n.length;r++){const s=n[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in t)){const c=Object.getOwnPropertyDescriptor(s,i);c&&Object.defineProperty(t,i,c.get?c:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function ix(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var om={exports:{}},Pi={};/**+ * @license React+ * react-jsx-runtime.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var nb;function uC(){if(nb)return Pi;nb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,i,c){var u=null;if(c!==void 0&&(u=""+c),i.key!==void 0&&(u=""+i.key),"key"in i){c={};for(var f in i)f!=="key"&&(c[f]=i[f])}else c=i;return i=c.ref,{$$typeof:t,type:s,key:u,ref:i!==void 0?i:null,props:c}}return Pi.Fragment=n,Pi.jsx=r,Pi.jsxs=r,Pi}var ab;function dC(){return ab||(ab=1,om.exports=uC()),om.exports}var p=dC(),im={exports:{}},Pe={};/**+ * @license React+ * react.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var rb;function fC(){if(rb)return Pe;rb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function N(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,C={};function A(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}A.prototype.isReactComponent={},A.prototype.setState=function(T,Y){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,Y,"setState")},A.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function O(){}O.prototype=A.prototype;function R(T,Y,D){this.props=T,this.context=Y,this.refs=C,this.updater=D||E}var L=R.prototype=new O;L.constructor=R,S(L,A.prototype),L.isPureReactComponent=!0;var I=Array.isArray;function ee(){}var U={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function le(T,Y,D){var V=D.ref;return{$$typeof:t,type:T,key:Y,ref:V!==void 0?V:null,props:D}}function ue(T,Y){return le(T.type,Y,T.props)}function me(T){return typeof T=="object"&&T!==null&&T.$$typeof===t}function re(T){var Y={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(D){return Y[D]})}var X=/\/+/g;function he(T,Y){return typeof T=="object"&&T!==null&&T.key!=null?re(""+T.key):Y.toString(36)}function be(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(ee,ee):(T.status="pending",T.then(function(Y){T.status==="pending"&&(T.status="fulfilled",T.value=Y)},function(Y){T.status==="pending"&&(T.status="rejected",T.reason=Y)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function j(T,Y,D,V,te){var fe=typeof T;(fe==="undefined"||fe==="boolean")&&(T=null);var oe=!1;if(T===null)oe=!0;else switch(fe){case"bigint":case"string":case"number":oe=!0;break;case"object":switch(T.$$typeof){case t:case n:oe=!0;break;case v:return oe=T._init,j(oe(T._payload),Y,D,V,te)}}if(oe)return te=te(T),oe=V===""?"."+he(T,0):V,I(te)?(D="",oe!=null&&(D=oe.replace(X,"$&/")+"/"),j(te,Y,D,"",function(_e){return _e})):te!=null&&(me(te)&&(te=ue(te,D+(te.key==null||T&&T.key===te.key?"":(""+te.key).replace(X,"$&/")+"/")+oe)),Y.push(te)),1;oe=0;var K=V===""?".":V+":";if(I(T))for(var de=0;de<T.length;de++)V=T[de],fe=K+he(V,de),oe+=j(V,Y,D,fe,te);else if(de=N(T),typeof de=="function")for(T=de.call(T),de=0;!(V=T.next()).done;)V=V.value,fe=K+he(V,de++),oe+=j(V,Y,D,fe,te);else if(fe==="object"){if(typeof T.then=="function")return j(be(T),Y,D,V,te);throw Y=String(T),Error("Objects are not valid as a React child (found: "+(Y==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":Y)+"). If you meant to render a collection of children, use an array instead.")}return oe}function Z(T,Y,D){if(T==null)return T;var V=[],te=0;return j(T,V,"","",function(fe){return Y.call(D,fe,te++)}),V}function P(T){if(T._status===-1){var Y=T._result;Y=Y(),Y.then(function(D){(T._status===0||T._status===-1)&&(T._status=1,T._result=D)},function(D){(T._status===0||T._status===-1)&&(T._status=2,T._result=D)}),T._status===-1&&(T._status=0,T._result=Y)}if(T._status===1)return T._result.default;throw T._result}var se=typeof reportError=="function"?reportError:function(T){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Y=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof T=="object"&&T!==null&&typeof T.message=="string"?String(T.message):String(T),error:T});if(!window.dispatchEvent(Y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",T);return}console.error(T)},we={map:Z,forEach:function(T,Y,D){Z(T,function(){Y.apply(this,arguments)},D)},count:function(T){var Y=0;return Z(T,function(){Y++}),Y},toArray:function(T){return Z(T,function(Y){return Y})||[]},only:function(T){if(!me(T))throw Error("React.Children.only expected to receive a single React element child.");return T}};return Pe.Activity=y,Pe.Children=we,Pe.Component=A,Pe.Fragment=r,Pe.Profiler=i,Pe.PureComponent=R,Pe.StrictMode=s,Pe.Suspense=g,Pe.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=U,Pe.__COMPILER_RUNTIME={__proto__:null,c:function(T){return U.H.useMemoCache(T)}},Pe.cache=function(T){return function(){return T.apply(null,arguments)}},Pe.cacheSignal=function(){return null},Pe.cloneElement=function(T,Y,D){if(T==null)throw Error("The argument must be a React element, but you passed "+T+".");var V=S({},T.props),te=T.key;if(Y!=null)for(fe in Y.key!==void 0&&(te=""+Y.key),Y)!Q.call(Y,fe)||fe==="key"||fe==="__self"||fe==="__source"||fe==="ref"&&Y.ref===void 0||(V[fe]=Y[fe]);var fe=arguments.length-2;if(fe===1)V.children=D;else if(1<fe){for(var oe=Array(fe),K=0;K<fe;K++)oe[K]=arguments[K+2];V.children=oe}return le(T.type,te,V)},Pe.createContext=function(T){return T={$$typeof:u,_currentValue:T,_currentValue2:T,_threadCount:0,Provider:null,Consumer:null},T.Provider=T,T.Consumer={$$typeof:c,_context:T},T},Pe.createElement=function(T,Y,D){var V,te={},fe=null;if(Y!=null)for(V in Y.key!==void 0&&(fe=""+Y.key),Y)Q.call(Y,V)&&V!=="key"&&V!=="__self"&&V!=="__source"&&(te[V]=Y[V]);var oe=arguments.length-2;if(oe===1)te.children=D;else if(1<oe){for(var K=Array(oe),de=0;de<oe;de++)K[de]=arguments[de+2];te.children=K}if(T&&T.defaultProps)for(V in oe=T.defaultProps,oe)te[V]===void 0&&(te[V]=oe[V]);return le(T,fe,te)},Pe.createRef=function(){return{current:null}},Pe.forwardRef=function(T){return{$$typeof:f,render:T}},Pe.isValidElement=me,Pe.lazy=function(T){return{$$typeof:v,_payload:{_status:-1,_result:T},_init:P}},Pe.memo=function(T,Y){return{$$typeof:h,type:T,compare:Y===void 0?null:Y}},Pe.startTransition=function(T){var Y=U.T,D={};U.T=D;try{var V=T(),te=U.S;te!==null&&te(D,V),typeof V=="object"&&V!==null&&typeof V.then=="function"&&V.then(ee,se)}catch(fe){se(fe)}finally{Y!==null&&D.types!==null&&(Y.types=D.types),U.T=Y}},Pe.unstable_useCacheRefresh=function(){return U.H.useCacheRefresh()},Pe.use=function(T){return U.H.use(T)},Pe.useActionState=function(T,Y,D){return U.H.useActionState(T,Y,D)},Pe.useCallback=function(T,Y){return U.H.useCallback(T,Y)},Pe.useContext=function(T){return U.H.useContext(T)},Pe.useDebugValue=function(){},Pe.useDeferredValue=function(T,Y){return U.H.useDeferredValue(T,Y)},Pe.useEffect=function(T,Y){return U.H.useEffect(T,Y)},Pe.useEffectEvent=function(T){return U.H.useEffectEvent(T)},Pe.useId=function(){return U.H.useId()},Pe.useImperativeHandle=function(T,Y,D){return U.H.useImperativeHandle(T,Y,D)},Pe.useInsertionEffect=function(T,Y){return U.H.useInsertionEffect(T,Y)},Pe.useLayoutEffect=function(T,Y){return U.H.useLayoutEffect(T,Y)},Pe.useMemo=function(T,Y){return U.H.useMemo(T,Y)},Pe.useOptimistic=function(T,Y){return U.H.useOptimistic(T,Y)},Pe.useReducer=function(T,Y,D){return U.H.useReducer(T,Y,D)},Pe.useRef=function(T){return U.H.useRef(T)},Pe.useState=function(T){return U.H.useState(T)},Pe.useSyncExternalStore=function(T,Y,D){return U.H.useSyncExternalStore(T,Y,D)},Pe.useTransition=function(){return U.H.useTransition()},Pe.version="19.2.0",Pe}var sb;function mh(){return sb||(sb=1,im.exports=fC()),im.exports}var b=mh();const ae=ix(b),_u=cC({__proto__:null,default:ae},[b]);var lm={exports:{}},Hi={},cm={exports:{}},um={};/**+ * @license React+ * scheduler.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var ob;function mC(){return ob||(ob=1,(function(t){function n(j,Z){var P=j.length;j.push(Z);e:for(;0<P;){var se=P-1>>>1,we=j[se];if(0<i(we,Z))j[se]=Z,j[P]=we,P=se;else break e}}function r(j){return j.length===0?null:j[0]}function s(j){if(j.length===0)return null;var Z=j[0],P=j.pop();if(P!==Z){j[0]=P;e:for(var se=0,we=j.length,T=we>>>1;se<T;){var Y=2*(se+1)-1,D=j[Y],V=Y+1,te=j[V];if(0>i(D,P))V<we&&0>i(te,D)?(j[se]=te,j[V]=P,se=V):(j[se]=D,j[Y]=P,se=Y);else if(V<we&&0>i(te,P))j[se]=te,j[V]=P,se=V;else break e}}return Z}function i(j,Z){var P=j.sortIndex-Z.sortIndex;return P!==0?P:j.id-Z.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;t.unstable_now=function(){return c.now()}}else{var u=Date,f=u.now();t.unstable_now=function(){return u.now()-f}}var g=[],h=[],v=1,y=null,w=3,N=!1,E=!1,S=!1,C=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function L(j){for(var Z=r(h);Z!==null;){if(Z.callback===null)s(h);else if(Z.startTime<=j)s(h),Z.sortIndex=Z.expirationTime,n(g,Z);else break;Z=r(h)}}function I(j){if(S=!1,L(j),!E)if(r(g)!==null)E=!0,ee||(ee=!0,re());else{var Z=r(h);Z!==null&&be(I,Z.startTime-j)}}var ee=!1,U=-1,Q=5,le=-1;function ue(){return C?!0:!(t.unstable_now()-le<Q)}function me(){if(C=!1,ee){var j=t.unstable_now();le=j;var Z=!0;try{e:{E=!1,S&&(S=!1,O(U),U=-1),N=!0;var P=w;try{t:{for(L(j),y=r(g);y!==null&&!(y.expirationTime>j&&ue());){var se=y.callback;if(typeof se=="function"){y.callback=null,w=y.priorityLevel;var we=se(y.expirationTime<=j);if(j=t.unstable_now(),typeof we=="function"){y.callback=we,L(j),Z=!0;break t}y===r(g)&&s(g),L(j)}else s(g);y=r(g)}if(y!==null)Z=!0;else{var T=r(h);T!==null&&be(I,T.startTime-j),Z=!1}}break e}finally{y=null,w=P,N=!1}Z=void 0}}finally{Z?re():ee=!1}}}var re;if(typeof R=="function")re=function(){R(me)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,he=X.port2;X.port1.onmessage=me,re=function(){he.postMessage(null)}}else re=function(){A(me,0)};function be(j,Z){U=A(function(){j(t.unstable_now())},Z)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(j){j.callback=null},t.unstable_forceFrameRate=function(j){0>j||125<j?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Q=0<j?Math.floor(1e3/j):5},t.unstable_getCurrentPriorityLevel=function(){return w},t.unstable_next=function(j){switch(w){case 1:case 2:case 3:var Z=3;break;default:Z=w}var P=w;w=Z;try{return j()}finally{w=P}},t.unstable_requestPaint=function(){C=!0},t.unstable_runWithPriority=function(j,Z){switch(j){case 1:case 2:case 3:case 4:case 5:break;default:j=3}var P=w;w=j;try{return Z()}finally{w=P}},t.unstable_scheduleCallback=function(j,Z,P){var se=t.unstable_now();switch(typeof P=="object"&&P!==null?(P=P.delay,P=typeof P=="number"&&0<P?se+P:se):P=se,j){case 1:var we=-1;break;case 2:we=250;break;case 5:we=1073741823;break;case 4:we=1e4;break;default:we=5e3}return we=P+we,j={id:v++,callback:Z,priorityLevel:j,startTime:P,expirationTime:we,sortIndex:-1},P>se?(j.sortIndex=P,n(h,j),r(g)===null&&j===r(h)&&(S?(O(U),U=-1):S=!0,be(I,P-se))):(j.sortIndex=we,n(g,j),E||N||(E=!0,ee||(ee=!0,re()))),j},t.unstable_shouldYield=ue,t.unstable_wrapCallback=function(j){var Z=w;return function(){var P=w;w=Z;try{return j.apply(this,arguments)}finally{w=P}}}})(um)),um}var ib;function hC(){return ib||(ib=1,cm.exports=mC()),cm.exports}var dm={exports:{}},cn={};/**+ * @license React+ * react-dom.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var lb;function pC(){if(lb)return cn;lb=1;var t=mh();function n(g){var h="https://react.dev/errors/"+g;if(1<arguments.length){h+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)h+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+g+"; visit "+h+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(){}var s={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},i=Symbol.for("react.portal");function c(g,h,v){var y=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:y==null?null:""+y,children:g,containerInfo:h,implementation:v}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(g,h){if(g==="font")return"";if(typeof h=="string")return h==="use-credentials"?h:""}return cn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,cn.createPortal=function(g,h){var v=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)throw Error(n(299));return c(g,h,null,v)},cn.flushSync=function(g){var h=u.T,v=s.p;try{if(u.T=null,s.p=2,g)return g()}finally{u.T=h,s.p=v,s.d.f()}},cn.preconnect=function(g,h){typeof g=="string"&&(h?(h=h.crossOrigin,h=typeof h=="string"?h==="use-credentials"?h:"":void 0):h=null,s.d.C(g,h))},cn.prefetchDNS=function(g){typeof g=="string"&&s.d.D(g)},cn.preinit=function(g,h){if(typeof g=="string"&&h&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin),w=typeof h.integrity=="string"?h.integrity:void 0,N=typeof h.fetchPriority=="string"?h.fetchPriority:void 0;v==="style"?s.d.S(g,typeof h.precedence=="string"?h.precedence:void 0,{crossOrigin:y,integrity:w,fetchPriority:N}):v==="script"&&s.d.X(g,{crossOrigin:y,integrity:w,fetchPriority:N,nonce:typeof h.nonce=="string"?h.nonce:void 0})}},cn.preinitModule=function(g,h){if(typeof g=="string")if(typeof h=="object"&&h!==null){if(h.as==null||h.as==="script"){var v=f(h.as,h.crossOrigin);s.d.M(g,{crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0})}}else h==null&&s.d.M(g)},cn.preload=function(g,h){if(typeof g=="string"&&typeof h=="object"&&h!==null&&typeof h.as=="string"){var v=h.as,y=f(v,h.crossOrigin);s.d.L(g,v,{crossOrigin:y,integrity:typeof h.integrity=="string"?h.integrity:void 0,nonce:typeof h.nonce=="string"?h.nonce:void 0,type:typeof h.type=="string"?h.type:void 0,fetchPriority:typeof h.fetchPriority=="string"?h.fetchPriority:void 0,referrerPolicy:typeof h.referrerPolicy=="string"?h.referrerPolicy:void 0,imageSrcSet:typeof h.imageSrcSet=="string"?h.imageSrcSet:void 0,imageSizes:typeof h.imageSizes=="string"?h.imageSizes:void 0,media:typeof h.media=="string"?h.media:void 0})}},cn.preloadModule=function(g,h){if(typeof g=="string")if(h){var v=f(h.as,h.crossOrigin);s.d.m(g,{as:typeof h.as=="string"&&h.as!=="script"?h.as:void 0,crossOrigin:v,integrity:typeof h.integrity=="string"?h.integrity:void 0})}else s.d.m(g)},cn.requestFormReset=function(g){s.d.r(g)},cn.unstable_batchedUpdates=function(g,h){return g(h)},cn.useFormState=function(g,h,v){return u.H.useFormState(g,h,v)},cn.useFormStatus=function(){return u.H.useHostTransitionStatus()},cn.version="19.2.0",cn}var cb;function lx(){if(cb)return dm.exports;cb=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),dm.exports=pC(),dm.exports}/**+ * @license React+ * react-dom-client.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var ub;function gC(){if(ub)return Hi;ub=1;var t=hC(),n=mh(),r=lx();function s(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var o=2;o<arguments.length;o++)a+="&args[]="+encodeURIComponent(arguments[o])}return"Minified React error #"+e+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function c(e){var a=e,o=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(o=a.return),e=a.return;while(e)}return a.tag===3?o:null}function u(e){if(e.tag===13){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function f(e){if(e.tag===31){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function g(e){if(c(e)!==e)throw Error(s(188))}function h(e){var a=e.alternate;if(!a){if(a=c(e),a===null)throw Error(s(188));return a!==e?null:e}for(var o=e,l=a;;){var d=o.return;if(d===null)break;var m=d.alternate;if(m===null){if(l=d.return,l!==null){o=l;continue}break}if(d.child===m.child){for(m=d.child;m;){if(m===o)return g(d),e;if(m===l)return g(d),a;m=m.sibling}throw Error(s(188))}if(o.return!==l.return)o=d,l=m;else{for(var x=!1,_=d.child;_;){if(_===o){x=!0,o=d,l=m;break}if(_===l){x=!0,l=d,o=m;break}_=_.sibling}if(!x){for(_=m.child;_;){if(_===o){x=!0,o=m,l=d;break}if(_===l){x=!0,l=m,o=d;break}_=_.sibling}if(!x)throw Error(s(189))}}if(o.alternate!==l)throw Error(s(190))}if(o.tag!==3)throw Error(s(188));return o.stateNode.current===o?e:a}function v(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=v(e),a!==null)return a;e=e.sibling}return null}var y=Object.assign,w=Symbol.for("react.element"),N=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),C=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),O=Symbol.for("react.consumer"),R=Symbol.for("react.context"),L=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),U=Symbol.for("react.memo"),Q=Symbol.for("react.lazy"),le=Symbol.for("react.activity"),ue=Symbol.for("react.memo_cache_sentinel"),me=Symbol.iterator;function re(e){return e===null||typeof e!="object"?null:(e=me&&e[me]||e["@@iterator"],typeof e=="function"?e:null)}var X=Symbol.for("react.client.reference");function he(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===X?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case S:return"Fragment";case A:return"Profiler";case C:return"StrictMode";case I:return"Suspense";case ee:return"SuspenseList";case le:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case E:return"Portal";case R:return e.displayName||"Context";case O:return(e._context.displayName||"Context")+".Consumer";case L:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case U:return a=e.displayName||null,a!==null?a:he(e.type)||"Memo";case Q:a=e._payload,e=e._init;try{return he(e(a))}catch{}}return null}var be=Array.isArray,j=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,P={pending:!1,data:null,method:null,action:null},se=[],we=-1;function T(e){return{current:e}}function Y(e){0>we||(e.current=se[we],se[we]=null,we--)}function D(e,a){we++,se[we]=e.current,e.current=a}var V=T(null),te=T(null),fe=T(null),oe=T(null);function K(e,a){switch(D(fe,a),D(te,e),D(V,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?_v(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=_v(a),e=Cv(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Y(V),D(V,e)}function de(){Y(V),Y(te),Y(fe)}function _e(e){e.memoizedState!==null&&D(oe,e);var a=V.current,o=Cv(a,e.type);a!==o&&(D(te,e),D(V,o))}function rt(e){te.current===e&&(Y(V),Y(te)),oe.current===e&&(Y(oe),zi._currentValue=P)}var De,Le;function xe(e){if(De===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);De=a&&a[1]||"",Le=-1<o.stack.indexOf(`+ at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`+`+De+e+Le}var je=!1;function at(e,a){if(!e||je)return"";je=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var ce=function(){throw Error()};if(Object.defineProperty(ce.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ce,[])}catch(J){var G=J}Reflect.construct(e,[],ce)}else{try{ce.call()}catch(J){G=J}e.call(ce.prototype)}}else{try{throw Error()}catch(J){G=J}(ce=e())&&typeof ce.catch=="function"&&ce.catch(function(){})}}catch(J){if(J&&G&&typeof J.stack=="string")return[J.stack,G.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var d=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");d&&d.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var m=l.DetermineComponentFrameRoot(),x=m[0],_=m[1];if(x&&_){var M=x.split(`+`),F=_.split(`+`);for(d=l=0;l<M.length&&!M[l].includes("DetermineComponentFrameRoot");)l++;for(;d<F.length&&!F[d].includes("DetermineComponentFrameRoot");)d++;if(l===M.length||d===F.length)for(l=M.length-1,d=F.length-1;1<=l&&0<=d&&M[l]!==F[d];)d--;for(;1<=l&&0<=d;l--,d--)if(M[l]!==F[d]){if(l!==1||d!==1)do if(l--,d--,0>d||M[l]!==F[d]){var ne=`+`+M[l].replace(" at new "," at ");return e.displayName&&ne.includes("<anonymous>")&&(ne=ne.replace("<anonymous>",e.displayName)),ne}while(1<=l&&0<=d);break}}}finally{je=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?xe(o):""}function pt(e,a){switch(e.tag){case 26:case 27:case 5:return xe(e.type);case 16:return xe("Lazy");case 13:return e.child!==a&&a!==null?xe("Suspense Fallback"):xe("Suspense");case 19:return xe("SuspenseList");case 0:case 15:return at(e.type,!1);case 11:return at(e.type.render,!1);case 1:return at(e.type,!0);case 31:return xe("Activity");default:return""}}function Je(e){try{var a="",o=null;do a+=pt(e,o),o=e,e=e.return;while(e);return a}catch(l){return`+Error generating stack: `+l.message+`+`+l.stack}}var Ue=Object.prototype.hasOwnProperty,k=t.unstable_scheduleCallback,H=t.unstable_cancelCallback,$=t.unstable_shouldYield,ye=t.unstable_requestPaint,pe=t.unstable_now,ge=t.unstable_getCurrentPriorityLevel,Se=t.unstable_ImmediatePriority,qe=t.unstable_UserBlockingPriority,Xe=t.unstable_NormalPriority,Ot=t.unstable_LowPriority,on=t.unstable_IdlePriority,dn=t.log,Fn=t.unstable_setDisableYieldValue,Ft=null,Nt=null;function fn(e){if(typeof dn=="function"&&Fn(e),Nt&&typeof Nt.setStrictMode=="function")try{Nt.setStrictMode(Ft,e)}catch{}}var $t=Math.clz32?Math.clz32:ya,Xo=Math.log,cr=Math.LN2;function ya(e){return e>>>=0,e===0?32:31-(Xo(e)/cr|0)|0}var As=256,Rs=262144,Xr=4194304;function va(e){var a=e&42;if(a!==0)return a;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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Be(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,m=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var _=l&134217727;return _!==0?(l=_&~m,l!==0?d=va(l):(x&=_,x!==0?d=va(x):o||(o=_&~e,o!==0&&(d=va(o))))):(_=l&~m,_!==0?d=va(_):x!==0?d=va(x):o||(o=l&~e,o!==0&&(d=va(o)))),d===0?0:a!==0&&a!==d&&(a&m)===0&&(m=d&-d,o=a&-a,m>=o||m===32&&(o&4194048)!==0)?a:d}function Et(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function Kt(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32: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+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ln(){var e=Xr;return Xr<<=1,(Xr&62914560)===0&&(Xr=4194304),e}function ur(e){for(var a=[],o=0;31>o;o++)a.push(e);return a}function At(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function gn(e,a,o,l,d,m){var x=e.pendingLanes;e.pendingLanes=o,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=o,e.entangledLanes&=o,e.errorRecoveryDisabledLanes&=o,e.shellSuspendCounter=0;var _=e.entanglements,M=e.expirationTimes,F=e.hiddenUpdates;for(o=x&~o;0<o;){var ne=31-$t(o),ce=1<<ne;_[ne]=0,M[ne]=-1;var G=F[ne];if(G!==null)for(F[ne]=null,ne=0;ne<G.length;ne++){var J=G[ne];J!==null&&(J.lane&=-536870913)}o&=~ce}l!==0&&Kr(e,l,0),m!==0&&d===0&&e.tag!==0&&(e.suspendedLanes|=m&~(x&~a))}function Kr(e,a,o){e.pendingLanes|=a,e.suspendedLanes&=~a;var l=31-$t(a);e.entangledLanes|=a,e.entanglements[l]=e.entanglements[l]|1073741824|o&261930}function yn(e,a){var o=e.entangledLanes|=a;for(e=e.entanglements;o;){var l=31-$t(o),d=1<<l;d&a|e[l]&a&&(e[l]|=a),o&=~d}}function vn(e,a){var o=a&-a;return o=(o&42)!==0?1:Ts(o),(o&(e.suspendedLanes|a))!==0?0:o}function Ts(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function sa(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Xu(){var e=Z.p;return e!==0?e:(e=window.event,e===void 0?32:Zv(e.type))}function up(e,a){var o=Z.p;try{return Z.p=e,a()}finally{Z.p=o}}var dr=Math.random().toString(36).slice(2),en="__reactFiber$"+dr,bn="__reactProps$"+dr,js="__reactContainer$"+dr,Ku="__reactEvents$"+dr,KS="__reactListeners$"+dr,QS="__reactHandles$"+dr,dp="__reactResources$"+dr,Ko="__reactMarker$"+dr;function Qu(e){delete e[en],delete e[bn],delete e[Ku],delete e[KS],delete e[QS]}function Os(e){var a=e[en];if(a)return a;for(var o=e.parentNode;o;){if(a=o[js]||o[en]){if(o=a.alternate,a.child!==null||o!==null&&o.child!==null)for(e=kv(e);e!==null;){if(o=e[en])return o;e=kv(e)}return a}e=o,o=e.parentNode}return null}function ks(e){if(e=e[en]||e[js]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Qo(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function Ms(e){var a=e[dp];return a||(a=e[dp]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Qt(e){e[Ko]=!0}var fp=new Set,mp={};function Qr(e,a){Ds(e,a),Ds(e+"Capture",a)}function Ds(e,a){for(mp[e]=a,e=0;e<a.length;e++)fp.add(a[e])}var WS=RegExp("^[: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]*$"),hp={},pp={};function JS(e){return Ue.call(pp,e)?!0:Ue.call(hp,e)?!1:WS.test(e)?pp[e]=!0:(hp[e]=!0,!1)}function vl(e,a,o){if(JS(a))if(o===null)e.removeAttribute(a);else{switch(typeof o){case"undefined":case"function":case"symbol":e.removeAttribute(a);return;case"boolean":var l=a.toLowerCase().slice(0,5);if(l!=="data-"&&l!=="aria-"){e.removeAttribute(a);return}}e.setAttribute(a,""+o)}}function bl(e,a,o){if(o===null)e.removeAttribute(a);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(a);return}e.setAttribute(a,""+o)}}function za(e,a,o,l){if(l===null)e.removeAttribute(o);else{switch(typeof l){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(o);return}e.setAttributeNS(a,o,""+l)}}function $n(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function gp(e){var a=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function eE(e,a,o){var l=Object.getOwnPropertyDescriptor(e.constructor.prototype,a);if(!e.hasOwnProperty(a)&&typeof l<"u"&&typeof l.get=="function"&&typeof l.set=="function"){var d=l.get,m=l.set;return Object.defineProperty(e,a,{configurable:!0,get:function(){return d.call(this)},set:function(x){o=""+x,m.call(this,x)}}),Object.defineProperty(e,a,{enumerable:l.enumerable}),{getValue:function(){return o},setValue:function(x){o=""+x},stopTracking:function(){e._valueTracker=null,delete e[a]}}}}function Wu(e){if(!e._valueTracker){var a=gp(e)?"checked":"value";e._valueTracker=eE(e,a,""+e[a])}}function yp(e){if(!e)return!1;var a=e._valueTracker;if(!a)return!0;var o=a.getValue(),l="";return e&&(l=gp(e)?e.checked?"true":"false":e.value),e=l,e!==o?(a.setValue(e),!0):!1}function xl(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}}var tE=/[\n"\\]/g;function Gn(e){return e.replace(tE,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Ju(e,a,o,l,d,m,x,_){e.name="",x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"?e.type=x:e.removeAttribute("type"),a!=null?x==="number"?(a===0&&e.value===""||e.value!=a)&&(e.value=""+$n(a)):e.value!==""+$n(a)&&(e.value=""+$n(a)):x!=="submit"&&x!=="reset"||e.removeAttribute("value"),a!=null?ed(e,x,$n(a)):o!=null?ed(e,x,$n(o)):l!=null&&e.removeAttribute("value"),d==null&&m!=null&&(e.defaultChecked=!!m),d!=null&&(e.checked=d&&typeof d!="function"&&typeof d!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+$n(_):e.removeAttribute("name")}function vp(e,a,o,l,d,m,x,_){if(m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(e.type=m),a!=null||o!=null){if(!(m!=="submit"&&m!=="reset"||a!=null)){Wu(e);return}o=o!=null?""+$n(o):"",a=a!=null?""+$n(a):o,_||a===e.value||(e.value=a),e.defaultValue=a}l=l??d,l=typeof l!="function"&&typeof l!="symbol"&&!!l,e.checked=_?e.checked:!!l,e.defaultChecked=!!l,x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"&&(e.name=x),Wu(e)}function ed(e,a,o){a==="number"&&xl(e.ownerDocument)===e||e.defaultValue===""+o||(e.defaultValue=""+o)}function zs(e,a,o,l){if(e=e.options,a){a={};for(var d=0;d<o.length;d++)a["$"+o[d]]=!0;for(o=0;o<e.length;o++)d=a.hasOwnProperty("$"+e[o].value),e[o].selected!==d&&(e[o].selected=d),d&&l&&(e[o].defaultSelected=!0)}else{for(o=""+$n(o),a=null,d=0;d<e.length;d++){if(e[d].value===o){e[d].selected=!0,l&&(e[d].defaultSelected=!0);return}a!==null||e[d].disabled||(a=e[d])}a!==null&&(a.selected=!0)}}function bp(e,a,o){if(a!=null&&(a=""+$n(a),a!==e.value&&(e.value=a),o==null)){e.defaultValue!==a&&(e.defaultValue=a);return}e.defaultValue=o!=null?""+$n(o):""}function xp(e,a,o,l){if(a==null){if(l!=null){if(o!=null)throw Error(s(92));if(be(l)){if(1<l.length)throw Error(s(93));l=l[0]}o=l}o==null&&(o=""),a=o}o=$n(a),e.defaultValue=o,l=e.textContent,l===o&&l!==""&&l!==null&&(e.value=l),Wu(e)}function Ls(e,a){if(a){var o=e.firstChild;if(o&&o===e.lastChild&&o.nodeType===3){o.nodeValue=a;return}}e.textContent=a}var nE=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function wp(e,a,o){var l=a.indexOf("--")===0;o==null||typeof o=="boolean"||o===""?l?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="":l?e.setProperty(a,o):typeof o!="number"||o===0||nE.has(a)?a==="float"?e.cssFloat=o:e[a]=(""+o).trim():e[a]=o+"px"}function Sp(e,a,o){if(a!=null&&typeof a!="object")throw Error(s(62));if(e=e.style,o!=null){for(var l in o)!o.hasOwnProperty(l)||a!=null&&a.hasOwnProperty(l)||(l.indexOf("--")===0?e.setProperty(l,""):l==="float"?e.cssFloat="":e[l]="");for(var d in a)l=a[d],a.hasOwnProperty(d)&&o[d]!==l&&wp(e,d,l)}else for(var m in a)a.hasOwnProperty(m)&&wp(e,m,a[m])}function td(e){if(e.indexOf("-")===-1)return!1;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 aE=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),rE=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function wl(e){return rE.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function La(){}var nd=null;function ad(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Us=null,Bs=null;function Ep(e){var a=ks(e);if(a&&(e=a.stateNode)){var o=e[bn]||null;e:switch(e=a.stateNode,a.type){case"input":if(Ju(e,o.value,o.defaultValue,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name),a=o.name,o.type==="radio"&&a!=null){for(o=e;o.parentNode;)o=o.parentNode;for(o=o.querySelectorAll('input[name="'+Gn(""+a)+'"][type="radio"]'),a=0;a<o.length;a++){var l=o[a];if(l!==e&&l.form===e.form){var d=l[bn]||null;if(!d)throw Error(s(90));Ju(l,d.value,d.defaultValue,d.defaultValue,d.checked,d.defaultChecked,d.type,d.name)}}for(a=0;a<o.length;a++)l=o[a],l.form===e.form&&yp(l)}break e;case"textarea":bp(e,o.value,o.defaultValue);break e;case"select":a=o.value,a!=null&&zs(e,!!o.multiple,a,!1)}}}var rd=!1;function _p(e,a,o){if(rd)return e(a,o);rd=!0;try{var l=e(a);return l}finally{if(rd=!1,(Us!==null||Bs!==null)&&(lc(),Us&&(a=Us,e=Bs,Bs=Us=null,Ep(a),e)))for(a=0;a<e.length;a++)Ep(e[a])}}function Wo(e,a){var o=e.stateNode;if(o===null)return null;var l=o[bn]||null;if(l===null)return null;o=l[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(l=!l.disabled)||(e=e.type,l=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!l;break e;default:e=!1}if(e)return null;if(o&&typeof o!="function")throw Error(s(231,a,typeof o));return o}var Ua=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),sd=!1;if(Ua)try{var Jo={};Object.defineProperty(Jo,"passive",{get:function(){sd=!0}}),window.addEventListener("test",Jo,Jo),window.removeEventListener("test",Jo,Jo)}catch{sd=!1}var fr=null,od=null,Sl=null;function Cp(){if(Sl)return Sl;var e,a=od,o=a.length,l,d="value"in fr?fr.value:fr.textContent,m=d.length;for(e=0;e<o&&a[e]===d[e];e++);var x=o-e;for(l=1;l<=x&&a[o-l]===d[m-l];l++);return Sl=d.slice(e,1<l?1-l:void 0)}function El(e){var a=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&a===13&&(e=13)):e=a,e===10&&(e=13),32<=e||e===13?e:0}function _l(){return!0}function Np(){return!1}function xn(e){function a(o,l,d,m,x){this._reactName=o,this._targetInst=d,this.type=l,this.nativeEvent=m,this.target=x,this.currentTarget=null;for(var _ in e)e.hasOwnProperty(_)&&(o=e[_],this[_]=o?o(m):m[_]);return this.isDefaultPrevented=(m.defaultPrevented!=null?m.defaultPrevented:m.returnValue===!1)?_l:Np,this.isPropagationStopped=Np,this}return y(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var o=this.nativeEvent;o&&(o.preventDefault?o.preventDefault():typeof o.returnValue!="unknown"&&(o.returnValue=!1),this.isDefaultPrevented=_l)},stopPropagation:function(){var o=this.nativeEvent;o&&(o.stopPropagation?o.stopPropagation():typeof o.cancelBubble!="unknown"&&(o.cancelBubble=!0),this.isPropagationStopped=_l)},persist:function(){},isPersistent:_l}),a}var Wr={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Cl=xn(Wr),ei=y({},Wr,{view:0,detail:0}),sE=xn(ei),id,ld,ti,Nl=y({},ei,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ud,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==ti&&(ti&&e.type==="mousemove"?(id=e.screenX-ti.screenX,ld=e.screenY-ti.screenY):ld=id=0,ti=e),id)},movementY:function(e){return"movementY"in e?e.movementY:ld}}),Ap=xn(Nl),oE=y({},Nl,{dataTransfer:0}),iE=xn(oE),lE=y({},ei,{relatedTarget:0}),cd=xn(lE),cE=y({},Wr,{animationName:0,elapsedTime:0,pseudoElement:0}),uE=xn(cE),dE=y({},Wr,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),fE=xn(dE),mE=y({},Wr,{data:0}),Rp=xn(mE),hE={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},pE={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},gE={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function yE(e){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(e):(e=gE[e])?!!a[e]:!1}function ud(){return yE}var vE=y({},ei,{key:function(e){if(e.key){var a=hE[e.key]||e.key;if(a!=="Unidentified")return a}return e.type==="keypress"?(e=El(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?pE[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ud,charCode:function(e){return e.type==="keypress"?El(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?El(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),bE=xn(vE),xE=y({},Nl,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Tp=xn(xE),wE=y({},ei,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ud}),SE=xn(wE),EE=y({},Wr,{propertyName:0,elapsedTime:0,pseudoElement:0}),_E=xn(EE),CE=y({},Nl,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),NE=xn(CE),AE=y({},Wr,{newState:0,oldState:0}),RE=xn(AE),TE=[9,13,27,32],dd=Ua&&"CompositionEvent"in window,ni=null;Ua&&"documentMode"in document&&(ni=document.documentMode);var jE=Ua&&"TextEvent"in window&&!ni,jp=Ua&&(!dd||ni&&8<ni&&11>=ni),Op=" ",kp=!1;function Mp(e,a){switch(e){case"keyup":return TE.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Dp(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ps=!1;function OE(e,a){switch(e){case"compositionend":return Dp(a);case"keypress":return a.which!==32?null:(kp=!0,Op);case"textInput":return e=a.data,e===Op&&kp?null:e;default:return null}}function kE(e,a){if(Ps)return e==="compositionend"||!dd&&Mp(e,a)?(e=Cp(),Sl=od=fr=null,Ps=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return jp&&a.locale!=="ko"?null:a.data;default:return null}}var ME={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function zp(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a==="input"?!!ME[e.type]:a==="textarea"}function Lp(e,a,o,l){Us?Bs?Bs.push(l):Bs=[l]:Us=l,a=pc(a,"onChange"),0<a.length&&(o=new Cl("onChange","change",null,o,l),e.push({event:o,listeners:a}))}var ai=null,ri=null;function DE(e){vv(e,0)}function Al(e){var a=Qo(e);if(yp(a))return e}function Up(e,a){if(e==="change")return a}var Bp=!1;if(Ua){var fd;if(Ua){var md="oninput"in document;if(!md){var Pp=document.createElement("div");Pp.setAttribute("oninput","return;"),md=typeof Pp.oninput=="function"}fd=md}else fd=!1;Bp=fd&&(!document.documentMode||9<document.documentMode)}function Hp(){ai&&(ai.detachEvent("onpropertychange",Vp),ri=ai=null)}function Vp(e){if(e.propertyName==="value"&&Al(ri)){var a=[];Lp(a,ri,e,ad(e)),_p(DE,a)}}function zE(e,a,o){e==="focusin"?(Hp(),ai=a,ri=o,ai.attachEvent("onpropertychange",Vp)):e==="focusout"&&Hp()}function LE(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Al(ri)}function UE(e,a){if(e==="click")return Al(a)}function BE(e,a){if(e==="input"||e==="change")return Al(a)}function PE(e,a){return e===a&&(e!==0||1/e===1/a)||e!==e&&a!==a}var jn=typeof Object.is=="function"?Object.is:PE;function si(e,a){if(jn(e,a))return!0;if(typeof e!="object"||e===null||typeof a!="object"||a===null)return!1;var o=Object.keys(e),l=Object.keys(a);if(o.length!==l.length)return!1;for(l=0;l<o.length;l++){var d=o[l];if(!Ue.call(a,d)||!jn(e[d],a[d]))return!1}return!0}function Ip(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function qp(e,a){var o=Ip(e);e=0;for(var l;o;){if(o.nodeType===3){if(l=e+o.textContent.length,e<=a&&l>=a)return{node:o,offset:a-e};e=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Ip(o)}}function Fp(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?Fp(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function $p(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=xl(e.document);a instanceof e.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)e=a.contentWindow;else break;a=xl(e.document)}return a}function hd(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a&&(a==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||a==="textarea"||e.contentEditable==="true")}var HE=Ua&&"documentMode"in document&&11>=document.documentMode,Hs=null,pd=null,oi=null,gd=!1;function Gp(e,a,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;gd||Hs==null||Hs!==xl(l)||(l=Hs,"selectionStart"in l&&hd(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),oi&&si(oi,l)||(oi=l,l=pc(pd,"onSelect"),0<l.length&&(a=new Cl("onSelect","select",null,a,o),e.push({event:a,listeners:l}),a.target=Hs)))}function Jr(e,a){var o={};return o[e.toLowerCase()]=a.toLowerCase(),o["Webkit"+e]="webkit"+a,o["Moz"+e]="moz"+a,o}var Vs={animationend:Jr("Animation","AnimationEnd"),animationiteration:Jr("Animation","AnimationIteration"),animationstart:Jr("Animation","AnimationStart"),transitionrun:Jr("Transition","TransitionRun"),transitionstart:Jr("Transition","TransitionStart"),transitioncancel:Jr("Transition","TransitionCancel"),transitionend:Jr("Transition","TransitionEnd")},yd={},Yp={};Ua&&(Yp=document.createElement("div").style,"AnimationEvent"in window||(delete Vs.animationend.animation,delete Vs.animationiteration.animation,delete Vs.animationstart.animation),"TransitionEvent"in window||delete Vs.transitionend.transition);function es(e){if(yd[e])return yd[e];if(!Vs[e])return e;var a=Vs[e],o;for(o in a)if(a.hasOwnProperty(o)&&o in Yp)return yd[e]=a[o];return e}var Zp=es("animationend"),Xp=es("animationiteration"),Kp=es("animationstart"),VE=es("transitionrun"),IE=es("transitionstart"),qE=es("transitioncancel"),Qp=es("transitionend"),Wp=new Map,vd="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");vd.push("scrollEnd");function oa(e,a){Wp.set(e,a),Qr(a,[e])}var Rl=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},Yn=[],Is=0,bd=0;function Tl(){for(var e=Is,a=bd=Is=0;a<e;){var o=Yn[a];Yn[a++]=null;var l=Yn[a];Yn[a++]=null;var d=Yn[a];Yn[a++]=null;var m=Yn[a];if(Yn[a++]=null,l!==null&&d!==null){var x=l.pending;x===null?d.next=d:(d.next=x.next,x.next=d),l.pending=d}m!==0&&Jp(o,d,m)}}function jl(e,a,o,l){Yn[Is++]=e,Yn[Is++]=a,Yn[Is++]=o,Yn[Is++]=l,bd|=l,e.lanes|=l,e=e.alternate,e!==null&&(e.lanes|=l)}function xd(e,a,o,l){return jl(e,a,o,l),Ol(e)}function ts(e,a){return jl(e,null,null,a),Ol(e)}function Jp(e,a,o){e.lanes|=o;var l=e.alternate;l!==null&&(l.lanes|=o);for(var d=!1,m=e.return;m!==null;)m.childLanes|=o,l=m.alternate,l!==null&&(l.childLanes|=o),m.tag===22&&(e=m.stateNode,e===null||e._visibility&1||(d=!0)),e=m,m=m.return;return e.tag===3?(m=e.stateNode,d&&a!==null&&(d=31-$t(o),e=m.hiddenUpdates,l=e[d],l===null?e[d]=[a]:l.push(a),a.lane=o|536870912),m):null}function Ol(e){if(50<Ri)throw Ri=0,jf=null,Error(s(185));for(var a=e.return;a!==null;)e=a,a=e.return;return e.tag===3?e.stateNode:null}var qs={};function FE(e,a,o,l){this.tag=e,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function On(e,a,o,l){return new FE(e,a,o,l)}function wd(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Ba(e,a){var o=e.alternate;return o===null?(o=On(e.tag,a,e.key,e.mode),o.elementType=e.elementType,o.type=e.type,o.stateNode=e.stateNode,o.alternate=e,e.alternate=o):(o.pendingProps=a,o.type=e.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=e.flags&65011712,o.childLanes=e.childLanes,o.lanes=e.lanes,o.child=e.child,o.memoizedProps=e.memoizedProps,o.memoizedState=e.memoizedState,o.updateQueue=e.updateQueue,a=e.dependencies,o.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},o.sibling=e.sibling,o.index=e.index,o.ref=e.ref,o.refCleanup=e.refCleanup,o}function eg(e,a){e.flags&=65011714;var o=e.alternate;return o===null?(e.childLanes=0,e.lanes=a,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=o.childLanes,e.lanes=o.lanes,e.child=o.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=o.memoizedProps,e.memoizedState=o.memoizedState,e.updateQueue=o.updateQueue,e.type=o.type,a=o.dependencies,e.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e}function kl(e,a,o,l,d,m){var x=0;if(l=e,typeof e=="function")wd(e)&&(x=1);else if(typeof e=="string")x=X_(e,o,V.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case le:return e=On(31,o,a,d),e.elementType=le,e.lanes=m,e;case S:return ns(o.children,d,m,a);case C:x=8,d|=24;break;case A:return e=On(12,o,a,d|2),e.elementType=A,e.lanes=m,e;case I:return e=On(13,o,a,d),e.elementType=I,e.lanes=m,e;case ee:return e=On(19,o,a,d),e.elementType=ee,e.lanes=m,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case R:x=10;break e;case O:x=9;break e;case L:x=11;break e;case U:x=14;break e;case Q:x=16,l=null;break e}x=29,o=Error(s(130,e===null?"null":typeof e,"")),l=null}return a=On(x,o,a,d),a.elementType=e,a.type=l,a.lanes=m,a}function ns(e,a,o,l){return e=On(7,e,l,a),e.lanes=o,e}function Sd(e,a,o){return e=On(6,e,null,a),e.lanes=o,e}function tg(e){var a=On(18,null,null,0);return a.stateNode=e,a}function Ed(e,a,o){return a=On(4,e.children!==null?e.children:[],e.key,a),a.lanes=o,a.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},a}var ng=new WeakMap;function Zn(e,a){if(typeof e=="object"&&e!==null){var o=ng.get(e);return o!==void 0?o:(a={value:e,source:a,stack:Je(a)},ng.set(e,a),a)}return{value:e,source:a,stack:Je(a)}}var Fs=[],$s=0,Ml=null,ii=0,Xn=[],Kn=0,mr=null,ba=1,xa="";function Pa(e,a){Fs[$s++]=ii,Fs[$s++]=Ml,Ml=e,ii=a}function ag(e,a,o){Xn[Kn++]=ba,Xn[Kn++]=xa,Xn[Kn++]=mr,mr=e;var l=ba;e=xa;var d=32-$t(l)-1;l&=~(1<<d),o+=1;var m=32-$t(a)+d;if(30<m){var x=d-d%5;m=(l&(1<<x)-1).toString(32),l>>=x,d-=x,ba=1<<32-$t(a)+d|o<<d|l,xa=m+e}else ba=1<<m|o<<d|l,xa=e}function _d(e){e.return!==null&&(Pa(e,1),ag(e,1,0))}function Cd(e){for(;e===Ml;)Ml=Fs[--$s],Fs[$s]=null,ii=Fs[--$s],Fs[$s]=null;for(;e===mr;)mr=Xn[--Kn],Xn[Kn]=null,xa=Xn[--Kn],Xn[Kn]=null,ba=Xn[--Kn],Xn[Kn]=null}function rg(e,a){Xn[Kn++]=ba,Xn[Kn++]=xa,Xn[Kn++]=mr,ba=a.id,xa=a.overflow,mr=e}var tn=null,wt=null,nt=!1,hr=null,Qn=!1,Nd=Error(s(519));function pr(e){var a=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw li(Zn(a,e)),Nd}function sg(e){var a=e.stateNode,o=e.type,l=e.memoizedProps;switch(a[en]=e,a[bn]=l,o){case"dialog":Qe("cancel",a),Qe("close",a);break;case"iframe":case"object":case"embed":Qe("load",a);break;case"video":case"audio":for(o=0;o<ji.length;o++)Qe(ji[o],a);break;case"source":Qe("error",a);break;case"img":case"image":case"link":Qe("error",a),Qe("load",a);break;case"details":Qe("toggle",a);break;case"input":Qe("invalid",a),vp(a,l.value,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name,!0);break;case"select":Qe("invalid",a);break;case"textarea":Qe("invalid",a),xp(a,l.value,l.defaultValue,l.children)}o=l.children,typeof o!="string"&&typeof o!="number"&&typeof o!="bigint"||a.textContent===""+o||l.suppressHydrationWarning===!0||Sv(a.textContent,o)?(l.popover!=null&&(Qe("beforetoggle",a),Qe("toggle",a)),l.onScroll!=null&&Qe("scroll",a),l.onScrollEnd!=null&&Qe("scrollend",a),l.onClick!=null&&(a.onclick=La),a=!0):a=!1,a||pr(e,!0)}function og(e){for(tn=e.return;tn;)switch(tn.tag){case 5:case 31:case 13:Qn=!1;return;case 27:case 3:Qn=!0;return;default:tn=tn.return}}function Gs(e){if(e!==tn)return!1;if(!nt)return og(e),nt=!0,!1;var a=e.tag,o;if((o=a!==3&&a!==27)&&((o=a===5)&&(o=e.type,o=!(o!=="form"&&o!=="button")||$f(e.type,e.memoizedProps)),o=!o),o&&wt&&pr(e),og(e),a===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));wt=Ov(e)}else if(a===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));wt=Ov(e)}else a===27?(a=wt,Tr(e.type)?(e=Kf,Kf=null,wt=e):wt=a):wt=tn?Jn(e.stateNode.nextSibling):null;return!0}function as(){wt=tn=null,nt=!1}function Ad(){var e=hr;return e!==null&&(_n===null?_n=e:_n.push.apply(_n,e),hr=null),e}function li(e){hr===null?hr=[e]:hr.push(e)}var Rd=T(null),rs=null,Ha=null;function gr(e,a,o){D(Rd,a._currentValue),a._currentValue=o}function Va(e){e._currentValue=Rd.current,Y(Rd)}function Td(e,a,o){for(;e!==null;){var l=e.alternate;if((e.childLanes&a)!==a?(e.childLanes|=a,l!==null&&(l.childLanes|=a)):l!==null&&(l.childLanes&a)!==a&&(l.childLanes|=a),e===o)break;e=e.return}}function jd(e,a,o,l){var d=e.child;for(d!==null&&(d.return=e);d!==null;){var m=d.dependencies;if(m!==null){var x=d.child;m=m.firstContext;e:for(;m!==null;){var _=m;m=d;for(var M=0;M<a.length;M++)if(_.context===a[M]){m.lanes|=o,_=m.alternate,_!==null&&(_.lanes|=o),Td(m.return,o,e),l||(x=null);break e}m=_.next}}else if(d.tag===18){if(x=d.return,x===null)throw Error(s(341));x.lanes|=o,m=x.alternate,m!==null&&(m.lanes|=o),Td(x,o,e),x=null}else x=d.child;if(x!==null)x.return=d;else for(x=d;x!==null;){if(x===e){x=null;break}if(d=x.sibling,d!==null){d.return=x.return,x=d;break}x=x.return}d=x}}function Ys(e,a,o,l){e=null;for(var d=a,m=!1;d!==null;){if(!m){if((d.flags&524288)!==0)m=!0;else if((d.flags&262144)!==0)break}if(d.tag===10){var x=d.alternate;if(x===null)throw Error(s(387));if(x=x.memoizedProps,x!==null){var _=d.type;jn(d.pendingProps.value,x.value)||(e!==null?e.push(_):e=[_])}}else if(d===oe.current){if(x=d.alternate,x===null)throw Error(s(387));x.memoizedState.memoizedState!==d.memoizedState.memoizedState&&(e!==null?e.push(zi):e=[zi])}d=d.return}e!==null&&jd(a,e,o,l),a.flags|=262144}function Dl(e){for(e=e.firstContext;e!==null;){if(!jn(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function ss(e){rs=e,Ha=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function nn(e){return ig(rs,e)}function zl(e,a){return rs===null&&ss(e),ig(e,a)}function ig(e,a){var o=a._currentValue;if(a={context:a,memoizedValue:o,next:null},Ha===null){if(e===null)throw Error(s(308));Ha=a,e.dependencies={lanes:0,firstContext:a},e.flags|=524288}else Ha=Ha.next=a;return o}var $E=typeof AbortController<"u"?AbortController:function(){var e=[],a=this.signal={aborted:!1,addEventListener:function(o,l){e.push(l)}};this.abort=function(){a.aborted=!0,e.forEach(function(o){return o()})}},GE=t.unstable_scheduleCallback,YE=t.unstable_NormalPriority,Lt={$$typeof:R,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Od(){return{controller:new $E,data:new Map,refCount:0}}function ci(e){e.refCount--,e.refCount===0&&GE(YE,function(){e.controller.abort()})}var ui=null,kd=0,Zs=0,Xs=null;function ZE(e,a){if(ui===null){var o=ui=[];kd=0,Zs=Lf(),Xs={status:"pending",value:void 0,then:function(l){o.push(l)}}}return kd++,a.then(lg,lg),a}function lg(){if(--kd===0&&ui!==null){Xs!==null&&(Xs.status="fulfilled");var e=ui;ui=null,Zs=0,Xs=null;for(var a=0;a<e.length;a++)(0,e[a])()}}function XE(e,a){var o=[],l={status:"pending",value:null,reason:null,then:function(d){o.push(d)}};return e.then(function(){l.status="fulfilled",l.value=a;for(var d=0;d<o.length;d++)(0,o[d])(a)},function(d){for(l.status="rejected",l.reason=d,d=0;d<o.length;d++)(0,o[d])(void 0)}),l}var cg=j.S;j.S=function(e,a){Gy=pe(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&ZE(e,a),cg!==null&&cg(e,a)};var os=T(null);function Md(){var e=os.current;return e!==null?e:bt.pooledCache}function Ll(e,a){a===null?D(os,os.current):D(os,a.pool)}function ug(){var e=Md();return e===null?null:{parent:Lt._currentValue,pool:e}}var Ks=Error(s(460)),Dd=Error(s(474)),Ul=Error(s(542)),Bl={then:function(){}};function dg(e){return e=e.status,e==="fulfilled"||e==="rejected"}function fg(e,a,o){switch(o=e[o],o===void 0?e.push(a):o!==a&&(a.then(La,La),a=o),a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,hg(e),e;default:if(typeof a.status=="string")a.then(La,La);else{if(e=bt,e!==null&&100<e.shellSuspendCounter)throw Error(s(482));e=a,e.status="pending",e.then(function(l){if(a.status==="pending"){var d=a;d.status="fulfilled",d.value=l}},function(l){if(a.status==="pending"){var d=a;d.status="rejected",d.reason=l}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,hg(e),e}throw ls=a,Ks}}function is(e){try{var a=e._init;return a(e._payload)}catch(o){throw o!==null&&typeof o=="object"&&typeof o.then=="function"?(ls=o,Ks):o}}var ls=null;function mg(){if(ls===null)throw Error(s(459));var e=ls;return ls=null,e}function hg(e){if(e===Ks||e===Ul)throw Error(s(483))}var Qs=null,di=0;function Pl(e){var a=di;return di+=1,Qs===null&&(Qs=[]),fg(Qs,e,a)}function fi(e,a){a=a.props.ref,e.ref=a!==void 0?a:null}function Hl(e,a){throw a.$$typeof===w?Error(s(525)):(e=Object.prototype.toString.call(a),Error(s(31,e==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":e)))}function pg(e){function a(B,z){if(e){var q=B.deletions;q===null?(B.deletions=[z],B.flags|=16):q.push(z)}}function o(B,z){if(!e)return null;for(;z!==null;)a(B,z),z=z.sibling;return null}function l(B){for(var z=new Map;B!==null;)B.key!==null?z.set(B.key,B):z.set(B.index,B),B=B.sibling;return z}function d(B,z){return B=Ba(B,z),B.index=0,B.sibling=null,B}function m(B,z,q){return B.index=q,e?(q=B.alternate,q!==null?(q=q.index,q<z?(B.flags|=67108866,z):q):(B.flags|=67108866,z)):(B.flags|=1048576,z)}function x(B){return e&&B.alternate===null&&(B.flags|=67108866),B}function _(B,z,q,ie){return z===null||z.tag!==6?(z=Sd(q,B.mode,ie),z.return=B,z):(z=d(z,q),z.return=B,z)}function M(B,z,q,ie){var Me=q.type;return Me===S?ne(B,z,q.props.children,ie,q.key):z!==null&&(z.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===Q&&is(Me)===z.type)?(z=d(z,q.props),fi(z,q),z.return=B,z):(z=kl(q.type,q.key,q.props,null,B.mode,ie),fi(z,q),z.return=B,z)}function F(B,z,q,ie){return z===null||z.tag!==4||z.stateNode.containerInfo!==q.containerInfo||z.stateNode.implementation!==q.implementation?(z=Ed(q,B.mode,ie),z.return=B,z):(z=d(z,q.children||[]),z.return=B,z)}function ne(B,z,q,ie,Me){return z===null||z.tag!==7?(z=ns(q,B.mode,ie,Me),z.return=B,z):(z=d(z,q),z.return=B,z)}function ce(B,z,q){if(typeof z=="string"&&z!==""||typeof z=="number"||typeof z=="bigint")return z=Sd(""+z,B.mode,q),z.return=B,z;if(typeof z=="object"&&z!==null){switch(z.$$typeof){case N:return q=kl(z.type,z.key,z.props,null,B.mode,q),fi(q,z),q.return=B,q;case E:return z=Ed(z,B.mode,q),z.return=B,z;case Q:return z=is(z),ce(B,z,q)}if(be(z)||re(z))return z=ns(z,B.mode,q,null),z.return=B,z;if(typeof z.then=="function")return ce(B,Pl(z),q);if(z.$$typeof===R)return ce(B,zl(B,z),q);Hl(B,z)}return null}function G(B,z,q,ie){var Me=z!==null?z.key:null;if(typeof q=="string"&&q!==""||typeof q=="number"||typeof q=="bigint")return Me!==null?null:_(B,z,""+q,ie);if(typeof q=="object"&&q!==null){switch(q.$$typeof){case N:return q.key===Me?M(B,z,q,ie):null;case E:return q.key===Me?F(B,z,q,ie):null;case Q:return q=is(q),G(B,z,q,ie)}if(be(q)||re(q))return Me!==null?null:ne(B,z,q,ie,null);if(typeof q.then=="function")return G(B,z,Pl(q),ie);if(q.$$typeof===R)return G(B,z,zl(B,q),ie);Hl(B,q)}return null}function J(B,z,q,ie,Me){if(typeof ie=="string"&&ie!==""||typeof ie=="number"||typeof ie=="bigint")return B=B.get(q)||null,_(z,B,""+ie,Me);if(typeof ie=="object"&&ie!==null){switch(ie.$$typeof){case N:return B=B.get(ie.key===null?q:ie.key)||null,M(z,B,ie,Me);case E:return B=B.get(ie.key===null?q:ie.key)||null,F(z,B,ie,Me);case Q:return ie=is(ie),J(B,z,q,ie,Me)}if(be(ie)||re(ie))return B=B.get(q)||null,ne(z,B,ie,Me,null);if(typeof ie.then=="function")return J(B,z,q,Pl(ie),Me);if(ie.$$typeof===R)return J(B,z,q,zl(z,ie),Me);Hl(z,ie)}return null}function Ce(B,z,q,ie){for(var Me=null,lt=null,Oe=z,Ge=z=0,tt=null;Oe!==null&&Ge<q.length;Ge++){Oe.index>Ge?(tt=Oe,Oe=null):tt=Oe.sibling;var ct=G(B,Oe,q[Ge],ie);if(ct===null){Oe===null&&(Oe=tt);break}e&&Oe&&ct.alternate===null&&a(B,Oe),z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct,Oe=tt}if(Ge===q.length)return o(B,Oe),nt&&Pa(B,Ge),Me;if(Oe===null){for(;Ge<q.length;Ge++)Oe=ce(B,q[Ge],ie),Oe!==null&&(z=m(Oe,z,Ge),lt===null?Me=Oe:lt.sibling=Oe,lt=Oe);return nt&&Pa(B,Ge),Me}for(Oe=l(Oe);Ge<q.length;Ge++)tt=J(Oe,B,Ge,q[Ge],ie),tt!==null&&(e&&tt.alternate!==null&&Oe.delete(tt.key===null?Ge:tt.key),z=m(tt,z,Ge),lt===null?Me=tt:lt.sibling=tt,lt=tt);return e&&Oe.forEach(function(Dr){return a(B,Dr)}),nt&&Pa(B,Ge),Me}function ze(B,z,q,ie){if(q==null)throw Error(s(151));for(var Me=null,lt=null,Oe=z,Ge=z=0,tt=null,ct=q.next();Oe!==null&&!ct.done;Ge++,ct=q.next()){Oe.index>Ge?(tt=Oe,Oe=null):tt=Oe.sibling;var Dr=G(B,Oe,ct.value,ie);if(Dr===null){Oe===null&&(Oe=tt);break}e&&Oe&&Dr.alternate===null&&a(B,Oe),z=m(Dr,z,Ge),lt===null?Me=Dr:lt.sibling=Dr,lt=Dr,Oe=tt}if(ct.done)return o(B,Oe),nt&&Pa(B,Ge),Me;if(Oe===null){for(;!ct.done;Ge++,ct=q.next())ct=ce(B,ct.value,ie),ct!==null&&(z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct);return nt&&Pa(B,Ge),Me}for(Oe=l(Oe);!ct.done;Ge++,ct=q.next())ct=J(Oe,B,Ge,ct.value,ie),ct!==null&&(e&&ct.alternate!==null&&Oe.delete(ct.key===null?Ge:ct.key),z=m(ct,z,Ge),lt===null?Me=ct:lt.sibling=ct,lt=ct);return e&&Oe.forEach(function(oC){return a(B,oC)}),nt&&Pa(B,Ge),Me}function vt(B,z,q,ie){if(typeof q=="object"&&q!==null&&q.type===S&&q.key===null&&(q=q.props.children),typeof q=="object"&&q!==null){switch(q.$$typeof){case N:e:{for(var Me=q.key;z!==null;){if(z.key===Me){if(Me=q.type,Me===S){if(z.tag===7){o(B,z.sibling),ie=d(z,q.props.children),ie.return=B,B=ie;break e}}else if(z.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===Q&&is(Me)===z.type){o(B,z.sibling),ie=d(z,q.props),fi(ie,q),ie.return=B,B=ie;break e}o(B,z);break}else a(B,z);z=z.sibling}q.type===S?(ie=ns(q.props.children,B.mode,ie,q.key),ie.return=B,B=ie):(ie=kl(q.type,q.key,q.props,null,B.mode,ie),fi(ie,q),ie.return=B,B=ie)}return x(B);case E:e:{for(Me=q.key;z!==null;){if(z.key===Me)if(z.tag===4&&z.stateNode.containerInfo===q.containerInfo&&z.stateNode.implementation===q.implementation){o(B,z.sibling),ie=d(z,q.children||[]),ie.return=B,B=ie;break e}else{o(B,z);break}else a(B,z);z=z.sibling}ie=Ed(q,B.mode,ie),ie.return=B,B=ie}return x(B);case Q:return q=is(q),vt(B,z,q,ie)}if(be(q))return Ce(B,z,q,ie);if(re(q)){if(Me=re(q),typeof Me!="function")throw Error(s(150));return q=Me.call(q),ze(B,z,q,ie)}if(typeof q.then=="function")return vt(B,z,Pl(q),ie);if(q.$$typeof===R)return vt(B,z,zl(B,q),ie);Hl(B,q)}return typeof q=="string"&&q!==""||typeof q=="number"||typeof q=="bigint"?(q=""+q,z!==null&&z.tag===6?(o(B,z.sibling),ie=d(z,q),ie.return=B,B=ie):(o(B,z),ie=Sd(q,B.mode,ie),ie.return=B,B=ie),x(B)):o(B,z)}return function(B,z,q,ie){try{di=0;var Me=vt(B,z,q,ie);return Qs=null,Me}catch(Oe){if(Oe===Ks||Oe===Ul)throw Oe;var lt=On(29,Oe,null,B.mode);return lt.lanes=ie,lt.return=B,lt}finally{}}}var cs=pg(!0),gg=pg(!1),yr=!1;function zd(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ld(e,a){e=e.updateQueue,a.updateQueue===e&&(a.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function vr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function br(e,a,o){var l=e.updateQueue;if(l===null)return null;if(l=l.shared,(dt&2)!==0){var d=l.pending;return d===null?a.next=a:(a.next=d.next,d.next=a),l.pending=a,a=Ol(e),Jp(e,null,o),a}return jl(e,l,a,o),Ol(e)}function mi(e,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,yn(e,o)}}function Ud(e,a){var o=e.updateQueue,l=e.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,m=null;if(o=o.firstBaseUpdate,o!==null){do{var x={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};m===null?d=m=x:m=m.next=x,o=o.next}while(o!==null);m===null?d=m=a:m=m.next=a}else d=m=a;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:m,shared:l.shared,callbacks:l.callbacks},e.updateQueue=o;return}e=o.lastBaseUpdate,e===null?o.firstBaseUpdate=a:e.next=a,o.lastBaseUpdate=a}var Bd=!1;function hi(){if(Bd){var e=Xs;if(e!==null)throw e}}function pi(e,a,o,l){Bd=!1;var d=e.updateQueue;yr=!1;var m=d.firstBaseUpdate,x=d.lastBaseUpdate,_=d.shared.pending;if(_!==null){d.shared.pending=null;var M=_,F=M.next;M.next=null,x===null?m=F:x.next=F,x=M;var ne=e.alternate;ne!==null&&(ne=ne.updateQueue,_=ne.lastBaseUpdate,_!==x&&(_===null?ne.firstBaseUpdate=F:_.next=F,ne.lastBaseUpdate=M))}if(m!==null){var ce=d.baseState;x=0,ne=F=M=null,_=m;do{var G=_.lane&-536870913,J=G!==_.lane;if(J?(et&G)===G:(l&G)===G){G!==0&&G===Zs&&(Bd=!0),ne!==null&&(ne=ne.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var Ce=e,ze=_;G=a;var vt=o;switch(ze.tag){case 1:if(Ce=ze.payload,typeof Ce=="function"){ce=Ce.call(vt,ce,G);break e}ce=Ce;break e;case 3:Ce.flags=Ce.flags&-65537|128;case 0:if(Ce=ze.payload,G=typeof Ce=="function"?Ce.call(vt,ce,G):Ce,G==null)break e;ce=y({},ce,G);break e;case 2:yr=!0}}G=_.callback,G!==null&&(e.flags|=64,J&&(e.flags|=8192),J=d.callbacks,J===null?d.callbacks=[G]:J.push(G))}else J={lane:G,tag:_.tag,payload:_.payload,callback:_.callback,next:null},ne===null?(F=ne=J,M=ce):ne=ne.next=J,x|=G;if(_=_.next,_===null){if(_=d.shared.pending,_===null)break;J=_,_=J.next,J.next=null,d.lastBaseUpdate=J,d.shared.pending=null}}while(!0);ne===null&&(M=ce),d.baseState=M,d.firstBaseUpdate=F,d.lastBaseUpdate=ne,m===null&&(d.shared.lanes=0),_r|=x,e.lanes=x,e.memoizedState=ce}}function yg(e,a){if(typeof e!="function")throw Error(s(191,e));e.call(a)}function vg(e,a){var o=e.callbacks;if(o!==null)for(e.callbacks=null,e=0;e<o.length;e++)yg(o[e],a)}var Ws=T(null),Vl=T(0);function bg(e,a){e=Ka,D(Vl,e),D(Ws,a),Ka=e|a.baseLanes}function Pd(){D(Vl,Ka),D(Ws,Ws.current)}function Hd(){Ka=Vl.current,Y(Ws),Y(Vl)}var kn=T(null),Wn=null;function xr(e){var a=e.alternate;D(kt,kt.current&1),D(kn,e),Wn===null&&(a===null||Ws.current!==null||a.memoizedState!==null)&&(Wn=e)}function Vd(e){D(kt,kt.current),D(kn,e),Wn===null&&(Wn=e)}function xg(e){e.tag===22?(D(kt,kt.current),D(kn,e),Wn===null&&(Wn=e)):wr()}function wr(){D(kt,kt.current),D(kn,kn.current)}function Mn(e){Y(kn),Wn===e&&(Wn=null),Y(kt)}var kt=T(0);function Il(e){for(var a=e;a!==null;){if(a.tag===13){var o=a.memoizedState;if(o!==null&&(o=o.dehydrated,o===null||Zf(o)||Xf(o)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var Ia=0,Fe=null,gt=null,Ut=null,ql=!1,Js=!1,us=!1,Fl=0,gi=0,eo=null,KE=0;function Rt(){throw Error(s(321))}function Id(e,a){if(a===null)return!1;for(var o=0;o<a.length&&o<e.length;o++)if(!jn(e[o],a[o]))return!1;return!0}function qd(e,a,o,l,d,m){return Ia=m,Fe=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,j.H=e===null||e.memoizedState===null?ay:rf,us=!1,m=o(l,d),us=!1,Js&&(m=Sg(a,o,l,d)),wg(e),m}function wg(e){j.H=bi;var a=gt!==null&>.next!==null;if(Ia=0,Ut=gt=Fe=null,ql=!1,gi=0,eo=null,a)throw Error(s(300));e===null||Bt||(e=e.dependencies,e!==null&&Dl(e)&&(Bt=!0))}function Sg(e,a,o,l){Fe=e;var d=0;do{if(Js&&(eo=null),gi=0,Js=!1,25<=d)throw Error(s(301));if(d+=1,Ut=gt=null,e.updateQueue!=null){var m=e.updateQueue;m.lastEffect=null,m.events=null,m.stores=null,m.memoCache!=null&&(m.memoCache.index=0)}j.H=ry,m=a(o,l)}while(Js);return m}function QE(){var e=j.H,a=e.useState()[0];return a=typeof a.then=="function"?yi(a):a,e=e.useState()[0],(gt!==null?gt.memoizedState:null)!==e&&(Fe.flags|=1024),a}function Fd(){var e=Fl!==0;return Fl=0,e}function $d(e,a,o){a.updateQueue=e.updateQueue,a.flags&=-2053,e.lanes&=~o}function Gd(e){if(ql){for(e=e.memoizedState;e!==null;){var a=e.queue;a!==null&&(a.pending=null),e=e.next}ql=!1}Ia=0,Ut=gt=Fe=null,Js=!1,gi=Fl=0,eo=null}function mn(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ut===null?Fe.memoizedState=Ut=e:Ut=Ut.next=e,Ut}function Mt(){if(gt===null){var e=Fe.alternate;e=e!==null?e.memoizedState:null}else e=gt.next;var a=Ut===null?Fe.memoizedState:Ut.next;if(a!==null)Ut=a,gt=e;else{if(e===null)throw Fe.alternate===null?Error(s(467)):Error(s(310));gt=e,e={memoizedState:gt.memoizedState,baseState:gt.baseState,baseQueue:gt.baseQueue,queue:gt.queue,next:null},Ut===null?Fe.memoizedState=Ut=e:Ut=Ut.next=e}return Ut}function $l(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function yi(e){var a=gi;return gi+=1,eo===null&&(eo=[]),e=fg(eo,e,a),a=Fe,(Ut===null?a.memoizedState:Ut.next)===null&&(a=a.alternate,j.H=a===null||a.memoizedState===null?ay:rf),e}function Gl(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return yi(e);if(e.$$typeof===R)return nn(e)}throw Error(s(438,String(e)))}function Yd(e){var a=null,o=Fe.updateQueue;if(o!==null&&(a=o.memoCache),a==null){var l=Fe.alternate;l!==null&&(l=l.updateQueue,l!==null&&(l=l.memoCache,l!=null&&(a={data:l.data.map(function(d){return d.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),o===null&&(o=$l(),Fe.updateQueue=o),o.memoCache=a,o=a.data[a.index],o===void 0)for(o=a.data[a.index]=Array(e),l=0;l<e;l++)o[l]=ue;return a.index++,o}function qa(e,a){return typeof a=="function"?a(e):a}function Yl(e){var a=Mt();return Zd(a,gt,e)}function Zd(e,a,o){var l=e.queue;if(l===null)throw Error(s(311));l.lastRenderedReducer=o;var d=e.baseQueue,m=l.pending;if(m!==null){if(d!==null){var x=d.next;d.next=m.next,m.next=x}a.baseQueue=d=m,l.pending=null}if(m=e.baseState,d===null)e.memoizedState=m;else{a=d.next;var _=x=null,M=null,F=a,ne=!1;do{var ce=F.lane&-536870913;if(ce!==F.lane?(et&ce)===ce:(Ia&ce)===ce){var G=F.revertLane;if(G===0)M!==null&&(M=M.next={lane:0,revertLane:0,gesture:null,action:F.action,hasEagerState:F.hasEagerState,eagerState:F.eagerState,next:null}),ce===Zs&&(ne=!0);else if((Ia&G)===G){F=F.next,G===Zs&&(ne=!0);continue}else ce={lane:0,revertLane:F.revertLane,gesture:null,action:F.action,hasEagerState:F.hasEagerState,eagerState:F.eagerState,next:null},M===null?(_=M=ce,x=m):M=M.next=ce,Fe.lanes|=G,_r|=G;ce=F.action,us&&o(m,ce),m=F.hasEagerState?F.eagerState:o(m,ce)}else G={lane:ce,revertLane:F.revertLane,gesture:F.gesture,action:F.action,hasEagerState:F.hasEagerState,eagerState:F.eagerState,next:null},M===null?(_=M=G,x=m):M=M.next=G,Fe.lanes|=ce,_r|=ce;F=F.next}while(F!==null&&F!==a);if(M===null?x=m:M.next=_,!jn(m,e.memoizedState)&&(Bt=!0,ne&&(o=Xs,o!==null)))throw o;e.memoizedState=m,e.baseState=x,e.baseQueue=M,l.lastRenderedState=m}return d===null&&(l.lanes=0),[e.memoizedState,l.dispatch]}function Xd(e){var a=Mt(),o=a.queue;if(o===null)throw Error(s(311));o.lastRenderedReducer=e;var l=o.dispatch,d=o.pending,m=a.memoizedState;if(d!==null){o.pending=null;var x=d=d.next;do m=e(m,x.action),x=x.next;while(x!==d);jn(m,a.memoizedState)||(Bt=!0),a.memoizedState=m,a.baseQueue===null&&(a.baseState=m),o.lastRenderedState=m}return[m,l]}function Eg(e,a,o){var l=Fe,d=Mt(),m=nt;if(m){if(o===void 0)throw Error(s(407));o=o()}else o=a();var x=!jn((gt||d).memoizedState,o);if(x&&(d.memoizedState=o,Bt=!0),d=d.queue,Wd(Ng.bind(null,l,d,e),[e]),d.getSnapshot!==a||x||Ut!==null&&Ut.memoizedState.tag&1){if(l.flags|=2048,to(9,{destroy:void 0},Cg.bind(null,l,d,o,a),null),bt===null)throw Error(s(349));m||(Ia&127)!==0||_g(l,a,o)}return o}function _g(e,a,o){e.flags|=16384,e={getSnapshot:a,value:o},a=Fe.updateQueue,a===null?(a=$l(),Fe.updateQueue=a,a.stores=[e]):(o=a.stores,o===null?a.stores=[e]:o.push(e))}function Cg(e,a,o,l){a.value=o,a.getSnapshot=l,Ag(a)&&Rg(e)}function Ng(e,a,o){return o(function(){Ag(a)&&Rg(e)})}function Ag(e){var a=e.getSnapshot;e=e.value;try{var o=a();return!jn(e,o)}catch{return!0}}function Rg(e){var a=ts(e,2);a!==null&&Cn(a,e,2)}function Kd(e){var a=mn();if(typeof e=="function"){var o=e;if(e=o(),us){fn(!0);try{o()}finally{fn(!1)}}}return a.memoizedState=a.baseState=e,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:qa,lastRenderedState:e},a}function Tg(e,a,o,l){return e.baseState=o,Zd(e,gt,typeof l=="function"?l:qa)}function WE(e,a,o,l,d){if(Kl(e))throw Error(s(485));if(e=a.action,e!==null){var m={payload:d,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(x){m.listeners.push(x)}};j.T!==null?o(!0):m.isTransition=!1,l(m),o=a.pending,o===null?(m.next=a.pending=m,jg(a,m)):(m.next=o.next,a.pending=o.next=m)}}function jg(e,a){var o=a.action,l=a.payload,d=e.state;if(a.isTransition){var m=j.T,x={};j.T=x;try{var _=o(d,l),M=j.S;M!==null&&M(x,_),Og(e,a,_)}catch(F){Qd(e,a,F)}finally{m!==null&&x.types!==null&&(m.types=x.types),j.T=m}}else try{m=o(d,l),Og(e,a,m)}catch(F){Qd(e,a,F)}}function Og(e,a,o){o!==null&&typeof o=="object"&&typeof o.then=="function"?o.then(function(l){kg(e,a,l)},function(l){return Qd(e,a,l)}):kg(e,a,o)}function kg(e,a,o){a.status="fulfilled",a.value=o,Mg(a),e.state=o,a=e.pending,a!==null&&(o=a.next,o===a?e.pending=null:(o=o.next,a.next=o,jg(e,o)))}function Qd(e,a,o){var l=e.pending;if(e.pending=null,l!==null){l=l.next;do a.status="rejected",a.reason=o,Mg(a),a=a.next;while(a!==l)}e.action=null}function Mg(e){e=e.listeners;for(var a=0;a<e.length;a++)(0,e[a])()}function Dg(e,a){return a}function zg(e,a){if(nt){var o=bt.formState;if(o!==null){e:{var l=Fe;if(nt){if(wt){t:{for(var d=wt,m=Qn;d.nodeType!==8;){if(!m){d=null;break t}if(d=Jn(d.nextSibling),d===null){d=null;break t}}m=d.data,d=m==="F!"||m==="F"?d:null}if(d){wt=Jn(d.nextSibling),l=d.data==="F!";break e}}pr(l)}l=!1}l&&(a=o[0])}}return o=mn(),o.memoizedState=o.baseState=a,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Dg,lastRenderedState:a},o.queue=l,o=ey.bind(null,Fe,l),l.dispatch=o,l=Kd(!1),m=af.bind(null,Fe,!1,l.queue),l=mn(),d={state:a,dispatch:null,action:e,pending:null},l.queue=d,o=WE.bind(null,Fe,d,m,o),d.dispatch=o,l.memoizedState=e,[a,o,!1]}function Lg(e){var a=Mt();return Ug(a,gt,e)}function Ug(e,a,o){if(a=Zd(e,a,Dg)[0],e=Yl(qa)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var l=yi(a)}catch(x){throw x===Ks?Ul:x}else l=a;a=Mt();var d=a.queue,m=d.dispatch;return o!==a.memoizedState&&(Fe.flags|=2048,to(9,{destroy:void 0},JE.bind(null,d,o),null)),[l,m,e]}function JE(e,a){e.action=a}function Bg(e){var a=Mt(),o=gt;if(o!==null)return Ug(a,o,e);Mt(),a=a.memoizedState,o=Mt();var l=o.queue.dispatch;return o.memoizedState=e,[a,l,!1]}function to(e,a,o,l){return e={tag:e,create:o,deps:l,inst:a,next:null},a=Fe.updateQueue,a===null&&(a=$l(),Fe.updateQueue=a),o=a.lastEffect,o===null?a.lastEffect=e.next=e:(l=o.next,o.next=e,e.next=l,a.lastEffect=e),e}function Pg(){return Mt().memoizedState}function Zl(e,a,o,l){var d=mn();Fe.flags|=e,d.memoizedState=to(1|a,{destroy:void 0},o,l===void 0?null:l)}function Xl(e,a,o,l){var d=Mt();l=l===void 0?null:l;var m=d.memoizedState.inst;gt!==null&&l!==null&&Id(l,gt.memoizedState.deps)?d.memoizedState=to(a,m,o,l):(Fe.flags|=e,d.memoizedState=to(1|a,m,o,l))}function Hg(e,a){Zl(8390656,8,e,a)}function Wd(e,a){Xl(2048,8,e,a)}function e_(e){Fe.flags|=4;var a=Fe.updateQueue;if(a===null)a=$l(),Fe.updateQueue=a,a.events=[e];else{var o=a.events;o===null?a.events=[e]:o.push(e)}}function Vg(e){var a=Mt().memoizedState;return e_({ref:a,nextImpl:e}),function(){if((dt&2)!==0)throw Error(s(440));return a.impl.apply(void 0,arguments)}}function Ig(e,a){return Xl(4,2,e,a)}function qg(e,a){return Xl(4,4,e,a)}function Fg(e,a){if(typeof a=="function"){e=e();var o=a(e);return function(){typeof o=="function"?o():a(null)}}if(a!=null)return e=e(),a.current=e,function(){a.current=null}}function $g(e,a,o){o=o!=null?o.concat([e]):null,Xl(4,4,Fg.bind(null,a,e),o)}function Jd(){}function Gg(e,a){var o=Mt();a=a===void 0?null:a;var l=o.memoizedState;return a!==null&&Id(a,l[1])?l[0]:(o.memoizedState=[e,a],e)}function Yg(e,a){var o=Mt();a=a===void 0?null:a;var l=o.memoizedState;if(a!==null&&Id(a,l[1]))return l[0];if(l=e(),us){fn(!0);try{e()}finally{fn(!1)}}return o.memoizedState=[l,a],l}function ef(e,a,o){return o===void 0||(Ia&1073741824)!==0&&(et&261930)===0?e.memoizedState=a:(e.memoizedState=o,e=Zy(),Fe.lanes|=e,_r|=e,o)}function Zg(e,a,o,l){return jn(o,a)?o:Ws.current!==null?(e=ef(e,o,l),jn(e,a)||(Bt=!0),e):(Ia&42)===0||(Ia&1073741824)!==0&&(et&261930)===0?(Bt=!0,e.memoizedState=o):(e=Zy(),Fe.lanes|=e,_r|=e,a)}function Xg(e,a,o,l,d){var m=Z.p;Z.p=m!==0&&8>m?m:8;var x=j.T,_={};j.T=_,af(e,!1,a,o);try{var M=d(),F=j.S;if(F!==null&&F(_,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var ne=XE(M,l);vi(e,a,ne,Ln(e))}else vi(e,a,l,Ln(e))}catch(ce){vi(e,a,{then:function(){},status:"rejected",reason:ce},Ln())}finally{Z.p=m,x!==null&&_.types!==null&&(x.types=_.types),j.T=x}}function t_(){}function tf(e,a,o,l){if(e.tag!==5)throw Error(s(476));var d=Kg(e).queue;Xg(e,d,a,P,o===null?t_:function(){return Qg(e),o(l)})}function Kg(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:P,baseState:P,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qa,lastRenderedState:P},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qa,lastRenderedState:o},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function Qg(e){var a=Kg(e);a.next===null&&(a=e.alternate.memoizedState),vi(e,a.next.queue,{},Ln())}function nf(){return nn(zi)}function Wg(){return Mt().memoizedState}function Jg(){return Mt().memoizedState}function n_(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var o=Ln();e=vr(o);var l=br(a,e,o);l!==null&&(Cn(l,a,o),mi(l,a,o)),a={cache:Od()},e.payload=a;return}a=a.return}}function a_(e,a,o){var l=Ln();o={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Kl(e)?ty(a,o):(o=xd(e,a,o,l),o!==null&&(Cn(o,e,l),ny(o,a,l)))}function ey(e,a,o){var l=Ln();vi(e,a,o,l)}function vi(e,a,o,l){var d={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Kl(e))ty(a,d);else{var m=e.alternate;if(e.lanes===0&&(m===null||m.lanes===0)&&(m=a.lastRenderedReducer,m!==null))try{var x=a.lastRenderedState,_=m(x,o);if(d.hasEagerState=!0,d.eagerState=_,jn(_,x))return jl(e,a,d,0),bt===null&&Tl(),!1}catch{}finally{}if(o=xd(e,a,d,l),o!==null)return Cn(o,e,l),ny(o,a,l),!0}return!1}function af(e,a,o,l){if(l={lane:2,revertLane:Lf(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Kl(e)){if(a)throw Error(s(479))}else a=xd(e,o,l,2),a!==null&&Cn(a,e,2)}function Kl(e){var a=e.alternate;return e===Fe||a!==null&&a===Fe}function ty(e,a){Js=ql=!0;var o=e.pending;o===null?a.next=a:(a.next=o.next,o.next=a),e.pending=a}function ny(e,a,o){if((o&4194048)!==0){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,yn(e,o)}}var bi={readContext:nn,use:Gl,useCallback:Rt,useContext:Rt,useEffect:Rt,useImperativeHandle:Rt,useLayoutEffect:Rt,useInsertionEffect:Rt,useMemo:Rt,useReducer:Rt,useRef:Rt,useState:Rt,useDebugValue:Rt,useDeferredValue:Rt,useTransition:Rt,useSyncExternalStore:Rt,useId:Rt,useHostTransitionStatus:Rt,useFormState:Rt,useActionState:Rt,useOptimistic:Rt,useMemoCache:Rt,useCacheRefresh:Rt};bi.useEffectEvent=Rt;var ay={readContext:nn,use:Gl,useCallback:function(e,a){return mn().memoizedState=[e,a===void 0?null:a],e},useContext:nn,useEffect:Hg,useImperativeHandle:function(e,a,o){o=o!=null?o.concat([e]):null,Zl(4194308,4,Fg.bind(null,a,e),o)},useLayoutEffect:function(e,a){return Zl(4194308,4,e,a)},useInsertionEffect:function(e,a){Zl(4,2,e,a)},useMemo:function(e,a){var o=mn();a=a===void 0?null:a;var l=e();if(us){fn(!0);try{e()}finally{fn(!1)}}return o.memoizedState=[l,a],l},useReducer:function(e,a,o){var l=mn();if(o!==void 0){var d=o(a);if(us){fn(!0);try{o(a)}finally{fn(!1)}}}else d=a;return l.memoizedState=l.baseState=d,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:d},l.queue=e,e=e.dispatch=a_.bind(null,Fe,e),[l.memoizedState,e]},useRef:function(e){var a=mn();return e={current:e},a.memoizedState=e},useState:function(e){e=Kd(e);var a=e.queue,o=ey.bind(null,Fe,a);return a.dispatch=o,[e.memoizedState,o]},useDebugValue:Jd,useDeferredValue:function(e,a){var o=mn();return ef(o,e,a)},useTransition:function(){var e=Kd(!1);return e=Xg.bind(null,Fe,e.queue,!0,!1),mn().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,o){var l=Fe,d=mn();if(nt){if(o===void 0)throw Error(s(407));o=o()}else{if(o=a(),bt===null)throw Error(s(349));(et&127)!==0||_g(l,a,o)}d.memoizedState=o;var m={value:o,getSnapshot:a};return d.queue=m,Hg(Ng.bind(null,l,m,e),[e]),l.flags|=2048,to(9,{destroy:void 0},Cg.bind(null,l,m,o,a),null),o},useId:function(){var e=mn(),a=bt.identifierPrefix;if(nt){var o=xa,l=ba;o=(l&~(1<<32-$t(l)-1)).toString(32)+o,a="_"+a+"R_"+o,o=Fl++,0<o&&(a+="H"+o.toString(32)),a+="_"}else o=KE++,a="_"+a+"r_"+o.toString(32)+"_";return e.memoizedState=a},useHostTransitionStatus:nf,useFormState:zg,useActionState:zg,useOptimistic:function(e){var a=mn();a.memoizedState=a.baseState=e;var o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=o,a=af.bind(null,Fe,!0,o),o.dispatch=a,[e,a]},useMemoCache:Yd,useCacheRefresh:function(){return mn().memoizedState=n_.bind(null,Fe)},useEffectEvent:function(e){var a=mn(),o={impl:e};return a.memoizedState=o,function(){if((dt&2)!==0)throw Error(s(440));return o.impl.apply(void 0,arguments)}}},rf={readContext:nn,use:Gl,useCallback:Gg,useContext:nn,useEffect:Wd,useImperativeHandle:$g,useInsertionEffect:Ig,useLayoutEffect:qg,useMemo:Yg,useReducer:Yl,useRef:Pg,useState:function(){return Yl(qa)},useDebugValue:Jd,useDeferredValue:function(e,a){var o=Mt();return Zg(o,gt.memoizedState,e,a)},useTransition:function(){var e=Yl(qa)[0],a=Mt().memoizedState;return[typeof e=="boolean"?e:yi(e),a]},useSyncExternalStore:Eg,useId:Wg,useHostTransitionStatus:nf,useFormState:Lg,useActionState:Lg,useOptimistic:function(e,a){var o=Mt();return Tg(o,gt,e,a)},useMemoCache:Yd,useCacheRefresh:Jg};rf.useEffectEvent=Vg;var ry={readContext:nn,use:Gl,useCallback:Gg,useContext:nn,useEffect:Wd,useImperativeHandle:$g,useInsertionEffect:Ig,useLayoutEffect:qg,useMemo:Yg,useReducer:Xd,useRef:Pg,useState:function(){return Xd(qa)},useDebugValue:Jd,useDeferredValue:function(e,a){var o=Mt();return gt===null?ef(o,e,a):Zg(o,gt.memoizedState,e,a)},useTransition:function(){var e=Xd(qa)[0],a=Mt().memoizedState;return[typeof e=="boolean"?e:yi(e),a]},useSyncExternalStore:Eg,useId:Wg,useHostTransitionStatus:nf,useFormState:Bg,useActionState:Bg,useOptimistic:function(e,a){var o=Mt();return gt!==null?Tg(o,gt,e,a):(o.baseState=e,[e,o.queue.dispatch])},useMemoCache:Yd,useCacheRefresh:Jg};ry.useEffectEvent=Vg;function sf(e,a,o,l){a=e.memoizedState,o=o(l,a),o=o==null?a:y({},a,o),e.memoizedState=o,e.lanes===0&&(e.updateQueue.baseState=o)}var of={enqueueSetState:function(e,a,o){e=e._reactInternals;var l=Ln(),d=vr(l);d.payload=a,o!=null&&(d.callback=o),a=br(e,d,l),a!==null&&(Cn(a,e,l),mi(a,e,l))},enqueueReplaceState:function(e,a,o){e=e._reactInternals;var l=Ln(),d=vr(l);d.tag=1,d.payload=a,o!=null&&(d.callback=o),a=br(e,d,l),a!==null&&(Cn(a,e,l),mi(a,e,l))},enqueueForceUpdate:function(e,a){e=e._reactInternals;var o=Ln(),l=vr(o);l.tag=2,a!=null&&(l.callback=a),a=br(e,l,o),a!==null&&(Cn(a,e,o),mi(a,e,o))}};function sy(e,a,o,l,d,m,x){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(l,m,x):a.prototype&&a.prototype.isPureReactComponent?!si(o,l)||!si(d,m):!0}function oy(e,a,o,l){e=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(o,l),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(o,l),a.state!==e&&of.enqueueReplaceState(a,a.state,null)}function ds(e,a){var o=a;if("ref"in a){o={};for(var l in a)l!=="ref"&&(o[l]=a[l])}if(e=e.defaultProps){o===a&&(o=y({},o));for(var d in e)o[d]===void 0&&(o[d]=e[d])}return o}function iy(e){Rl(e)}function ly(e){console.error(e)}function cy(e){Rl(e)}function Ql(e,a){try{var o=e.onUncaughtError;o(a.value,{componentStack:a.stack})}catch(l){setTimeout(function(){throw l})}}function uy(e,a,o){try{var l=e.onCaughtError;l(o.value,{componentStack:o.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(d){setTimeout(function(){throw d})}}function lf(e,a,o){return o=vr(o),o.tag=3,o.payload={element:null},o.callback=function(){Ql(e,a)},o}function dy(e){return e=vr(e),e.tag=3,e}function fy(e,a,o,l){var d=o.type.getDerivedStateFromError;if(typeof d=="function"){var m=l.value;e.payload=function(){return d(m)},e.callback=function(){uy(a,o,l)}}var x=o.stateNode;x!==null&&typeof x.componentDidCatch=="function"&&(e.callback=function(){uy(a,o,l),typeof d!="function"&&(Cr===null?Cr=new Set([this]):Cr.add(this));var _=l.stack;this.componentDidCatch(l.value,{componentStack:_!==null?_:""})})}function r_(e,a,o,l,d){if(o.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){if(a=o.alternate,a!==null&&Ys(a,o,d,!0),o=kn.current,o!==null){switch(o.tag){case 31:case 13:return Wn===null?cc():o.alternate===null&&Tt===0&&(Tt=3),o.flags&=-257,o.flags|=65536,o.lanes=d,l===Bl?o.flags|=16384:(a=o.updateQueue,a===null?o.updateQueue=new Set([l]):a.add(l),Mf(e,l,d)),!1;case 22:return o.flags|=65536,l===Bl?o.flags|=16384:(a=o.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([l])},o.updateQueue=a):(o=a.retryQueue,o===null?a.retryQueue=new Set([l]):o.add(l)),Mf(e,l,d)),!1}throw Error(s(435,o.tag))}return Mf(e,l,d),cc(),!1}if(nt)return a=kn.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=d,l!==Nd&&(e=Error(s(422),{cause:l}),li(Zn(e,o)))):(l!==Nd&&(a=Error(s(423),{cause:l}),li(Zn(a,o))),e=e.current.alternate,e.flags|=65536,d&=-d,e.lanes|=d,l=Zn(l,o),d=lf(e.stateNode,l,d),Ud(e,d),Tt!==4&&(Tt=2)),!1;var m=Error(s(520),{cause:l});if(m=Zn(m,o),Ai===null?Ai=[m]:Ai.push(m),Tt!==4&&(Tt=2),a===null)return!0;l=Zn(l,o),o=a;do{switch(o.tag){case 3:return o.flags|=65536,e=d&-d,o.lanes|=e,e=lf(o.stateNode,l,e),Ud(o,e),!1;case 1:if(a=o.type,m=o.stateNode,(o.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||m!==null&&typeof m.componentDidCatch=="function"&&(Cr===null||!Cr.has(m))))return o.flags|=65536,d&=-d,o.lanes|=d,d=dy(d),fy(d,e,o,l),Ud(o,d),!1}o=o.return}while(o!==null);return!1}var cf=Error(s(461)),Bt=!1;function an(e,a,o,l){a.child=e===null?gg(a,null,o,l):cs(a,e.child,o,l)}function my(e,a,o,l,d){o=o.render;var m=a.ref;if("ref"in l){var x={};for(var _ in l)_!=="ref"&&(x[_]=l[_])}else x=l;return ss(a),l=qd(e,a,o,x,m,d),_=Fd(),e!==null&&!Bt?($d(e,a,d),Fa(e,a,d)):(nt&&_&&_d(a),a.flags|=1,an(e,a,l,d),a.child)}function hy(e,a,o,l,d){if(e===null){var m=o.type;return typeof m=="function"&&!wd(m)&&m.defaultProps===void 0&&o.compare===null?(a.tag=15,a.type=m,py(e,a,m,l,d)):(e=kl(o.type,null,l,a,a.mode,d),e.ref=a.ref,e.return=a,a.child=e)}if(m=e.child,!yf(e,d)){var x=m.memoizedProps;if(o=o.compare,o=o!==null?o:si,o(x,l)&&e.ref===a.ref)return Fa(e,a,d)}return a.flags|=1,e=Ba(m,l),e.ref=a.ref,e.return=a,a.child=e}function py(e,a,o,l,d){if(e!==null){var m=e.memoizedProps;if(si(m,l)&&e.ref===a.ref)if(Bt=!1,a.pendingProps=l=m,yf(e,d))(e.flags&131072)!==0&&(Bt=!0);else return a.lanes=e.lanes,Fa(e,a,d)}return uf(e,a,o,l,d)}function gy(e,a,o,l){var d=l.children,m=e!==null?e.memoizedState:null;if(e===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),l.mode==="hidden"){if((a.flags&128)!==0){if(m=m!==null?m.baseLanes|o:o,e!==null){for(l=a.child=e.child,d=0;l!==null;)d=d|l.lanes|l.childLanes,l=l.sibling;l=d&~m}else l=0,a.child=null;return yy(e,a,m,o,l)}if((o&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},e!==null&&Ll(a,m!==null?m.cachePool:null),m!==null?bg(a,m):Pd(),xg(a);else return l=a.lanes=536870912,yy(e,a,m!==null?m.baseLanes|o:o,o,l)}else m!==null?(Ll(a,m.cachePool),bg(a,m),wr(),a.memoizedState=null):(e!==null&&Ll(a,null),Pd(),wr());return an(e,a,d,o),a.child}function xi(e,a){return e!==null&&e.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function yy(e,a,o,l,d){var m=Md();return m=m===null?null:{parent:Lt._currentValue,pool:m},a.memoizedState={baseLanes:o,cachePool:m},e!==null&&Ll(a,null),Pd(),xg(a),e!==null&&Ys(e,a,l,!0),a.childLanes=d,null}function Wl(e,a){return a=ec({mode:a.mode,children:a.children},e.mode),a.ref=e.ref,e.child=a,a.return=e,a}function vy(e,a,o){return cs(a,e.child,null,o),e=Wl(a,a.pendingProps),e.flags|=2,Mn(a),a.memoizedState=null,e}function s_(e,a,o){var l=a.pendingProps,d=(a.flags&128)!==0;if(a.flags&=-129,e===null){if(nt){if(l.mode==="hidden")return e=Wl(a,l),a.lanes=536870912,xi(null,e);if(Vd(a),(e=wt)?(e=jv(e,Qn),e=e!==null&&e.data==="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:mr!==null?{id:ba,overflow:xa}:null,retryLane:536870912,hydrationErrors:null},o=tg(e),o.return=a,a.child=o,tn=a,wt=null)):e=null,e===null)throw pr(a);return a.lanes=536870912,null}return Wl(a,l)}var m=e.memoizedState;if(m!==null){var x=m.dehydrated;if(Vd(a),d)if(a.flags&256)a.flags&=-257,a=vy(e,a,o);else if(a.memoizedState!==null)a.child=e.child,a.flags|=128,a=null;else throw Error(s(558));else if(Bt||Ys(e,a,o,!1),d=(o&e.childLanes)!==0,Bt||d){if(l=bt,l!==null&&(x=vn(l,o),x!==0&&x!==m.retryLane))throw m.retryLane=x,ts(e,x),Cn(l,e,x),cf;cc(),a=vy(e,a,o)}else e=m.treeContext,wt=Jn(x.nextSibling),tn=a,nt=!0,hr=null,Qn=!1,e!==null&&rg(a,e),a=Wl(a,l),a.flags|=4096;return a}return e=Ba(e.child,{mode:l.mode,children:l.children}),e.ref=a.ref,a.child=e,e.return=a,e}function Jl(e,a){var o=a.ref;if(o===null)e!==null&&e.ref!==null&&(a.flags|=4194816);else{if(typeof o!="function"&&typeof o!="object")throw Error(s(284));(e===null||e.ref!==o)&&(a.flags|=4194816)}}function uf(e,a,o,l,d){return ss(a),o=qd(e,a,o,l,void 0,d),l=Fd(),e!==null&&!Bt?($d(e,a,d),Fa(e,a,d)):(nt&&l&&_d(a),a.flags|=1,an(e,a,o,d),a.child)}function by(e,a,o,l,d,m){return ss(a),a.updateQueue=null,o=Sg(a,l,o,d),wg(e),l=Fd(),e!==null&&!Bt?($d(e,a,m),Fa(e,a,m)):(nt&&l&&_d(a),a.flags|=1,an(e,a,o,m),a.child)}function xy(e,a,o,l,d){if(ss(a),a.stateNode===null){var m=qs,x=o.contextType;typeof x=="object"&&x!==null&&(m=nn(x)),m=new o(l,m),a.memoizedState=m.state!==null&&m.state!==void 0?m.state:null,m.updater=of,a.stateNode=m,m._reactInternals=a,m=a.stateNode,m.props=l,m.state=a.memoizedState,m.refs={},zd(a),x=o.contextType,m.context=typeof x=="object"&&x!==null?nn(x):qs,m.state=a.memoizedState,x=o.getDerivedStateFromProps,typeof x=="function"&&(sf(a,o,x,l),m.state=a.memoizedState),typeof o.getDerivedStateFromProps=="function"||typeof m.getSnapshotBeforeUpdate=="function"||typeof m.UNSAFE_componentWillMount!="function"&&typeof m.componentWillMount!="function"||(x=m.state,typeof m.componentWillMount=="function"&&m.componentWillMount(),typeof m.UNSAFE_componentWillMount=="function"&&m.UNSAFE_componentWillMount(),x!==m.state&&of.enqueueReplaceState(m,m.state,null),pi(a,l,m,d),hi(),m.state=a.memoizedState),typeof m.componentDidMount=="function"&&(a.flags|=4194308),l=!0}else if(e===null){m=a.stateNode;var _=a.memoizedProps,M=ds(o,_);m.props=M;var F=m.context,ne=o.contextType;x=qs,typeof ne=="object"&&ne!==null&&(x=nn(ne));var ce=o.getDerivedStateFromProps;ne=typeof ce=="function"||typeof m.getSnapshotBeforeUpdate=="function",_=a.pendingProps!==_,ne||typeof m.UNSAFE_componentWillReceiveProps!="function"&&typeof m.componentWillReceiveProps!="function"||(_||F!==x)&&oy(a,m,l,x),yr=!1;var G=a.memoizedState;m.state=G,pi(a,l,m,d),hi(),F=a.memoizedState,_||G!==F||yr?(typeof ce=="function"&&(sf(a,o,ce,l),F=a.memoizedState),(M=yr||sy(a,o,M,l,G,F,x))?(ne||typeof m.UNSAFE_componentWillMount!="function"&&typeof m.componentWillMount!="function"||(typeof m.componentWillMount=="function"&&m.componentWillMount(),typeof m.UNSAFE_componentWillMount=="function"&&m.UNSAFE_componentWillMount()),typeof m.componentDidMount=="function"&&(a.flags|=4194308)):(typeof m.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=l,a.memoizedState=F),m.props=l,m.state=F,m.context=x,l=M):(typeof m.componentDidMount=="function"&&(a.flags|=4194308),l=!1)}else{m=a.stateNode,Ld(e,a),x=a.memoizedProps,ne=ds(o,x),m.props=ne,ce=a.pendingProps,G=m.context,F=o.contextType,M=qs,typeof F=="object"&&F!==null&&(M=nn(F)),_=o.getDerivedStateFromProps,(F=typeof _=="function"||typeof m.getSnapshotBeforeUpdate=="function")||typeof m.UNSAFE_componentWillReceiveProps!="function"&&typeof m.componentWillReceiveProps!="function"||(x!==ce||G!==M)&&oy(a,m,l,M),yr=!1,G=a.memoizedState,m.state=G,pi(a,l,m,d),hi();var J=a.memoizedState;x!==ce||G!==J||yr||e!==null&&e.dependencies!==null&&Dl(e.dependencies)?(typeof _=="function"&&(sf(a,o,_,l),J=a.memoizedState),(ne=yr||sy(a,o,ne,l,G,J,M)||e!==null&&e.dependencies!==null&&Dl(e.dependencies))?(F||typeof m.UNSAFE_componentWillUpdate!="function"&&typeof m.componentWillUpdate!="function"||(typeof m.componentWillUpdate=="function"&&m.componentWillUpdate(l,J,M),typeof m.UNSAFE_componentWillUpdate=="function"&&m.UNSAFE_componentWillUpdate(l,J,M)),typeof m.componentDidUpdate=="function"&&(a.flags|=4),typeof m.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof m.componentDidUpdate!="function"||x===e.memoizedProps&&G===e.memoizedState||(a.flags|=4),typeof m.getSnapshotBeforeUpdate!="function"||x===e.memoizedProps&&G===e.memoizedState||(a.flags|=1024),a.memoizedProps=l,a.memoizedState=J),m.props=l,m.state=J,m.context=M,l=ne):(typeof m.componentDidUpdate!="function"||x===e.memoizedProps&&G===e.memoizedState||(a.flags|=4),typeof m.getSnapshotBeforeUpdate!="function"||x===e.memoizedProps&&G===e.memoizedState||(a.flags|=1024),l=!1)}return m=l,Jl(e,a),l=(a.flags&128)!==0,m||l?(m=a.stateNode,o=l&&typeof o.getDerivedStateFromError!="function"?null:m.render(),a.flags|=1,e!==null&&l?(a.child=cs(a,e.child,null,d),a.child=cs(a,null,o,d)):an(e,a,o,d),a.memoizedState=m.state,e=a.child):e=Fa(e,a,d),e}function wy(e,a,o,l){return as(),a.flags|=256,an(e,a,o,l),a.child}var df={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function ff(e){return{baseLanes:e,cachePool:ug()}}function mf(e,a,o){return e=e!==null?e.childLanes&~o:0,a&&(e|=zn),e}function Sy(e,a,o){var l=a.pendingProps,d=!1,m=(a.flags&128)!==0,x;if((x=m)||(x=e!==null&&e.memoizedState===null?!1:(kt.current&2)!==0),x&&(d=!0,a.flags&=-129),x=(a.flags&32)!==0,a.flags&=-33,e===null){if(nt){if(d?xr(a):wr(),(e=wt)?(e=jv(e,Qn),e=e!==null&&e.data!=="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:mr!==null?{id:ba,overflow:xa}:null,retryLane:536870912,hydrationErrors:null},o=tg(e),o.return=a,a.child=o,tn=a,wt=null)):e=null,e===null)throw pr(a);return Xf(e)?a.lanes=32:a.lanes=536870912,null}var _=l.children;return l=l.fallback,d?(wr(),d=a.mode,_=ec({mode:"hidden",children:_},d),l=ns(l,d,o,null),_.return=a,l.return=a,_.sibling=l,a.child=_,l=a.child,l.memoizedState=ff(o),l.childLanes=mf(e,x,o),a.memoizedState=df,xi(null,l)):(xr(a),hf(a,_))}var M=e.memoizedState;if(M!==null&&(_=M.dehydrated,_!==null)){if(m)a.flags&256?(xr(a),a.flags&=-257,a=pf(e,a,o)):a.memoizedState!==null?(wr(),a.child=e.child,a.flags|=128,a=null):(wr(),_=l.fallback,d=a.mode,l=ec({mode:"visible",children:l.children},d),_=ns(_,d,o,null),_.flags|=2,l.return=a,_.return=a,l.sibling=_,a.child=l,cs(a,e.child,null,o),l=a.child,l.memoizedState=ff(o),l.childLanes=mf(e,x,o),a.memoizedState=df,a=xi(null,l));else if(xr(a),Xf(_)){if(x=_.nextSibling&&_.nextSibling.dataset,x)var F=x.dgst;x=F,l=Error(s(419)),l.stack="",l.digest=x,li({value:l,source:null,stack:null}),a=pf(e,a,o)}else if(Bt||Ys(e,a,o,!1),x=(o&e.childLanes)!==0,Bt||x){if(x=bt,x!==null&&(l=vn(x,o),l!==0&&l!==M.retryLane))throw M.retryLane=l,ts(e,l),Cn(x,e,l),cf;Zf(_)||cc(),a=pf(e,a,o)}else Zf(_)?(a.flags|=192,a.child=e.child,a=null):(e=M.treeContext,wt=Jn(_.nextSibling),tn=a,nt=!0,hr=null,Qn=!1,e!==null&&rg(a,e),a=hf(a,l.children),a.flags|=4096);return a}return d?(wr(),_=l.fallback,d=a.mode,M=e.child,F=M.sibling,l=Ba(M,{mode:"hidden",children:l.children}),l.subtreeFlags=M.subtreeFlags&65011712,F!==null?_=Ba(F,_):(_=ns(_,d,o,null),_.flags|=2),_.return=a,l.return=a,l.sibling=_,a.child=l,xi(null,l),l=a.child,_=e.child.memoizedState,_===null?_=ff(o):(d=_.cachePool,d!==null?(M=Lt._currentValue,d=d.parent!==M?{parent:M,pool:M}:d):d=ug(),_={baseLanes:_.baseLanes|o,cachePool:d}),l.memoizedState=_,l.childLanes=mf(e,x,o),a.memoizedState=df,xi(e.child,l)):(xr(a),o=e.child,e=o.sibling,o=Ba(o,{mode:"visible",children:l.children}),o.return=a,o.sibling=null,e!==null&&(x=a.deletions,x===null?(a.deletions=[e],a.flags|=16):x.push(e)),a.child=o,a.memoizedState=null,o)}function hf(e,a){return a=ec({mode:"visible",children:a},e.mode),a.return=e,e.child=a}function ec(e,a){return e=On(22,e,null,a),e.lanes=0,e}function pf(e,a,o){return cs(a,e.child,null,o),e=hf(a,a.pendingProps.children),e.flags|=2,a.memoizedState=null,e}function Ey(e,a,o){e.lanes|=a;var l=e.alternate;l!==null&&(l.lanes|=a),Td(e.return,a,o)}function gf(e,a,o,l,d,m){var x=e.memoizedState;x===null?e.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:l,tail:o,tailMode:d,treeForkCount:m}:(x.isBackwards=a,x.rendering=null,x.renderingStartTime=0,x.last=l,x.tail=o,x.tailMode=d,x.treeForkCount=m)}function _y(e,a,o){var l=a.pendingProps,d=l.revealOrder,m=l.tail;l=l.children;var x=kt.current,_=(x&2)!==0;if(_?(x=x&1|2,a.flags|=128):x&=1,D(kt,x),an(e,a,l,o),l=nt?ii:0,!_&&e!==null&&(e.flags&128)!==0)e:for(e=a.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Ey(e,o,a);else if(e.tag===19)Ey(e,o,a);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===a)break e;for(;e.sibling===null;){if(e.return===null||e.return===a)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(d){case"forwards":for(o=a.child,d=null;o!==null;)e=o.alternate,e!==null&&Il(e)===null&&(d=o),o=o.sibling;o=d,o===null?(d=a.child,a.child=null):(d=o.sibling,o.sibling=null),gf(a,!1,d,o,m,l);break;case"backwards":case"unstable_legacy-backwards":for(o=null,d=a.child,a.child=null;d!==null;){if(e=d.alternate,e!==null&&Il(e)===null){a.child=d;break}e=d.sibling,d.sibling=o,o=d,d=e}gf(a,!0,o,null,m,l);break;case"together":gf(a,!1,null,null,void 0,l);break;default:a.memoizedState=null}return a.child}function Fa(e,a,o){if(e!==null&&(a.dependencies=e.dependencies),_r|=a.lanes,(o&a.childLanes)===0)if(e!==null){if(Ys(e,a,o,!1),(o&a.childLanes)===0)return null}else return null;if(e!==null&&a.child!==e.child)throw Error(s(153));if(a.child!==null){for(e=a.child,o=Ba(e,e.pendingProps),a.child=o,o.return=a;e.sibling!==null;)e=e.sibling,o=o.sibling=Ba(e,e.pendingProps),o.return=a;o.sibling=null}return a.child}function yf(e,a){return(e.lanes&a)!==0?!0:(e=e.dependencies,!!(e!==null&&Dl(e)))}function o_(e,a,o){switch(a.tag){case 3:K(a,a.stateNode.containerInfo),gr(a,Lt,e.memoizedState.cache),as();break;case 27:case 5:_e(a);break;case 4:K(a,a.stateNode.containerInfo);break;case 10:gr(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,Vd(a),null;break;case 13:var l=a.memoizedState;if(l!==null)return l.dehydrated!==null?(xr(a),a.flags|=128,null):(o&a.child.childLanes)!==0?Sy(e,a,o):(xr(a),e=Fa(e,a,o),e!==null?e.sibling:null);xr(a);break;case 19:var d=(e.flags&128)!==0;if(l=(o&a.childLanes)!==0,l||(Ys(e,a,o,!1),l=(o&a.childLanes)!==0),d){if(l)return _y(e,a,o);a.flags|=128}if(d=a.memoizedState,d!==null&&(d.rendering=null,d.tail=null,d.lastEffect=null),D(kt,kt.current),l)break;return null;case 22:return a.lanes=0,gy(e,a,o,a.pendingProps);case 24:gr(a,Lt,e.memoizedState.cache)}return Fa(e,a,o)}function Cy(e,a,o){if(e!==null)if(e.memoizedProps!==a.pendingProps)Bt=!0;else{if(!yf(e,o)&&(a.flags&128)===0)return Bt=!1,o_(e,a,o);Bt=(e.flags&131072)!==0}else Bt=!1,nt&&(a.flags&1048576)!==0&&ag(a,ii,a.index);switch(a.lanes=0,a.tag){case 16:e:{var l=a.pendingProps;if(e=is(a.elementType),a.type=e,typeof e=="function")wd(e)?(l=ds(e,l),a.tag=1,a=xy(null,a,e,l,o)):(a.tag=0,a=uf(null,a,e,l,o));else{if(e!=null){var d=e.$$typeof;if(d===L){a.tag=11,a=my(null,a,e,l,o);break e}else if(d===U){a.tag=14,a=hy(null,a,e,l,o);break e}}throw a=he(e)||e,Error(s(306,a,""))}}return a;case 0:return uf(e,a,a.type,a.pendingProps,o);case 1:return l=a.type,d=ds(l,a.pendingProps),xy(e,a,l,d,o);case 3:e:{if(K(a,a.stateNode.containerInfo),e===null)throw Error(s(387));l=a.pendingProps;var m=a.memoizedState;d=m.element,Ld(e,a),pi(a,l,null,o);var x=a.memoizedState;if(l=x.cache,gr(a,Lt,l),l!==m.cache&&jd(a,[Lt],o,!0),hi(),l=x.element,m.isDehydrated)if(m={element:l,isDehydrated:!1,cache:x.cache},a.updateQueue.baseState=m,a.memoizedState=m,a.flags&256){a=wy(e,a,l,o);break e}else if(l!==d){d=Zn(Error(s(424)),a),li(d),a=wy(e,a,l,o);break e}else{switch(e=a.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName==="HTML"?e.ownerDocument.body:e}for(wt=Jn(e.firstChild),tn=a,nt=!0,hr=null,Qn=!0,o=gg(a,null,l,o),a.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling}else{if(as(),l===d){a=Fa(e,a,o);break e}an(e,a,l,o)}a=a.child}return a;case 26:return Jl(e,a),e===null?(o=Lv(a.type,null,a.pendingProps,null))?a.memoizedState=o:nt||(o=a.type,e=a.pendingProps,l=gc(fe.current).createElement(o),l[en]=a,l[bn]=e,rn(l,o,e),Qt(l),a.stateNode=l):a.memoizedState=Lv(a.type,e.memoizedProps,a.pendingProps,e.memoizedState),null;case 27:return _e(a),e===null&&nt&&(l=a.stateNode=Mv(a.type,a.pendingProps,fe.current),tn=a,Qn=!0,d=wt,Tr(a.type)?(Kf=d,wt=Jn(l.firstChild)):wt=d),an(e,a,a.pendingProps.children,o),Jl(e,a),e===null&&(a.flags|=4194304),a.child;case 5:return e===null&&nt&&((d=l=wt)&&(l=L_(l,a.type,a.pendingProps,Qn),l!==null?(a.stateNode=l,tn=a,wt=Jn(l.firstChild),Qn=!1,d=!0):d=!1),d||pr(a)),_e(a),d=a.type,m=a.pendingProps,x=e!==null?e.memoizedProps:null,l=m.children,$f(d,m)?l=null:x!==null&&$f(d,x)&&(a.flags|=32),a.memoizedState!==null&&(d=qd(e,a,QE,null,null,o),zi._currentValue=d),Jl(e,a),an(e,a,l,o),a.child;case 6:return e===null&&nt&&((e=o=wt)&&(o=U_(o,a.pendingProps,Qn),o!==null?(a.stateNode=o,tn=a,wt=null,e=!0):e=!1),e||pr(a)),null;case 13:return Sy(e,a,o);case 4:return K(a,a.stateNode.containerInfo),l=a.pendingProps,e===null?a.child=cs(a,null,l,o):an(e,a,l,o),a.child;case 11:return my(e,a,a.type,a.pendingProps,o);case 7:return an(e,a,a.pendingProps,o),a.child;case 8:return an(e,a,a.pendingProps.children,o),a.child;case 12:return an(e,a,a.pendingProps.children,o),a.child;case 10:return l=a.pendingProps,gr(a,a.type,l.value),an(e,a,l.children,o),a.child;case 9:return d=a.type._context,l=a.pendingProps.children,ss(a),d=nn(d),l=l(d),a.flags|=1,an(e,a,l,o),a.child;case 14:return hy(e,a,a.type,a.pendingProps,o);case 15:return py(e,a,a.type,a.pendingProps,o);case 19:return _y(e,a,o);case 31:return s_(e,a,o);case 22:return gy(e,a,o,a.pendingProps);case 24:return ss(a),l=nn(Lt),e===null?(d=Md(),d===null&&(d=bt,m=Od(),d.pooledCache=m,m.refCount++,m!==null&&(d.pooledCacheLanes|=o),d=m),a.memoizedState={parent:l,cache:d},zd(a),gr(a,Lt,d)):((e.lanes&o)!==0&&(Ld(e,a),pi(a,null,null,o),hi()),d=e.memoizedState,m=a.memoizedState,d.parent!==l?(d={parent:l,cache:l},a.memoizedState=d,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=d),gr(a,Lt,l)):(l=m.cache,gr(a,Lt,l),l!==d.cache&&jd(a,[Lt],o,!0))),an(e,a,a.pendingProps.children,o),a.child;case 29:throw a.pendingProps}throw Error(s(156,a.tag))}function $a(e){e.flags|=4}function vf(e,a,o,l,d){if((a=(e.mode&32)!==0)&&(a=!1),a){if(e.flags|=16777216,(d&335544128)===d)if(e.stateNode.complete)e.flags|=8192;else if(Wy())e.flags|=8192;else throw ls=Bl,Dd}else e.flags&=-16777217}function Ny(e,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Vv(a))if(Wy())e.flags|=8192;else throw ls=Bl,Dd}function tc(e,a){a!==null&&(e.flags|=4),e.flags&16384&&(a=e.tag!==22?ln():536870912,e.lanes|=a,so|=a)}function wi(e,a){if(!nt)switch(e.tailMode){case"hidden":a=e.tail;for(var o=null;a!==null;)a.alternate!==null&&(o=a),a=a.sibling;o===null?e.tail=null:o.sibling=null;break;case"collapsed":o=e.tail;for(var l=null;o!==null;)o.alternate!==null&&(l=o),o=o.sibling;l===null?a||e.tail===null?e.tail=null:e.tail.sibling=null:l.sibling=null}}function St(e){var a=e.alternate!==null&&e.alternate.child===e.child,o=0,l=0;if(a)for(var d=e.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags&65011712,l|=d.flags&65011712,d.return=e,d=d.sibling;else for(d=e.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags,l|=d.flags,d.return=e,d=d.sibling;return e.subtreeFlags|=l,e.childLanes=o,a}function i_(e,a,o){var l=a.pendingProps;switch(Cd(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return St(a),null;case 1:return St(a),null;case 3:return o=a.stateNode,l=null,e!==null&&(l=e.memoizedState.cache),a.memoizedState.cache!==l&&(a.flags|=2048),Va(Lt),de(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(e===null||e.child===null)&&(Gs(a)?$a(a):e===null||e.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Ad())),St(a),null;case 26:var d=a.type,m=a.memoizedState;return e===null?($a(a),m!==null?(St(a),Ny(a,m)):(St(a),vf(a,d,null,l,o))):m?m!==e.memoizedState?($a(a),St(a),Ny(a,m)):(St(a),a.flags&=-16777217):(e=e.memoizedProps,e!==l&&$a(a),St(a),vf(a,d,e,l,o)),null;case 27:if(rt(a),o=fe.current,d=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&$a(a);else{if(!l){if(a.stateNode===null)throw Error(s(166));return St(a),null}e=V.current,Gs(a)?sg(a):(e=Mv(d,l,o),a.stateNode=e,$a(a))}return St(a),null;case 5:if(rt(a),d=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&$a(a);else{if(!l){if(a.stateNode===null)throw Error(s(166));return St(a),null}if(m=V.current,Gs(a))sg(a);else{var x=gc(fe.current);switch(m){case 1:m=x.createElementNS("http://www.w3.org/2000/svg",d);break;case 2:m=x.createElementNS("http://www.w3.org/1998/Math/MathML",d);break;default:switch(d){case"svg":m=x.createElementNS("http://www.w3.org/2000/svg",d);break;case"math":m=x.createElementNS("http://www.w3.org/1998/Math/MathML",d);break;case"script":m=x.createElement("div"),m.innerHTML="<script><\/script>",m=m.removeChild(m.firstChild);break;case"select":m=typeof l.is=="string"?x.createElement("select",{is:l.is}):x.createElement("select"),l.multiple?m.multiple=!0:l.size&&(m.size=l.size);break;default:m=typeof l.is=="string"?x.createElement(d,{is:l.is}):x.createElement(d)}}m[en]=a,m[bn]=l;e:for(x=a.child;x!==null;){if(x.tag===5||x.tag===6)m.appendChild(x.stateNode);else if(x.tag!==4&&x.tag!==27&&x.child!==null){x.child.return=x,x=x.child;continue}if(x===a)break e;for(;x.sibling===null;){if(x.return===null||x.return===a)break e;x=x.return}x.sibling.return=x.return,x=x.sibling}a.stateNode=m;e:switch(rn(m,d,l),d){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}l&&$a(a)}}return St(a),vf(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,o),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==l&&$a(a);else{if(typeof l!="string"&&a.stateNode===null)throw Error(s(166));if(e=fe.current,Gs(a)){if(e=a.stateNode,o=a.memoizedProps,l=null,d=tn,d!==null)switch(d.tag){case 27:case 5:l=d.memoizedProps}e[en]=a,e=!!(e.nodeValue===o||l!==null&&l.suppressHydrationWarning===!0||Sv(e.nodeValue,o)),e||pr(a,!0)}else e=gc(e).createTextNode(l),e[en]=a,a.stateNode=e}return St(a),null;case 31:if(o=a.memoizedState,e===null||e.memoizedState!==null){if(l=Gs(a),o!==null){if(e===null){if(!l)throw Error(s(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[en]=a}else as(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;St(a),e=!1}else o=Ad(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=o),e=!0;if(!e)return a.flags&256?(Mn(a),a):(Mn(a),null);if((a.flags&128)!==0)throw Error(s(558))}return St(a),null;case 13:if(l=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(d=Gs(a),l!==null&&l.dehydrated!==null){if(e===null){if(!d)throw Error(s(318));if(d=a.memoizedState,d=d!==null?d.dehydrated:null,!d)throw Error(s(317));d[en]=a}else as(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;St(a),d=!1}else d=Ad(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=d),d=!0;if(!d)return a.flags&256?(Mn(a),a):(Mn(a),null)}return Mn(a),(a.flags&128)!==0?(a.lanes=o,a):(o=l!==null,e=e!==null&&e.memoizedState!==null,o&&(l=a.child,d=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(d=l.alternate.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==d&&(l.flags|=2048)),o!==e&&o&&(a.child.flags|=8192),tc(a,a.updateQueue),St(a),null);case 4:return de(),e===null&&Hf(a.stateNode.containerInfo),St(a),null;case 10:return Va(a.type),St(a),null;case 19:if(Y(kt),l=a.memoizedState,l===null)return St(a),null;if(d=(a.flags&128)!==0,m=l.rendering,m===null)if(d)wi(l,!1);else{if(Tt!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(m=Il(e),m!==null){for(a.flags|=128,wi(l,!1),e=m.updateQueue,a.updateQueue=e,tc(a,e),a.subtreeFlags=0,e=o,o=a.child;o!==null;)eg(o,e),o=o.sibling;return D(kt,kt.current&1|2),nt&&Pa(a,l.treeForkCount),a.child}e=e.sibling}l.tail!==null&&pe()>oc&&(a.flags|=128,d=!0,wi(l,!1),a.lanes=4194304)}else{if(!d)if(e=Il(m),e!==null){if(a.flags|=128,d=!0,e=e.updateQueue,a.updateQueue=e,tc(a,e),wi(l,!0),l.tail===null&&l.tailMode==="hidden"&&!m.alternate&&!nt)return St(a),null}else 2*pe()-l.renderingStartTime>oc&&o!==536870912&&(a.flags|=128,d=!0,wi(l,!1),a.lanes=4194304);l.isBackwards?(m.sibling=a.child,a.child=m):(e=l.last,e!==null?e.sibling=m:a.child=m,l.last=m)}return l.tail!==null?(e=l.tail,l.rendering=e,l.tail=e.sibling,l.renderingStartTime=pe(),e.sibling=null,o=kt.current,D(kt,d?o&1|2:o&1),nt&&Pa(a,l.treeForkCount),e):(St(a),null);case 22:case 23:return Mn(a),Hd(),l=a.memoizedState!==null,e!==null?e.memoizedState!==null!==l&&(a.flags|=8192):l&&(a.flags|=8192),l?(o&536870912)!==0&&(a.flags&128)===0&&(St(a),a.subtreeFlags&6&&(a.flags|=8192)):St(a),o=a.updateQueue,o!==null&&tc(a,o.retryQueue),o=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(o=e.memoizedState.cachePool.pool),l=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(l=a.memoizedState.cachePool.pool),l!==o&&(a.flags|=2048),e!==null&&Y(os),null;case 24:return o=null,e!==null&&(o=e.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),Va(Lt),St(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function l_(e,a){switch(Cd(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return Va(Lt),de(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return rt(a),null;case 31:if(a.memoizedState!==null){if(Mn(a),a.alternate===null)throw Error(s(340));as()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(Mn(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(s(340));as()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return Y(kt),null;case 4:return de(),null;case 10:return Va(a.type),null;case 22:case 23:return Mn(a),Hd(),e!==null&&Y(os),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return Va(Lt),null;case 25:return null;default:return null}}function Ay(e,a){switch(Cd(a),a.tag){case 3:Va(Lt),de();break;case 26:case 27:case 5:rt(a);break;case 4:de();break;case 31:a.memoizedState!==null&&Mn(a);break;case 13:Mn(a);break;case 19:Y(kt);break;case 10:Va(a.type);break;case 22:case 23:Mn(a),Hd(),e!==null&&Y(os);break;case 24:Va(Lt)}}function Si(e,a){try{var o=a.updateQueue,l=o!==null?o.lastEffect:null;if(l!==null){var d=l.next;o=d;do{if((o.tag&e)===e){l=void 0;var m=o.create,x=o.inst;l=m(),x.destroy=l}o=o.next}while(o!==d)}}catch(_){ht(a,a.return,_)}}function Sr(e,a,o){try{var l=a.updateQueue,d=l!==null?l.lastEffect:null;if(d!==null){var m=d.next;l=m;do{if((l.tag&e)===e){var x=l.inst,_=x.destroy;if(_!==void 0){x.destroy=void 0,d=a;var M=o,F=_;try{F()}catch(ne){ht(d,M,ne)}}}l=l.next}while(l!==m)}}catch(ne){ht(a,a.return,ne)}}function Ry(e){var a=e.updateQueue;if(a!==null){var o=e.stateNode;try{vg(a,o)}catch(l){ht(e,e.return,l)}}}function Ty(e,a,o){o.props=ds(e.type,e.memoizedProps),o.state=e.memoizedState;try{o.componentWillUnmount()}catch(l){ht(e,a,l)}}function Ei(e,a){try{var o=e.ref;if(o!==null){switch(e.tag){case 26:case 27:case 5:var l=e.stateNode;break;case 30:l=e.stateNode;break;default:l=e.stateNode}typeof o=="function"?e.refCleanup=o(l):o.current=l}}catch(d){ht(e,a,d)}}function wa(e,a){var o=e.ref,l=e.refCleanup;if(o!==null)if(typeof l=="function")try{l()}catch(d){ht(e,a,d)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(d){ht(e,a,d)}else o.current=null}function jy(e){var a=e.type,o=e.memoizedProps,l=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&l.focus();break e;case"img":o.src?l.src=o.src:o.srcSet&&(l.srcset=o.srcSet)}}catch(d){ht(e,e.return,d)}}function bf(e,a,o){try{var l=e.stateNode;j_(l,e.type,o,a),l[bn]=a}catch(d){ht(e,e.return,d)}}function Oy(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Tr(e.type)||e.tag===4}function xf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Oy(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.tag===27&&Tr(e.type)||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 wf(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(e,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(e),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=La));else if(l!==4&&(l===27&&Tr(e.type)&&(o=e.stateNode,a=null),e=e.child,e!==null))for(wf(e,a,o),e=e.sibling;e!==null;)wf(e,a,o),e=e.sibling}function nc(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?o.insertBefore(e,a):o.appendChild(e);else if(l!==4&&(l===27&&Tr(e.type)&&(o=e.stateNode),e=e.child,e!==null))for(nc(e,a,o),e=e.sibling;e!==null;)nc(e,a,o),e=e.sibling}function ky(e){var a=e.stateNode,o=e.memoizedProps;try{for(var l=e.type,d=a.attributes;d.length;)a.removeAttributeNode(d[0]);rn(a,l,o),a[en]=e,a[bn]=o}catch(m){ht(e,e.return,m)}}var Ga=!1,Pt=!1,Sf=!1,My=typeof WeakSet=="function"?WeakSet:Set,Wt=null;function c_(e,a){if(e=e.containerInfo,qf=Ec,e=$p(e),hd(e)){if("selectionStart"in e)var o={start:e.selectionStart,end:e.selectionEnd};else e:{o=(o=e.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,m=l.focusNode;l=l.focusOffset;try{o.nodeType,m.nodeType}catch{o=null;break e}var x=0,_=-1,M=-1,F=0,ne=0,ce=e,G=null;t:for(;;){for(var J;ce!==o||d!==0&&ce.nodeType!==3||(_=x+d),ce!==m||l!==0&&ce.nodeType!==3||(M=x+l),ce.nodeType===3&&(x+=ce.nodeValue.length),(J=ce.firstChild)!==null;)G=ce,ce=J;for(;;){if(ce===e)break t;if(G===o&&++F===d&&(_=x),G===m&&++ne===l&&(M=x),(J=ce.nextSibling)!==null)break;ce=G,G=ce.parentNode}ce=J}o=_===-1||M===-1?null:{start:_,end:M}}else o=null}o=o||{start:0,end:0}}else o=null;for(Ff={focusedElem:e,selectionRange:o},Ec=!1,Wt=a;Wt!==null;)if(a=Wt,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,Wt=e;else for(;Wt!==null;){switch(a=Wt,m=a.alternate,e=a.flags,a.tag){case 0:if((e&4)!==0&&(e=a.updateQueue,e=e!==null?e.events:null,e!==null))for(o=0;o<e.length;o++)d=e[o],d.ref.impl=d.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&m!==null){e=void 0,o=a,d=m.memoizedProps,m=m.memoizedState,l=o.stateNode;try{var Ce=ds(o.type,d);e=l.getSnapshotBeforeUpdate(Ce,m),l.__reactInternalSnapshotBeforeUpdate=e}catch(ze){ht(o,o.return,ze)}}break;case 3:if((e&1024)!==0){if(e=a.stateNode.containerInfo,o=e.nodeType,o===9)Yf(e);else if(o===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Yf(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((e&1024)!==0)throw Error(s(163))}if(e=a.sibling,e!==null){e.return=a.return,Wt=e;break}Wt=a.return}}function Dy(e,a,o){var l=o.flags;switch(o.tag){case 0:case 11:case 15:Za(e,o),l&4&&Si(5,o);break;case 1:if(Za(e,o),l&4)if(e=o.stateNode,a===null)try{e.componentDidMount()}catch(x){ht(o,o.return,x)}else{var d=ds(o.type,a.memoizedProps);a=a.memoizedState;try{e.componentDidUpdate(d,a,e.__reactInternalSnapshotBeforeUpdate)}catch(x){ht(o,o.return,x)}}l&64&&Ry(o),l&512&&Ei(o,o.return);break;case 3:if(Za(e,o),l&64&&(e=o.updateQueue,e!==null)){if(a=null,o.child!==null)switch(o.child.tag){case 27:case 5:a=o.child.stateNode;break;case 1:a=o.child.stateNode}try{vg(e,a)}catch(x){ht(o,o.return,x)}}break;case 27:a===null&&l&4&&ky(o);case 26:case 5:Za(e,o),a===null&&l&4&&jy(o),l&512&&Ei(o,o.return);break;case 12:Za(e,o);break;case 31:Za(e,o),l&4&&Uy(e,o);break;case 13:Za(e,o),l&4&&By(e,o),l&64&&(e=o.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(o=v_.bind(null,o),B_(e,o))));break;case 22:if(l=o.memoizedState!==null||Ga,!l){a=a!==null&&a.memoizedState!==null||Pt,d=Ga;var m=Pt;Ga=l,(Pt=a)&&!m?Xa(e,o,(o.subtreeFlags&8772)!==0):Za(e,o),Ga=d,Pt=m}break;case 30:break;default:Za(e,o)}}function zy(e){var a=e.alternate;a!==null&&(e.alternate=null,zy(a)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(a=e.stateNode,a!==null&&Qu(a)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var _t=null,wn=!1;function Ya(e,a,o){for(o=o.child;o!==null;)Ly(e,a,o),o=o.sibling}function Ly(e,a,o){if(Nt&&typeof Nt.onCommitFiberUnmount=="function")try{Nt.onCommitFiberUnmount(Ft,o)}catch{}switch(o.tag){case 26:Pt||wa(o,a),Ya(e,a,o),o.memoizedState?o.memoizedState.count--:o.stateNode&&(o=o.stateNode,o.parentNode.removeChild(o));break;case 27:Pt||wa(o,a);var l=_t,d=wn;Tr(o.type)&&(_t=o.stateNode,wn=!1),Ya(e,a,o),ki(o.stateNode),_t=l,wn=d;break;case 5:Pt||wa(o,a);case 6:if(l=_t,d=wn,_t=null,Ya(e,a,o),_t=l,wn=d,_t!==null)if(wn)try{(_t.nodeType===9?_t.body:_t.nodeName==="HTML"?_t.ownerDocument.body:_t).removeChild(o.stateNode)}catch(m){ht(o,a,m)}else try{_t.removeChild(o.stateNode)}catch(m){ht(o,a,m)}break;case 18:_t!==null&&(wn?(e=_t,Rv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,o.stateNode),ho(e)):Rv(_t,o.stateNode));break;case 4:l=_t,d=wn,_t=o.stateNode.containerInfo,wn=!0,Ya(e,a,o),_t=l,wn=d;break;case 0:case 11:case 14:case 15:Sr(2,o,a),Pt||Sr(4,o,a),Ya(e,a,o);break;case 1:Pt||(wa(o,a),l=o.stateNode,typeof l.componentWillUnmount=="function"&&Ty(o,a,l)),Ya(e,a,o);break;case 21:Ya(e,a,o);break;case 22:Pt=(l=Pt)||o.memoizedState!==null,Ya(e,a,o),Pt=l;break;default:Ya(e,a,o)}}function Uy(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{ho(e)}catch(o){ht(a,a.return,o)}}}function By(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{ho(e)}catch(o){ht(a,a.return,o)}}function u_(e){switch(e.tag){case 31:case 13:case 19:var a=e.stateNode;return a===null&&(a=e.stateNode=new My),a;case 22:return e=e.stateNode,a=e._retryCache,a===null&&(a=e._retryCache=new My),a;default:throw Error(s(435,e.tag))}}function ac(e,a){var o=u_(e);a.forEach(function(l){if(!o.has(l)){o.add(l);var d=b_.bind(null,e,l);l.then(d,d)}})}function Sn(e,a){var o=a.deletions;if(o!==null)for(var l=0;l<o.length;l++){var d=o[l],m=e,x=a,_=x;e:for(;_!==null;){switch(_.tag){case 27:if(Tr(_.type)){_t=_.stateNode,wn=!1;break e}break;case 5:_t=_.stateNode,wn=!1;break e;case 3:case 4:_t=_.stateNode.containerInfo,wn=!0;break e}_=_.return}if(_t===null)throw Error(s(160));Ly(m,x,d),_t=null,wn=!1,m=d.alternate,m!==null&&(m.return=null),d.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)Py(a,e),a=a.sibling}var ia=null;function Py(e,a){var o=e.alternate,l=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Sn(a,e),En(e),l&4&&(Sr(3,e,e.return),Si(3,e),Sr(5,e,e.return));break;case 1:Sn(a,e),En(e),l&512&&(Pt||o===null||wa(o,o.return)),l&64&&Ga&&(e=e.updateQueue,e!==null&&(l=e.callbacks,l!==null&&(o=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=o===null?l:o.concat(l))));break;case 26:var d=ia;if(Sn(a,e),En(e),l&512&&(Pt||o===null||wa(o,o.return)),l&4){var m=o!==null?o.memoizedState:null;if(l=e.memoizedState,o===null)if(l===null)if(e.stateNode===null){e:{l=e.type,o=e.memoizedProps,d=d.ownerDocument||d;t:switch(l){case"title":m=d.getElementsByTagName("title")[0],(!m||m[Ko]||m[en]||m.namespaceURI==="http://www.w3.org/2000/svg"||m.hasAttribute("itemprop"))&&(m=d.createElement(l),d.head.insertBefore(m,d.querySelector("head > title"))),rn(m,l,o),m[en]=e,Qt(m),l=m;break e;case"link":var x=Pv("link","href",d).get(l+(o.href||""));if(x){for(var _=0;_<x.length;_++)if(m=x[_],m.getAttribute("href")===(o.href==null||o.href===""?null:o.href)&&m.getAttribute("rel")===(o.rel==null?null:o.rel)&&m.getAttribute("title")===(o.title==null?null:o.title)&&m.getAttribute("crossorigin")===(o.crossOrigin==null?null:o.crossOrigin)){x.splice(_,1);break t}}m=d.createElement(l),rn(m,l,o),d.head.appendChild(m);break;case"meta":if(x=Pv("meta","content",d).get(l+(o.content||""))){for(_=0;_<x.length;_++)if(m=x[_],m.getAttribute("content")===(o.content==null?null:""+o.content)&&m.getAttribute("name")===(o.name==null?null:o.name)&&m.getAttribute("property")===(o.property==null?null:o.property)&&m.getAttribute("http-equiv")===(o.httpEquiv==null?null:o.httpEquiv)&&m.getAttribute("charset")===(o.charSet==null?null:o.charSet)){x.splice(_,1);break t}}m=d.createElement(l),rn(m,l,o),d.head.appendChild(m);break;default:throw Error(s(468,l))}m[en]=e,Qt(m),l=m}e.stateNode=l}else Hv(d,e.type,e.stateNode);else e.stateNode=Bv(d,l,e.memoizedProps);else m!==l?(m===null?o.stateNode!==null&&(o=o.stateNode,o.parentNode.removeChild(o)):m.count--,l===null?Hv(d,e.type,e.stateNode):Bv(d,l,e.memoizedProps)):l===null&&e.stateNode!==null&&bf(e,e.memoizedProps,o.memoizedProps)}break;case 27:Sn(a,e),En(e),l&512&&(Pt||o===null||wa(o,o.return)),o!==null&&l&4&&bf(e,e.memoizedProps,o.memoizedProps);break;case 5:if(Sn(a,e),En(e),l&512&&(Pt||o===null||wa(o,o.return)),e.flags&32){d=e.stateNode;try{Ls(d,"")}catch(Ce){ht(e,e.return,Ce)}}l&4&&e.stateNode!=null&&(d=e.memoizedProps,bf(e,d,o!==null?o.memoizedProps:d)),l&1024&&(Sf=!0);break;case 6:if(Sn(a,e),En(e),l&4){if(e.stateNode===null)throw Error(s(162));l=e.memoizedProps,o=e.stateNode;try{o.nodeValue=l}catch(Ce){ht(e,e.return,Ce)}}break;case 3:if(bc=null,d=ia,ia=yc(a.containerInfo),Sn(a,e),ia=d,En(e),l&4&&o!==null&&o.memoizedState.isDehydrated)try{ho(a.containerInfo)}catch(Ce){ht(e,e.return,Ce)}Sf&&(Sf=!1,Hy(e));break;case 4:l=ia,ia=yc(e.stateNode.containerInfo),Sn(a,e),En(e),ia=l;break;case 12:Sn(a,e),En(e);break;case 31:Sn(a,e),En(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ac(e,l)));break;case 13:Sn(a,e),En(e),e.child.flags&8192&&e.memoizedState!==null!=(o!==null&&o.memoizedState!==null)&&(sc=pe()),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ac(e,l)));break;case 22:d=e.memoizedState!==null;var M=o!==null&&o.memoizedState!==null,F=Ga,ne=Pt;if(Ga=F||d,Pt=ne||M,Sn(a,e),Pt=ne,Ga=F,En(e),l&8192)e:for(a=e.stateNode,a._visibility=d?a._visibility&-2:a._visibility|1,d&&(o===null||M||Ga||Pt||fs(e)),o=null,a=e;;){if(a.tag===5||a.tag===26){if(o===null){M=o=a;try{if(m=M.stateNode,d)x=m.style,typeof x.setProperty=="function"?x.setProperty("display","none","important"):x.display="none";else{_=M.stateNode;var ce=M.memoizedProps.style,G=ce!=null&&ce.hasOwnProperty("display")?ce.display:null;_.style.display=G==null||typeof G=="boolean"?"":(""+G).trim()}}catch(Ce){ht(M,M.return,Ce)}}}else if(a.tag===6){if(o===null){M=a;try{M.stateNode.nodeValue=d?"":M.memoizedProps}catch(Ce){ht(M,M.return,Ce)}}}else if(a.tag===18){if(o===null){M=a;try{var J=M.stateNode;d?Tv(J,!0):Tv(M.stateNode,!1)}catch(Ce){ht(M,M.return,Ce)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===e)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break e;for(;a.sibling===null;){if(a.return===null||a.return===e)break e;o===a&&(o=null),a=a.return}o===a&&(o=null),a.sibling.return=a.return,a=a.sibling}l&4&&(l=e.updateQueue,l!==null&&(o=l.retryQueue,o!==null&&(l.retryQueue=null,ac(e,o))));break;case 19:Sn(a,e),En(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,ac(e,l)));break;case 30:break;case 21:break;default:Sn(a,e),En(e)}}function En(e){var a=e.flags;if(a&2){try{for(var o,l=e.return;l!==null;){if(Oy(l)){o=l;break}l=l.return}if(o==null)throw Error(s(160));switch(o.tag){case 27:var d=o.stateNode,m=xf(e);nc(e,m,d);break;case 5:var x=o.stateNode;o.flags&32&&(Ls(x,""),o.flags&=-33);var _=xf(e);nc(e,_,x);break;case 3:case 4:var M=o.stateNode.containerInfo,F=xf(e);wf(e,F,M);break;default:throw Error(s(161))}}catch(ne){ht(e,e.return,ne)}e.flags&=-3}a&4096&&(e.flags&=-4097)}function Hy(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var a=e;Hy(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),e=e.sibling}}function Za(e,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)Dy(e,a.alternate,a),a=a.sibling}function fs(e){for(e=e.child;e!==null;){var a=e;switch(a.tag){case 0:case 11:case 14:case 15:Sr(4,a,a.return),fs(a);break;case 1:wa(a,a.return);var o=a.stateNode;typeof o.componentWillUnmount=="function"&&Ty(a,a.return,o),fs(a);break;case 27:ki(a.stateNode);case 26:case 5:wa(a,a.return),fs(a);break;case 22:a.memoizedState===null&&fs(a);break;case 30:fs(a);break;default:fs(a)}e=e.sibling}}function Xa(e,a,o){for(o=o&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var l=a.alternate,d=e,m=a,x=m.flags;switch(m.tag){case 0:case 11:case 15:Xa(d,m,o),Si(4,m);break;case 1:if(Xa(d,m,o),l=m,d=l.stateNode,typeof d.componentDidMount=="function")try{d.componentDidMount()}catch(F){ht(l,l.return,F)}if(l=m,d=l.updateQueue,d!==null){var _=l.stateNode;try{var M=d.shared.hiddenCallbacks;if(M!==null)for(d.shared.hiddenCallbacks=null,d=0;d<M.length;d++)yg(M[d],_)}catch(F){ht(l,l.return,F)}}o&&x&64&&Ry(m),Ei(m,m.return);break;case 27:ky(m);case 26:case 5:Xa(d,m,o),o&&l===null&&x&4&&jy(m),Ei(m,m.return);break;case 12:Xa(d,m,o);break;case 31:Xa(d,m,o),o&&x&4&&Uy(d,m);break;case 13:Xa(d,m,o),o&&x&4&&By(d,m);break;case 22:m.memoizedState===null&&Xa(d,m,o),Ei(m,m.return);break;case 30:break;default:Xa(d,m,o)}a=a.sibling}}function Ef(e,a){var o=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(o=e.memoizedState.cachePool.pool),e=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(e=a.memoizedState.cachePool.pool),e!==o&&(e!=null&&e.refCount++,o!=null&&ci(o))}function _f(e,a){e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ci(e))}function la(e,a,o,l){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)Vy(e,a,o,l),a=a.sibling}function Vy(e,a,o,l){var d=a.flags;switch(a.tag){case 0:case 11:case 15:la(e,a,o,l),d&2048&&Si(9,a);break;case 1:la(e,a,o,l);break;case 3:la(e,a,o,l),d&2048&&(e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ci(e)));break;case 12:if(d&2048){la(e,a,o,l),e=a.stateNode;try{var m=a.memoizedProps,x=m.id,_=m.onPostCommit;typeof _=="function"&&_(x,a.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(M){ht(a,a.return,M)}}else la(e,a,o,l);break;case 31:la(e,a,o,l);break;case 13:la(e,a,o,l);break;case 23:break;case 22:m=a.stateNode,x=a.alternate,a.memoizedState!==null?m._visibility&2?la(e,a,o,l):_i(e,a):m._visibility&2?la(e,a,o,l):(m._visibility|=2,no(e,a,o,l,(a.subtreeFlags&10256)!==0||!1)),d&2048&&Ef(x,a);break;case 24:la(e,a,o,l),d&2048&&_f(a.alternate,a);break;default:la(e,a,o,l)}}function no(e,a,o,l,d){for(d=d&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var m=e,x=a,_=o,M=l,F=x.flags;switch(x.tag){case 0:case 11:case 15:no(m,x,_,M,d),Si(8,x);break;case 23:break;case 22:var ne=x.stateNode;x.memoizedState!==null?ne._visibility&2?no(m,x,_,M,d):_i(m,x):(ne._visibility|=2,no(m,x,_,M,d)),d&&F&2048&&Ef(x.alternate,x);break;case 24:no(m,x,_,M,d),d&&F&2048&&_f(x.alternate,x);break;default:no(m,x,_,M,d)}a=a.sibling}}function _i(e,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var o=e,l=a,d=l.flags;switch(l.tag){case 22:_i(o,l),d&2048&&Ef(l.alternate,l);break;case 24:_i(o,l),d&2048&&_f(l.alternate,l);break;default:_i(o,l)}a=a.sibling}}var Ci=8192;function ao(e,a,o){if(e.subtreeFlags&Ci)for(e=e.child;e!==null;)Iy(e,a,o),e=e.sibling}function Iy(e,a,o){switch(e.tag){case 26:ao(e,a,o),e.flags&Ci&&e.memoizedState!==null&&K_(o,ia,e.memoizedState,e.memoizedProps);break;case 5:ao(e,a,o);break;case 3:case 4:var l=ia;ia=yc(e.stateNode.containerInfo),ao(e,a,o),ia=l;break;case 22:e.memoizedState===null&&(l=e.alternate,l!==null&&l.memoizedState!==null?(l=Ci,Ci=16777216,ao(e,a,o),Ci=l):ao(e,a,o));break;default:ao(e,a,o)}}function qy(e){var a=e.alternate;if(a!==null&&(e=a.child,e!==null)){a.child=null;do a=e.sibling,e.sibling=null,e=a;while(e!==null)}}function Ni(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var o=0;o<a.length;o++){var l=a[o];Wt=l,$y(l,e)}qy(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Fy(e),e=e.sibling}function Fy(e){switch(e.tag){case 0:case 11:case 15:Ni(e),e.flags&2048&&Sr(9,e,e.return);break;case 3:Ni(e);break;case 12:Ni(e);break;case 22:var a=e.stateNode;e.memoizedState!==null&&a._visibility&2&&(e.return===null||e.return.tag!==13)?(a._visibility&=-3,rc(e)):Ni(e);break;default:Ni(e)}}function rc(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var o=0;o<a.length;o++){var l=a[o];Wt=l,$y(l,e)}qy(e)}for(e=e.child;e!==null;){switch(a=e,a.tag){case 0:case 11:case 15:Sr(8,a,a.return),rc(a);break;case 22:o=a.stateNode,o._visibility&2&&(o._visibility&=-3,rc(a));break;default:rc(a)}e=e.sibling}}function $y(e,a){for(;Wt!==null;){var o=Wt;switch(o.tag){case 0:case 11:case 15:Sr(8,o,a);break;case 23:case 22:if(o.memoizedState!==null&&o.memoizedState.cachePool!==null){var l=o.memoizedState.cachePool.pool;l!=null&&l.refCount++}break;case 24:ci(o.memoizedState.cache)}if(l=o.child,l!==null)l.return=o,Wt=l;else e:for(o=e;Wt!==null;){l=Wt;var d=l.sibling,m=l.return;if(zy(l),l===o){Wt=null;break e}if(d!==null){d.return=m,Wt=d;break e}Wt=m}}}var d_={getCacheForType:function(e){var a=nn(Lt),o=a.data.get(e);return o===void 0&&(o=e(),a.data.set(e,o)),o},cacheSignal:function(){return nn(Lt).controller.signal}},f_=typeof WeakMap=="function"?WeakMap:Map,dt=0,bt=null,Ke=null,et=0,mt=0,Dn=null,Er=!1,ro=!1,Cf=!1,Ka=0,Tt=0,_r=0,ms=0,Nf=0,zn=0,so=0,Ai=null,_n=null,Af=!1,sc=0,Gy=0,oc=1/0,ic=null,Cr=null,Gt=0,Nr=null,oo=null,Qa=0,Rf=0,Tf=null,Yy=null,Ri=0,jf=null;function Ln(){return(dt&2)!==0&&et!==0?et&-et:j.T!==null?Lf():Xu()}function Zy(){if(zn===0)if((et&536870912)===0||nt){var e=Rs;Rs<<=1,(Rs&3932160)===0&&(Rs=262144),zn=e}else zn=536870912;return e=kn.current,e!==null&&(e.flags|=32),zn}function Cn(e,a,o){(e===bt&&(mt===2||mt===9)||e.cancelPendingCommit!==null)&&(io(e,0),Ar(e,et,zn,!1)),At(e,o),((dt&2)===0||e!==bt)&&(e===bt&&((dt&2)===0&&(ms|=o),Tt===4&&Ar(e,et,zn,!1)),Sa(e))}function Xy(e,a,o){if((dt&6)!==0)throw Error(s(327));var l=!o&&(a&127)===0&&(a&e.expiredLanes)===0||Et(e,a),d=l?p_(e,a):kf(e,a,!0),m=l;do{if(d===0){ro&&!l&&Ar(e,a,0,!1);break}else{if(o=e.current.alternate,m&&!m_(o)){d=kf(e,a,!1),m=!1;continue}if(d===2){if(m=a,e.errorRecoveryDisabledLanes&m)var x=0;else x=e.pendingLanes&-536870913,x=x!==0?x:x&536870912?536870912:0;if(x!==0){a=x;e:{var _=e;d=Ai;var M=_.current.memoizedState.isDehydrated;if(M&&(io(_,x).flags|=256),x=kf(_,x,!1),x!==2){if(Cf&&!M){_.errorRecoveryDisabledLanes|=m,ms|=m,d=4;break e}m=_n,_n=d,m!==null&&(_n===null?_n=m:_n.push.apply(_n,m))}d=x}if(m=!1,d!==2)continue}}if(d===1){io(e,0),Ar(e,a,0,!0);break}e:{switch(l=e,m=d,m){case 0:case 1:throw Error(s(345));case 4:if((a&4194048)!==a)break;case 6:Ar(l,a,zn,!Er);break e;case 2:_n=null;break;case 3:case 5:break;default:throw Error(s(329))}if((a&62914560)===a&&(d=sc+300-pe(),10<d)){if(Ar(l,a,zn,!Er),Be(l,0,!0)!==0)break e;Qa=a,l.timeoutHandle=Nv(Ky.bind(null,l,o,_n,ic,Af,a,zn,ms,so,Er,m,"Throttled",-0,0),d);break e}Ky(l,o,_n,ic,Af,a,zn,ms,so,Er,m,null,-0,0)}}break}while(!0);Sa(e)}function Ky(e,a,o,l,d,m,x,_,M,F,ne,ce,G,J){if(e.timeoutHandle=-1,ce=a.subtreeFlags,ce&8192||(ce&16785408)===16785408){ce={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:La},Iy(a,m,ce);var Ce=(m&62914560)===m?sc-pe():(m&4194048)===m?Gy-pe():0;if(Ce=Q_(ce,Ce),Ce!==null){Qa=m,e.cancelPendingCommit=Ce(rv.bind(null,e,a,m,o,l,d,x,_,M,ne,ce,null,G,J)),Ar(e,m,x,!F);return}}rv(e,a,m,o,l,d,x,_,M)}function m_(e){for(var a=e;;){var o=a.tag;if((o===0||o===11||o===15)&&a.flags&16384&&(o=a.updateQueue,o!==null&&(o=o.stores,o!==null)))for(var l=0;l<o.length;l++){var d=o[l],m=d.getSnapshot;d=d.value;try{if(!jn(m(),d))return!1}catch{return!1}}if(o=a.child,a.subtreeFlags&16384&&o!==null)o.return=a,a=o;else{if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Ar(e,a,o,l){a&=~Nf,a&=~ms,e.suspendedLanes|=a,e.pingedLanes&=~a,l&&(e.warmLanes|=a),l=e.expirationTimes;for(var d=a;0<d;){var m=31-$t(d),x=1<<m;l[m]=-1,d&=~x}o!==0&&Kr(e,o,a)}function lc(){return(dt&6)===0?(Ti(0),!1):!0}function Of(){if(Ke!==null){if(mt===0)var e=Ke.return;else e=Ke,Ha=rs=null,Gd(e),Qs=null,di=0,e=Ke;for(;e!==null;)Ay(e.alternate,e),e=e.return;Ke=null}}function io(e,a){var o=e.timeoutHandle;o!==-1&&(e.timeoutHandle=-1,M_(o)),o=e.cancelPendingCommit,o!==null&&(e.cancelPendingCommit=null,o()),Qa=0,Of(),bt=e,Ke=o=Ba(e.current,null),et=a,mt=0,Dn=null,Er=!1,ro=Et(e,a),Cf=!1,so=zn=Nf=ms=_r=Tt=0,_n=Ai=null,Af=!1,(a&8)!==0&&(a|=a&32);var l=e.entangledLanes;if(l!==0)for(e=e.entanglements,l&=a;0<l;){var d=31-$t(l),m=1<<d;a|=e[d],l&=~m}return Ka=a,Tl(),o}function Qy(e,a){Fe=null,j.H=bi,a===Ks||a===Ul?(a=mg(),mt=3):a===Dd?(a=mg(),mt=4):mt=a===cf?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,Dn=a,Ke===null&&(Tt=1,Ql(e,Zn(a,e.current)))}function Wy(){var e=kn.current;return e===null?!0:(et&4194048)===et?Wn===null:(et&62914560)===et||(et&536870912)!==0?e===Wn:!1}function Jy(){var e=j.H;return j.H=bi,e===null?bi:e}function ev(){var e=j.A;return j.A=d_,e}function cc(){Tt=4,Er||(et&4194048)!==et&&kn.current!==null||(ro=!0),(_r&134217727)===0&&(ms&134217727)===0||bt===null||Ar(bt,et,zn,!1)}function kf(e,a,o){var l=dt;dt|=2;var d=Jy(),m=ev();(bt!==e||et!==a)&&(ic=null,io(e,a)),a=!1;var x=Tt;e:do try{if(mt!==0&&Ke!==null){var _=Ke,M=Dn;switch(mt){case 8:Of(),x=6;break e;case 3:case 2:case 9:case 6:kn.current===null&&(a=!0);var F=mt;if(mt=0,Dn=null,lo(e,_,M,F),o&&ro){x=0;break e}break;default:F=mt,mt=0,Dn=null,lo(e,_,M,F)}}h_(),x=Tt;break}catch(ne){Qy(e,ne)}while(!0);return a&&e.shellSuspendCounter++,Ha=rs=null,dt=l,j.H=d,j.A=m,Ke===null&&(bt=null,et=0,Tl()),x}function h_(){for(;Ke!==null;)tv(Ke)}function p_(e,a){var o=dt;dt|=2;var l=Jy(),d=ev();bt!==e||et!==a?(ic=null,oc=pe()+500,io(e,a)):ro=Et(e,a);e:do try{if(mt!==0&&Ke!==null){a=Ke;var m=Dn;t:switch(mt){case 1:mt=0,Dn=null,lo(e,a,m,1);break;case 2:case 9:if(dg(m)){mt=0,Dn=null,nv(a);break}a=function(){mt!==2&&mt!==9||bt!==e||(mt=7),Sa(e)},m.then(a,a);break e;case 3:mt=7;break e;case 4:mt=5;break e;case 7:dg(m)?(mt=0,Dn=null,nv(a)):(mt=0,Dn=null,lo(e,a,m,7));break;case 5:var x=null;switch(Ke.tag){case 26:x=Ke.memoizedState;case 5:case 27:var _=Ke;if(x?Vv(x):_.stateNode.complete){mt=0,Dn=null;var M=_.sibling;if(M!==null)Ke=M;else{var F=_.return;F!==null?(Ke=F,uc(F)):Ke=null}break t}}mt=0,Dn=null,lo(e,a,m,5);break;case 6:mt=0,Dn=null,lo(e,a,m,6);break;case 8:Of(),Tt=6;break e;default:throw Error(s(462))}}g_();break}catch(ne){Qy(e,ne)}while(!0);return Ha=rs=null,j.H=l,j.A=d,dt=o,Ke!==null?0:(bt=null,et=0,Tl(),Tt)}function g_(){for(;Ke!==null&&!$();)tv(Ke)}function tv(e){var a=Cy(e.alternate,e,Ka);e.memoizedProps=e.pendingProps,a===null?uc(e):Ke=a}function nv(e){var a=e,o=a.alternate;switch(a.tag){case 15:case 0:a=by(o,a,a.pendingProps,a.type,void 0,et);break;case 11:a=by(o,a,a.pendingProps,a.type.render,a.ref,et);break;case 5:Gd(a);default:Ay(o,a),a=Ke=eg(a,Ka),a=Cy(o,a,Ka)}e.memoizedProps=e.pendingProps,a===null?uc(e):Ke=a}function lo(e,a,o,l){Ha=rs=null,Gd(a),Qs=null,di=0;var d=a.return;try{if(r_(e,d,a,o,et)){Tt=1,Ql(e,Zn(o,e.current)),Ke=null;return}}catch(m){if(d!==null)throw Ke=d,m;Tt=1,Ql(e,Zn(o,e.current)),Ke=null;return}a.flags&32768?(nt||l===1?e=!0:ro||(et&536870912)!==0?e=!1:(Er=e=!0,(l===2||l===9||l===3||l===6)&&(l=kn.current,l!==null&&l.tag===13&&(l.flags|=16384))),av(a,e)):uc(a)}function uc(e){var a=e;do{if((a.flags&32768)!==0){av(a,Er);return}e=a.return;var o=i_(a.alternate,a,Ka);if(o!==null){Ke=o;return}if(a=a.sibling,a!==null){Ke=a;return}Ke=a=e}while(a!==null);Tt===0&&(Tt=5)}function av(e,a){do{var o=l_(e.alternate,e);if(o!==null){o.flags&=32767,Ke=o;return}if(o=e.return,o!==null&&(o.flags|=32768,o.subtreeFlags=0,o.deletions=null),!a&&(e=e.sibling,e!==null)){Ke=e;return}Ke=e=o}while(e!==null);Tt=6,Ke=null}function rv(e,a,o,l,d,m,x,_,M){e.cancelPendingCommit=null;do dc();while(Gt!==0);if((dt&6)!==0)throw Error(s(327));if(a!==null){if(a===e.current)throw Error(s(177));if(m=a.lanes|a.childLanes,m|=bd,gn(e,o,m,x,_,M),e===bt&&(Ke=bt=null,et=0),oo=a,Nr=e,Qa=o,Rf=m,Tf=d,Yy=l,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,x_(Xe,function(){return cv(),null})):(e.callbackNode=null,e.callbackPriority=0),l=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||l){l=j.T,j.T=null,d=Z.p,Z.p=2,x=dt,dt|=4;try{c_(e,a,o)}finally{dt=x,Z.p=d,j.T=l}}Gt=1,sv(),ov(),iv()}}function sv(){if(Gt===1){Gt=0;var e=Nr,a=oo,o=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||o){o=j.T,j.T=null;var l=Z.p;Z.p=2;var d=dt;dt|=4;try{Py(a,e);var m=Ff,x=$p(e.containerInfo),_=m.focusedElem,M=m.selectionRange;if(x!==_&&_&&_.ownerDocument&&Fp(_.ownerDocument.documentElement,_)){if(M!==null&&hd(_)){var F=M.start,ne=M.end;if(ne===void 0&&(ne=F),"selectionStart"in _)_.selectionStart=F,_.selectionEnd=Math.min(ne,_.value.length);else{var ce=_.ownerDocument||document,G=ce&&ce.defaultView||window;if(G.getSelection){var J=G.getSelection(),Ce=_.textContent.length,ze=Math.min(M.start,Ce),vt=M.end===void 0?ze:Math.min(M.end,Ce);!J.extend&&ze>vt&&(x=vt,vt=ze,ze=x);var B=qp(_,ze),z=qp(_,vt);if(B&&z&&(J.rangeCount!==1||J.anchorNode!==B.node||J.anchorOffset!==B.offset||J.focusNode!==z.node||J.focusOffset!==z.offset)){var q=ce.createRange();q.setStart(B.node,B.offset),J.removeAllRanges(),ze>vt?(J.addRange(q),J.extend(z.node,z.offset)):(q.setEnd(z.node,z.offset),J.addRange(q))}}}}for(ce=[],J=_;J=J.parentNode;)J.nodeType===1&&ce.push({element:J,left:J.scrollLeft,top:J.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_<ce.length;_++){var ie=ce[_];ie.element.scrollLeft=ie.left,ie.element.scrollTop=ie.top}}Ec=!!qf,Ff=qf=null}finally{dt=d,Z.p=l,j.T=o}}e.current=a,Gt=2}}function ov(){if(Gt===2){Gt=0;var e=Nr,a=oo,o=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||o){o=j.T,j.T=null;var l=Z.p;Z.p=2;var d=dt;dt|=4;try{Dy(e,a.alternate,a)}finally{dt=d,Z.p=l,j.T=o}}Gt=3}}function iv(){if(Gt===4||Gt===3){Gt=0,ye();var e=Nr,a=oo,o=Qa,l=Yy;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Gt=5:(Gt=0,oo=Nr=null,lv(e,e.pendingLanes));var d=e.pendingLanes;if(d===0&&(Cr=null),sa(o),a=a.stateNode,Nt&&typeof Nt.onCommitFiberRoot=="function")try{Nt.onCommitFiberRoot(Ft,a,void 0,(a.current.flags&128)===128)}catch{}if(l!==null){a=j.T,d=Z.p,Z.p=2,j.T=null;try{for(var m=e.onRecoverableError,x=0;x<l.length;x++){var _=l[x];m(_.value,{componentStack:_.stack})}}finally{j.T=a,Z.p=d}}(Qa&3)!==0&&dc(),Sa(e),d=e.pendingLanes,(o&261930)!==0&&(d&42)!==0?e===jf?Ri++:(Ri=0,jf=e):Ri=0,Ti(0)}}function lv(e,a){(e.pooledCacheLanes&=a)===0&&(a=e.pooledCache,a!=null&&(e.pooledCache=null,ci(a)))}function dc(){return sv(),ov(),iv(),cv()}function cv(){if(Gt!==5)return!1;var e=Nr,a=Rf;Rf=0;var o=sa(Qa),l=j.T,d=Z.p;try{Z.p=32>o?32:o,j.T=null,o=Tf,Tf=null;var m=Nr,x=Qa;if(Gt=0,oo=Nr=null,Qa=0,(dt&6)!==0)throw Error(s(331));var _=dt;if(dt|=4,Fy(m.current),Vy(m,m.current,x,o),dt=_,Ti(0,!1),Nt&&typeof Nt.onPostCommitFiberRoot=="function")try{Nt.onPostCommitFiberRoot(Ft,m)}catch{}return!0}finally{Z.p=d,j.T=l,lv(e,a)}}function uv(e,a,o){a=Zn(o,a),a=lf(e.stateNode,a,2),e=br(e,a,2),e!==null&&(At(e,2),Sa(e))}function ht(e,a,o){if(e.tag===3)uv(e,e,o);else for(;a!==null;){if(a.tag===3){uv(a,e,o);break}else if(a.tag===1){var l=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(Cr===null||!Cr.has(l))){e=Zn(o,e),o=dy(2),l=br(a,o,2),l!==null&&(fy(o,l,a,e),At(l,2),Sa(l));break}}a=a.return}}function Mf(e,a,o){var l=e.pingCache;if(l===null){l=e.pingCache=new f_;var d=new Set;l.set(a,d)}else d=l.get(a),d===void 0&&(d=new Set,l.set(a,d));d.has(o)||(Cf=!0,d.add(o),e=y_.bind(null,e,a,o),a.then(e,e))}function y_(e,a,o){var l=e.pingCache;l!==null&&l.delete(a),e.pingedLanes|=e.suspendedLanes&o,e.warmLanes&=~o,bt===e&&(et&o)===o&&(Tt===4||Tt===3&&(et&62914560)===et&&300>pe()-sc?(dt&2)===0&&io(e,0):Nf|=o,so===et&&(so=0)),Sa(e)}function dv(e,a){a===0&&(a=ln()),e=ts(e,a),e!==null&&(At(e,a),Sa(e))}function v_(e){var a=e.memoizedState,o=0;a!==null&&(o=a.retryLane),dv(e,o)}function b_(e,a){var o=0;switch(e.tag){case 31:case 13:var l=e.stateNode,d=e.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=e.stateNode;break;case 22:l=e.stateNode._retryCache;break;default:throw Error(s(314))}l!==null&&l.delete(a),dv(e,o)}function x_(e,a){return k(e,a)}var fc=null,co=null,Df=!1,mc=!1,zf=!1,Rr=0;function Sa(e){e!==co&&e.next===null&&(co===null?fc=co=e:co=co.next=e),mc=!0,Df||(Df=!0,S_())}function Ti(e,a){if(!zf&&mc){zf=!0;do for(var o=!1,l=fc;l!==null;){if(e!==0){var d=l.pendingLanes;if(d===0)var m=0;else{var x=l.suspendedLanes,_=l.pingedLanes;m=(1<<31-$t(42|e)+1)-1,m&=d&~(x&~_),m=m&201326741?m&201326741|1:m?m|2:0}m!==0&&(o=!0,pv(l,m))}else m=et,m=Be(l,l===bt?m:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(m&3)===0||Et(l,m)||(o=!0,pv(l,m));l=l.next}while(o);zf=!1}}function w_(){fv()}function fv(){mc=Df=!1;var e=0;Rr!==0&&k_()&&(e=Rr);for(var a=pe(),o=null,l=fc;l!==null;){var d=l.next,m=mv(l,a);m===0?(l.next=null,o===null?fc=d:o.next=d,d===null&&(co=o)):(o=l,(e!==0||(m&3)!==0)&&(mc=!0)),l=d}Gt!==0&&Gt!==5||Ti(e),Rr!==0&&(Rr=0)}function mv(e,a){for(var o=e.suspendedLanes,l=e.pingedLanes,d=e.expirationTimes,m=e.pendingLanes&-62914561;0<m;){var x=31-$t(m),_=1<<x,M=d[x];M===-1?((_&o)===0||(_&l)!==0)&&(d[x]=Kt(_,a)):M<=a&&(e.expiredLanes|=_),m&=~_}if(a=bt,o=et,o=Be(e,e===a?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l=e.callbackNode,o===0||e===a&&(mt===2||mt===9)||e.cancelPendingCommit!==null)return l!==null&&l!==null&&H(l),e.callbackNode=null,e.callbackPriority=0;if((o&3)===0||Et(e,o)){if(a=o&-o,a===e.callbackPriority)return a;switch(l!==null&&H(l),sa(o)){case 2:case 8:o=qe;break;case 32:o=Xe;break;case 268435456:o=on;break;default:o=Xe}return l=hv.bind(null,e),o=k(o,l),e.callbackPriority=a,e.callbackNode=o,a}return l!==null&&l!==null&&H(l),e.callbackPriority=2,e.callbackNode=null,2}function hv(e,a){if(Gt!==0&&Gt!==5)return e.callbackNode=null,e.callbackPriority=0,null;var o=e.callbackNode;if(dc()&&e.callbackNode!==o)return null;var l=et;return l=Be(e,e===bt?l:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l===0?null:(Xy(e,l,a),mv(e,pe()),e.callbackNode!=null&&e.callbackNode===o?hv.bind(null,e):null)}function pv(e,a){if(dc())return null;Xy(e,a,!0)}function S_(){D_(function(){(dt&6)!==0?k(Se,w_):fv()})}function Lf(){if(Rr===0){var e=Zs;e===0&&(e=As,As<<=1,(As&261888)===0&&(As=256)),Rr=e}return Rr}function gv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:wl(""+e)}function yv(e,a){var o=a.ownerDocument.createElement("input");return o.name=a.name,o.value=a.value,e.id&&o.setAttribute("form",e.id),a.parentNode.insertBefore(o,a),e=new FormData(e),o.parentNode.removeChild(o),e}function E_(e,a,o,l,d){if(a==="submit"&&o&&o.stateNode===d){var m=gv((d[bn]||null).action),x=l.submitter;x&&(a=(a=x[bn]||null)?gv(a.formAction):x.getAttribute("formAction"),a!==null&&(m=a,x=null));var _=new Cl("action","action",null,l,d);e.push({event:_,listeners:[{instance:null,listener:function(){if(l.defaultPrevented){if(Rr!==0){var M=x?yv(d,x):new FormData(d);tf(o,{pending:!0,data:M,method:d.method,action:m},null,M)}}else typeof m=="function"&&(_.preventDefault(),M=x?yv(d,x):new FormData(d),tf(o,{pending:!0,data:M,method:d.method,action:m},m,M))},currentTarget:d}]})}}for(var Uf=0;Uf<vd.length;Uf++){var Bf=vd[Uf],__=Bf.toLowerCase(),C_=Bf[0].toUpperCase()+Bf.slice(1);oa(__,"on"+C_)}oa(Zp,"onAnimationEnd"),oa(Xp,"onAnimationIteration"),oa(Kp,"onAnimationStart"),oa("dblclick","onDoubleClick"),oa("focusin","onFocus"),oa("focusout","onBlur"),oa(VE,"onTransitionRun"),oa(IE,"onTransitionStart"),oa(qE,"onTransitionCancel"),oa(Qp,"onTransitionEnd"),Ds("onMouseEnter",["mouseout","mouseover"]),Ds("onMouseLeave",["mouseout","mouseover"]),Ds("onPointerEnter",["pointerout","pointerover"]),Ds("onPointerLeave",["pointerout","pointerover"]),Qr("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Qr("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Qr("onBeforeInput",["compositionend","keypress","textInput","paste"]),Qr("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Qr("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Qr("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var ji="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),N_=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(ji));function vv(e,a){a=(a&4)!==0;for(var o=0;o<e.length;o++){var l=e[o],d=l.event;l=l.listeners;e:{var m=void 0;if(a)for(var x=l.length-1;0<=x;x--){var _=l[x],M=_.instance,F=_.currentTarget;if(_=_.listener,M!==m&&d.isPropagationStopped())break e;m=_,d.currentTarget=F;try{m(d)}catch(ne){Rl(ne)}d.currentTarget=null,m=M}else for(x=0;x<l.length;x++){if(_=l[x],M=_.instance,F=_.currentTarget,_=_.listener,M!==m&&d.isPropagationStopped())break e;m=_,d.currentTarget=F;try{m(d)}catch(ne){Rl(ne)}d.currentTarget=null,m=M}}}}function Qe(e,a){var o=a[Ku];o===void 0&&(o=a[Ku]=new Set);var l=e+"__bubble";o.has(l)||(bv(a,e,2,!1),o.add(l))}function Pf(e,a,o){var l=0;a&&(l|=4),bv(o,e,l,a)}var hc="_reactListening"+Math.random().toString(36).slice(2);function Hf(e){if(!e[hc]){e[hc]=!0,fp.forEach(function(o){o!=="selectionchange"&&(N_.has(o)||Pf(o,!1,e),Pf(o,!0,e))});var a=e.nodeType===9?e:e.ownerDocument;a===null||a[hc]||(a[hc]=!0,Pf("selectionchange",!1,a))}}function bv(e,a,o,l){switch(Zv(a)){case 2:var d=eC;break;case 8:d=tC;break;default:d=tm}o=d.bind(null,a,o,e),d=void 0,!sd||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(d=!0),l?d!==void 0?e.addEventListener(a,o,{capture:!0,passive:d}):e.addEventListener(a,o,!0):d!==void 0?e.addEventListener(a,o,{passive:d}):e.addEventListener(a,o,!1)}function Vf(e,a,o,l,d){var m=l;if((a&1)===0&&(a&2)===0&&l!==null)e:for(;;){if(l===null)return;var x=l.tag;if(x===3||x===4){var _=l.stateNode.containerInfo;if(_===d)break;if(x===4)for(x=l.return;x!==null;){var M=x.tag;if((M===3||M===4)&&x.stateNode.containerInfo===d)return;x=x.return}for(;_!==null;){if(x=Os(_),x===null)return;if(M=x.tag,M===5||M===6||M===26||M===27){l=m=x;continue e}_=_.parentNode}}l=l.return}_p(function(){var F=m,ne=ad(o),ce=[];e:{var G=Wp.get(e);if(G!==void 0){var J=Cl,Ce=e;switch(e){case"keypress":if(El(o)===0)break e;case"keydown":case"keyup":J=bE;break;case"focusin":Ce="focus",J=cd;break;case"focusout":Ce="blur",J=cd;break;case"beforeblur":case"afterblur":J=cd;break;case"click":if(o.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":J=Ap;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":J=iE;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":J=SE;break;case Zp:case Xp:case Kp:J=uE;break;case Qp:J=_E;break;case"scroll":case"scrollend":J=sE;break;case"wheel":J=NE;break;case"copy":case"cut":case"paste":J=fE;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":J=Tp;break;case"toggle":case"beforetoggle":J=RE}var ze=(a&4)!==0,vt=!ze&&(e==="scroll"||e==="scrollend"),B=ze?G!==null?G+"Capture":null:G;ze=[];for(var z=F,q;z!==null;){var ie=z;if(q=ie.stateNode,ie=ie.tag,ie!==5&&ie!==26&&ie!==27||q===null||B===null||(ie=Wo(z,B),ie!=null&&ze.push(Oi(z,ie,q))),vt)break;z=z.return}0<ze.length&&(G=new J(G,Ce,null,o,ne),ce.push({event:G,listeners:ze}))}}if((a&7)===0){e:{if(G=e==="mouseover"||e==="pointerover",J=e==="mouseout"||e==="pointerout",G&&o!==nd&&(Ce=o.relatedTarget||o.fromElement)&&(Os(Ce)||Ce[js]))break e;if((J||G)&&(G=ne.window===ne?ne:(G=ne.ownerDocument)?G.defaultView||G.parentWindow:window,J?(Ce=o.relatedTarget||o.toElement,J=F,Ce=Ce?Os(Ce):null,Ce!==null&&(vt=c(Ce),ze=Ce.tag,Ce!==vt||ze!==5&&ze!==27&&ze!==6)&&(Ce=null)):(J=null,Ce=F),J!==Ce)){if(ze=Ap,ie="onMouseLeave",B="onMouseEnter",z="mouse",(e==="pointerout"||e==="pointerover")&&(ze=Tp,ie="onPointerLeave",B="onPointerEnter",z="pointer"),vt=J==null?G:Qo(J),q=Ce==null?G:Qo(Ce),G=new ze(ie,z+"leave",J,o,ne),G.target=vt,G.relatedTarget=q,ie=null,Os(ne)===F&&(ze=new ze(B,z+"enter",Ce,o,ne),ze.target=q,ze.relatedTarget=vt,ie=ze),vt=ie,J&&Ce)t:{for(ze=A_,B=J,z=Ce,q=0,ie=B;ie;ie=ze(ie))q++;ie=0;for(var Me=z;Me;Me=ze(Me))ie++;for(;0<q-ie;)B=ze(B),q--;for(;0<ie-q;)z=ze(z),ie--;for(;q--;){if(B===z||z!==null&&B===z.alternate){ze=B;break t}B=ze(B),z=ze(z)}ze=null}else ze=null;J!==null&&xv(ce,G,J,ze,!1),Ce!==null&&vt!==null&&xv(ce,vt,Ce,ze,!0)}}e:{if(G=F?Qo(F):window,J=G.nodeName&&G.nodeName.toLowerCase(),J==="select"||J==="input"&&G.type==="file")var lt=Up;else if(zp(G))if(Bp)lt=BE;else{lt=LE;var Oe=zE}else J=G.nodeName,!J||J.toLowerCase()!=="input"||G.type!=="checkbox"&&G.type!=="radio"?F&&td(F.elementType)&&(lt=Up):lt=UE;if(lt&&(lt=lt(e,F))){Lp(ce,lt,o,ne);break e}Oe&&Oe(e,G,F),e==="focusout"&&F&&G.type==="number"&&F.memoizedProps.value!=null&&ed(G,"number",G.value)}switch(Oe=F?Qo(F):window,e){case"focusin":(zp(Oe)||Oe.contentEditable==="true")&&(Hs=Oe,pd=F,oi=null);break;case"focusout":oi=pd=Hs=null;break;case"mousedown":gd=!0;break;case"contextmenu":case"mouseup":case"dragend":gd=!1,Gp(ce,o,ne);break;case"selectionchange":if(HE)break;case"keydown":case"keyup":Gp(ce,o,ne)}var Ge;if(dd)e:{switch(e){case"compositionstart":var tt="onCompositionStart";break e;case"compositionend":tt="onCompositionEnd";break e;case"compositionupdate":tt="onCompositionUpdate";break e}tt=void 0}else Ps?Mp(e,o)&&(tt="onCompositionEnd"):e==="keydown"&&o.keyCode===229&&(tt="onCompositionStart");tt&&(jp&&o.locale!=="ko"&&(Ps||tt!=="onCompositionStart"?tt==="onCompositionEnd"&&Ps&&(Ge=Cp()):(fr=ne,od="value"in fr?fr.value:fr.textContent,Ps=!0)),Oe=pc(F,tt),0<Oe.length&&(tt=new Rp(tt,e,null,o,ne),ce.push({event:tt,listeners:Oe}),Ge?tt.data=Ge:(Ge=Dp(o),Ge!==null&&(tt.data=Ge)))),(Ge=jE?OE(e,o):kE(e,o))&&(tt=pc(F,"onBeforeInput"),0<tt.length&&(Oe=new Rp("onBeforeInput","beforeinput",null,o,ne),ce.push({event:Oe,listeners:tt}),Oe.data=Ge)),E_(ce,e,F,o,ne)}vv(ce,a)})}function Oi(e,a,o){return{instance:e,listener:a,currentTarget:o}}function pc(e,a){for(var o=a+"Capture",l=[];e!==null;){var d=e,m=d.stateNode;if(d=d.tag,d!==5&&d!==26&&d!==27||m===null||(d=Wo(e,o),d!=null&&l.unshift(Oi(e,d,m)),d=Wo(e,a),d!=null&&l.push(Oi(e,d,m))),e.tag===3)return l;e=e.return}return[]}function A_(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function xv(e,a,o,l,d){for(var m=a._reactName,x=[];o!==null&&o!==l;){var _=o,M=_.alternate,F=_.stateNode;if(_=_.tag,M!==null&&M===l)break;_!==5&&_!==26&&_!==27||F===null||(M=F,d?(F=Wo(o,m),F!=null&&x.unshift(Oi(o,F,M))):d||(F=Wo(o,m),F!=null&&x.push(Oi(o,F,M)))),o=o.return}x.length!==0&&e.push({event:a,listeners:x})}var R_=/\r\n?/g,T_=/\u0000|\uFFFD/g;function wv(e){return(typeof e=="string"?e:""+e).replace(R_,`+`).replace(T_,"")}function Sv(e,a){return a=wv(a),wv(e)===a}function yt(e,a,o,l,d,m){switch(o){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||Ls(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&Ls(e,""+l);break;case"className":bl(e,"class",l);break;case"tabIndex":bl(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":bl(e,o,l);break;case"style":Sp(e,l,m);break;case"data":if(a!=="object"){bl(e,"data",l);break}case"src":case"href":if(l===""&&(a!=="a"||o!=="href")){e.removeAttribute(o);break}if(l==null||typeof l=="function"||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=wl(""+l),e.setAttribute(o,l);break;case"action":case"formAction":if(typeof l=="function"){e.setAttribute(o,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof m=="function"&&(o==="formAction"?(a!=="input"&&yt(e,a,"name",d.name,d,null),yt(e,a,"formEncType",d.formEncType,d,null),yt(e,a,"formMethod",d.formMethod,d,null),yt(e,a,"formTarget",d.formTarget,d,null)):(yt(e,a,"encType",d.encType,d,null),yt(e,a,"method",d.method,d,null),yt(e,a,"target",d.target,d,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=wl(""+l),e.setAttribute(o,l);break;case"onClick":l!=null&&(e.onclick=La);break;case"onScroll":l!=null&&Qe("scroll",e);break;case"onScrollEnd":l!=null&&Qe("scrollend",e);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"multiple":e.multiple=l&&typeof l!="function"&&typeof l!="symbol";break;case"muted":e.muted=l&&typeof l!="function"&&typeof l!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(l==null||typeof l=="function"||typeof l=="boolean"||typeof l=="symbol"){e.removeAttribute("xlink:href");break}o=wl(""+l),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""+l):e.removeAttribute(o);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":l&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""):e.removeAttribute(o);break;case"capture":case"download":l===!0?e.setAttribute(o,""):l!==!1&&l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,l):e.removeAttribute(o);break;case"cols":case"rows":case"size":case"span":l!=null&&typeof l!="function"&&typeof l!="symbol"&&!isNaN(l)&&1<=l?e.setAttribute(o,l):e.removeAttribute(o);break;case"rowSpan":case"start":l==null||typeof l=="function"||typeof l=="symbol"||isNaN(l)?e.removeAttribute(o):e.setAttribute(o,l);break;case"popover":Qe("beforetoggle",e),Qe("toggle",e),vl(e,"popover",l);break;case"xlinkActuate":za(e,"http://www.w3.org/1999/xlink","xlink:actuate",l);break;case"xlinkArcrole":za(e,"http://www.w3.org/1999/xlink","xlink:arcrole",l);break;case"xlinkRole":za(e,"http://www.w3.org/1999/xlink","xlink:role",l);break;case"xlinkShow":za(e,"http://www.w3.org/1999/xlink","xlink:show",l);break;case"xlinkTitle":za(e,"http://www.w3.org/1999/xlink","xlink:title",l);break;case"xlinkType":za(e,"http://www.w3.org/1999/xlink","xlink:type",l);break;case"xmlBase":za(e,"http://www.w3.org/XML/1998/namespace","xml:base",l);break;case"xmlLang":za(e,"http://www.w3.org/XML/1998/namespace","xml:lang",l);break;case"xmlSpace":za(e,"http://www.w3.org/XML/1998/namespace","xml:space",l);break;case"is":vl(e,"is",l);break;case"innerText":case"textContent":break;default:(!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(o=aE.get(o)||o,vl(e,o,l))}}function If(e,a,o,l,d,m){switch(o){case"style":Sp(e,l,m);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"children":typeof l=="string"?Ls(e,l):(typeof l=="number"||typeof l=="bigint")&&Ls(e,""+l);break;case"onScroll":l!=null&&Qe("scroll",e);break;case"onScrollEnd":l!=null&&Qe("scrollend",e);break;case"onClick":l!=null&&(e.onclick=La);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!mp.hasOwnProperty(o))e:{if(o[0]==="o"&&o[1]==="n"&&(d=o.endsWith("Capture"),a=o.slice(2,d?o.length-7:void 0),m=e[bn]||null,m=m!=null?m[o]:null,typeof m=="function"&&e.removeEventListener(a,m,d),typeof l=="function")){typeof m!="function"&&m!==null&&(o in e?e[o]=null:e.hasAttribute(o)&&e.removeAttribute(o)),e.addEventListener(a,l,d);break e}o in e?e[o]=l:l===!0?e.setAttribute(o,""):vl(e,o,l)}}}function rn(e,a,o){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Qe("error",e),Qe("load",e);var l=!1,d=!1,m;for(m in o)if(o.hasOwnProperty(m)){var x=o[m];if(x!=null)switch(m){case"src":l=!0;break;case"srcSet":d=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:yt(e,a,m,x,o,null)}}d&&yt(e,a,"srcSet",o.srcSet,o,null),l&&yt(e,a,"src",o.src,o,null);return;case"input":Qe("invalid",e);var _=m=x=d=null,M=null,F=null;for(l in o)if(o.hasOwnProperty(l)){var ne=o[l];if(ne!=null)switch(l){case"name":d=ne;break;case"type":x=ne;break;case"checked":M=ne;break;case"defaultChecked":F=ne;break;case"value":m=ne;break;case"defaultValue":_=ne;break;case"children":case"dangerouslySetInnerHTML":if(ne!=null)throw Error(s(137,a));break;default:yt(e,a,l,ne,o,null)}}vp(e,m,_,M,F,x,d,!1);return;case"select":Qe("invalid",e),l=x=m=null;for(d in o)if(o.hasOwnProperty(d)&&(_=o[d],_!=null))switch(d){case"value":m=_;break;case"defaultValue":x=_;break;case"multiple":l=_;default:yt(e,a,d,_,o,null)}a=m,o=x,e.multiple=!!l,a!=null?zs(e,!!l,a,!1):o!=null&&zs(e,!!l,o,!0);return;case"textarea":Qe("invalid",e),m=d=l=null;for(x in o)if(o.hasOwnProperty(x)&&(_=o[x],_!=null))switch(x){case"value":l=_;break;case"defaultValue":d=_;break;case"children":m=_;break;case"dangerouslySetInnerHTML":if(_!=null)throw Error(s(91));break;default:yt(e,a,x,_,o,null)}xp(e,l,d,m);return;case"option":for(M in o)if(o.hasOwnProperty(M)&&(l=o[M],l!=null))switch(M){case"selected":e.selected=l&&typeof l!="function"&&typeof l!="symbol";break;default:yt(e,a,M,l,o,null)}return;case"dialog":Qe("beforetoggle",e),Qe("toggle",e),Qe("cancel",e),Qe("close",e);break;case"iframe":case"object":Qe("load",e);break;case"video":case"audio":for(l=0;l<ji.length;l++)Qe(ji[l],e);break;case"image":Qe("error",e),Qe("load",e);break;case"details":Qe("toggle",e);break;case"embed":case"source":case"link":Qe("error",e),Qe("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(F in o)if(o.hasOwnProperty(F)&&(l=o[F],l!=null))switch(F){case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:yt(e,a,F,l,o,null)}return;default:if(td(a)){for(ne in o)o.hasOwnProperty(ne)&&(l=o[ne],l!==void 0&&If(e,a,ne,l,o,void 0));return}}for(_ in o)o.hasOwnProperty(_)&&(l=o[_],l!=null&&yt(e,a,_,l,o,null))}function j_(e,a,o,l){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var d=null,m=null,x=null,_=null,M=null,F=null,ne=null;for(J in o){var ce=o[J];if(o.hasOwnProperty(J)&&ce!=null)switch(J){case"checked":break;case"value":break;case"defaultValue":M=ce;default:l.hasOwnProperty(J)||yt(e,a,J,null,l,ce)}}for(var G in l){var J=l[G];if(ce=o[G],l.hasOwnProperty(G)&&(J!=null||ce!=null))switch(G){case"type":m=J;break;case"name":d=J;break;case"checked":F=J;break;case"defaultChecked":ne=J;break;case"value":x=J;break;case"defaultValue":_=J;break;case"children":case"dangerouslySetInnerHTML":if(J!=null)throw Error(s(137,a));break;default:J!==ce&&yt(e,a,G,J,l,ce)}}Ju(e,x,_,M,F,ne,m,d);return;case"select":J=x=_=G=null;for(m in o)if(M=o[m],o.hasOwnProperty(m)&&M!=null)switch(m){case"value":break;case"multiple":J=M;default:l.hasOwnProperty(m)||yt(e,a,m,null,l,M)}for(d in l)if(m=l[d],M=o[d],l.hasOwnProperty(d)&&(m!=null||M!=null))switch(d){case"value":G=m;break;case"defaultValue":_=m;break;case"multiple":x=m;default:m!==M&&yt(e,a,d,m,l,M)}a=_,o=x,l=J,G!=null?zs(e,!!o,G,!1):!!l!=!!o&&(a!=null?zs(e,!!o,a,!0):zs(e,!!o,o?[]:"",!1));return;case"textarea":J=G=null;for(_ in o)if(d=o[_],o.hasOwnProperty(_)&&d!=null&&!l.hasOwnProperty(_))switch(_){case"value":break;case"children":break;default:yt(e,a,_,null,l,d)}for(x in l)if(d=l[x],m=o[x],l.hasOwnProperty(x)&&(d!=null||m!=null))switch(x){case"value":G=d;break;case"defaultValue":J=d;break;case"children":break;case"dangerouslySetInnerHTML":if(d!=null)throw Error(s(91));break;default:d!==m&&yt(e,a,x,d,l,m)}bp(e,G,J);return;case"option":for(var Ce in o)if(G=o[Ce],o.hasOwnProperty(Ce)&&G!=null&&!l.hasOwnProperty(Ce))switch(Ce){case"selected":e.selected=!1;break;default:yt(e,a,Ce,null,l,G)}for(M in l)if(G=l[M],J=o[M],l.hasOwnProperty(M)&&G!==J&&(G!=null||J!=null))switch(M){case"selected":e.selected=G&&typeof G!="function"&&typeof G!="symbol";break;default:yt(e,a,M,G,l,J)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var ze in o)G=o[ze],o.hasOwnProperty(ze)&&G!=null&&!l.hasOwnProperty(ze)&&yt(e,a,ze,null,l,G);for(F in l)if(G=l[F],J=o[F],l.hasOwnProperty(F)&&G!==J&&(G!=null||J!=null))switch(F){case"children":case"dangerouslySetInnerHTML":if(G!=null)throw Error(s(137,a));break;default:yt(e,a,F,G,l,J)}return;default:if(td(a)){for(var vt in o)G=o[vt],o.hasOwnProperty(vt)&&G!==void 0&&!l.hasOwnProperty(vt)&&If(e,a,vt,void 0,l,G);for(ne in l)G=l[ne],J=o[ne],!l.hasOwnProperty(ne)||G===J||G===void 0&&J===void 0||If(e,a,ne,G,l,J);return}}for(var B in o)G=o[B],o.hasOwnProperty(B)&&G!=null&&!l.hasOwnProperty(B)&&yt(e,a,B,null,l,G);for(ce in l)G=l[ce],J=o[ce],!l.hasOwnProperty(ce)||G===J||G==null&&J==null||yt(e,a,ce,G,l,J)}function Ev(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function O_(){if(typeof performance.getEntriesByType=="function"){for(var e=0,a=0,o=performance.getEntriesByType("resource"),l=0;l<o.length;l++){var d=o[l],m=d.transferSize,x=d.initiatorType,_=d.duration;if(m&&_&&Ev(x)){for(x=0,_=d.responseEnd,l+=1;l<o.length;l++){var M=o[l],F=M.startTime;if(F>_)break;var ne=M.transferSize,ce=M.initiatorType;ne&&Ev(ce)&&(M=M.responseEnd,x+=ne*(M<_?1:(_-F)/(M-F)))}if(--l,a+=8*(m+x)/(d.duration/1e3),e++,10<e)break}}if(0<e)return a/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var qf=null,Ff=null;function gc(e){return e.nodeType===9?e:e.ownerDocument}function _v(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Cv(e,a){if(e===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&a==="foreignObject"?0:e}function $f(e,a){return e==="textarea"||e==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Gf=null;function k_(){var e=window.event;return e&&e.type==="popstate"?e===Gf?!1:(Gf=e,!0):(Gf=null,!1)}var Nv=typeof setTimeout=="function"?setTimeout:void 0,M_=typeof clearTimeout=="function"?clearTimeout:void 0,Av=typeof Promise=="function"?Promise:void 0,D_=typeof queueMicrotask=="function"?queueMicrotask:typeof Av<"u"?function(e){return Av.resolve(null).then(e).catch(z_)}:Nv;function z_(e){setTimeout(function(){throw e})}function Tr(e){return e==="head"}function Rv(e,a){var o=a,l=0;do{var d=o.nextSibling;if(e.removeChild(o),d&&d.nodeType===8)if(o=d.data,o==="/$"||o==="/&"){if(l===0){e.removeChild(d),ho(a);return}l--}else if(o==="$"||o==="$?"||o==="$~"||o==="$!"||o==="&")l++;else if(o==="html")ki(e.ownerDocument.documentElement);else if(o==="head"){o=e.ownerDocument.head,ki(o);for(var m=o.firstChild;m;){var x=m.nextSibling,_=m.nodeName;m[Ko]||_==="SCRIPT"||_==="STYLE"||_==="LINK"&&m.rel.toLowerCase()==="stylesheet"||o.removeChild(m),m=x}}else o==="body"&&ki(e.ownerDocument.body);o=d}while(o);ho(a)}function Tv(e,a){var o=e;e=0;do{var l=o.nextSibling;if(o.nodeType===1?a?(o._stashedDisplay=o.style.display,o.style.display="none"):(o.style.display=o._stashedDisplay||"",o.getAttribute("style")===""&&o.removeAttribute("style")):o.nodeType===3&&(a?(o._stashedText=o.nodeValue,o.nodeValue=""):o.nodeValue=o._stashedText||""),l&&l.nodeType===8)if(o=l.data,o==="/$"){if(e===0)break;e--}else o!=="$"&&o!=="$?"&&o!=="$~"&&o!=="$!"||e++;o=l}while(o)}function Yf(e){var a=e.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var o=a;switch(a=a.nextSibling,o.nodeName){case"HTML":case"HEAD":case"BODY":Yf(o),Qu(o);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(o.rel.toLowerCase()==="stylesheet")continue}e.removeChild(o)}}function L_(e,a,o,l){for(;e.nodeType===1;){var d=o;if(e.nodeName.toLowerCase()!==a.toLowerCase()){if(!l&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(l){if(!e[Ko])switch(a){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(m=e.getAttribute("rel"),m==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(m!==d.rel||e.getAttribute("href")!==(d.href==null||d.href===""?null:d.href)||e.getAttribute("crossorigin")!==(d.crossOrigin==null?null:d.crossOrigin)||e.getAttribute("title")!==(d.title==null?null:d.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(m=e.getAttribute("src"),(m!==(d.src==null?null:d.src)||e.getAttribute("type")!==(d.type==null?null:d.type)||e.getAttribute("crossorigin")!==(d.crossOrigin==null?null:d.crossOrigin))&&m&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(a==="input"&&e.type==="hidden"){var m=d.name==null?null:""+d.name;if(d.type==="hidden"&&e.getAttribute("name")===m)return e}else return e;if(e=Jn(e.nextSibling),e===null)break}return null}function U_(e,a,o){if(a==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!o||(e=Jn(e.nextSibling),e===null))return null;return e}function jv(e,a){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!a||(e=Jn(e.nextSibling),e===null))return null;return e}function Zf(e){return e.data==="$?"||e.data==="$~"}function Xf(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function B_(e,a){var o=e.ownerDocument;if(e.data==="$~")e._reactRetry=a;else if(e.data!=="$?"||o.readyState!=="loading")a();else{var l=function(){a(),o.removeEventListener("DOMContentLoaded",l)};o.addEventListener("DOMContentLoaded",l),e._reactRetry=l}}function Jn(e){for(;e!=null;e=e.nextSibling){var a=e.nodeType;if(a===1||a===3)break;if(a===8){if(a=e.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return e}var Kf=null;function Ov(e){e=e.nextSibling;for(var a=0;e;){if(e.nodeType===8){var o=e.data;if(o==="/$"||o==="/&"){if(a===0)return Jn(e.nextSibling);a--}else o!=="$"&&o!=="$!"&&o!=="$?"&&o!=="$~"&&o!=="&"||a++}e=e.nextSibling}return null}function kv(e){e=e.previousSibling;for(var a=0;e;){if(e.nodeType===8){var o=e.data;if(o==="$"||o==="$!"||o==="$?"||o==="$~"||o==="&"){if(a===0)return e;a--}else o!=="/$"&&o!=="/&"||a++}e=e.previousSibling}return null}function Mv(e,a,o){switch(a=gc(o),e){case"html":if(e=a.documentElement,!e)throw Error(s(452));return e;case"head":if(e=a.head,!e)throw Error(s(453));return e;case"body":if(e=a.body,!e)throw Error(s(454));return e;default:throw Error(s(451))}}function ki(e){for(var a=e.attributes;a.length;)e.removeAttributeNode(a[0]);Qu(e)}var ea=new Map,Dv=new Set;function yc(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Wa=Z.d;Z.d={f:P_,r:H_,D:V_,C:I_,L:q_,m:F_,X:G_,S:$_,M:Y_};function P_(){var e=Wa.f(),a=lc();return e||a}function H_(e){var a=ks(e);a!==null&&a.tag===5&&a.type==="form"?Qg(a):Wa.r(e)}var uo=typeof document>"u"?null:document;function zv(e,a,o){var l=uo;if(l&&typeof a=="string"&&a){var d=Gn(a);d='link[rel="'+e+'"][href="'+d+'"]',typeof o=="string"&&(d+='[crossorigin="'+o+'"]'),Dv.has(d)||(Dv.add(d),e={rel:e,crossOrigin:o,href:a},l.querySelector(d)===null&&(a=l.createElement("link"),rn(a,"link",e),Qt(a),l.head.appendChild(a)))}}function V_(e){Wa.D(e),zv("dns-prefetch",e,null)}function I_(e,a){Wa.C(e,a),zv("preconnect",e,a)}function q_(e,a,o){Wa.L(e,a,o);var l=uo;if(l&&e&&a){var d='link[rel="preload"][as="'+Gn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(d+='[imagesrcset="'+Gn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(d+='[imagesizes="'+Gn(o.imageSizes)+'"]')):d+='[href="'+Gn(e)+'"]';var m=d;switch(a){case"style":m=fo(e);break;case"script":m=mo(e)}ea.has(m)||(e=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:e,as:a},o),ea.set(m,e),l.querySelector(d)!==null||a==="style"&&l.querySelector(Mi(m))||a==="script"&&l.querySelector(Di(m))||(a=l.createElement("link"),rn(a,"link",e),Qt(a),l.head.appendChild(a)))}}function F_(e,a){Wa.m(e,a);var o=uo;if(o&&e){var l=a&&typeof a.as=="string"?a.as:"script",d='link[rel="modulepreload"][as="'+Gn(l)+'"][href="'+Gn(e)+'"]',m=d;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=mo(e)}if(!ea.has(m)&&(e=y({rel:"modulepreload",href:e},a),ea.set(m,e),o.querySelector(d)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Di(m)))return}l=o.createElement("link"),rn(l,"link",e),Qt(l),o.head.appendChild(l)}}}function $_(e,a,o){Wa.S(e,a,o);var l=uo;if(l&&e){var d=Ms(l).hoistableStyles,m=fo(e);a=a||"default";var x=d.get(m);if(!x){var _={loading:0,preload:null};if(x=l.querySelector(Mi(m)))_.loading=5;else{e=y({rel:"stylesheet",href:e,"data-precedence":a},o),(o=ea.get(m))&&Qf(e,o);var M=x=l.createElement("link");Qt(M),rn(M,"link",e),M._p=new Promise(function(F,ne){M.onload=F,M.onerror=ne}),M.addEventListener("load",function(){_.loading|=1}),M.addEventListener("error",function(){_.loading|=2}),_.loading|=4,vc(x,a,l)}x={type:"stylesheet",instance:x,count:1,state:_},d.set(m,x)}}}function G_(e,a){Wa.X(e,a);var o=uo;if(o&&e){var l=Ms(o).hoistableScripts,d=mo(e),m=l.get(d);m||(m=o.querySelector(Di(d)),m||(e=y({src:e,async:!0},a),(a=ea.get(d))&&Wf(e,a),m=o.createElement("script"),Qt(m),rn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function Y_(e,a){Wa.M(e,a);var o=uo;if(o&&e){var l=Ms(o).hoistableScripts,d=mo(e),m=l.get(d);m||(m=o.querySelector(Di(d)),m||(e=y({src:e,async:!0,type:"module"},a),(a=ea.get(d))&&Wf(e,a),m=o.createElement("script"),Qt(m),rn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function Lv(e,a,o,l){var d=(d=fe.current)?yc(d):null;if(!d)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=fo(o.href),o=Ms(d).hoistableStyles,l=o.get(a),l||(l={type:"style",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){e=fo(o.href);var m=Ms(d).hoistableStyles,x=m.get(e);if(x||(d=d.ownerDocument||d,x={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},m.set(e,x),(m=d.querySelector(Mi(e)))&&!m._p&&(x.instance=m,x.state.loading=5),ea.has(e)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},ea.set(e,o),m||Z_(d,e,o,x.state))),a&&l===null)throw Error(s(528,""));return x}if(a&&l!==null)throw Error(s(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=mo(o),o=Ms(d).hoistableScripts,l=o.get(a),l||(l={type:"script",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function fo(e){return'href="'+Gn(e)+'"'}function Mi(e){return'link[rel="stylesheet"]['+e+"]"}function Uv(e){return y({},e,{"data-precedence":e.precedence,precedence:null})}function Z_(e,a,o,l){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?l.loading=1:(a=e.createElement("link"),l.preload=a,a.addEventListener("load",function(){return l.loading|=1}),a.addEventListener("error",function(){return l.loading|=2}),rn(a,"link",o),Qt(a),e.head.appendChild(a))}function mo(e){return'[src="'+Gn(e)+'"]'}function Di(e){return"script[async]"+e}function Bv(e,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var l=e.querySelector('style[data-href~="'+Gn(o.href)+'"]');if(l)return a.instance=l,Qt(l),l;var d=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return l=(e.ownerDocument||e).createElement("style"),Qt(l),rn(l,"style",d),vc(l,o.precedence,e),a.instance=l;case"stylesheet":d=fo(o.href);var m=e.querySelector(Mi(d));if(m)return a.state.loading|=4,a.instance=m,Qt(m),m;l=Uv(o),(d=ea.get(d))&&Qf(l,d),m=(e.ownerDocument||e).createElement("link"),Qt(m);var x=m;return x._p=new Promise(function(_,M){x.onload=_,x.onerror=M}),rn(m,"link",l),a.state.loading|=4,vc(m,o.precedence,e),a.instance=m;case"script":return m=mo(o.src),(d=e.querySelector(Di(m)))?(a.instance=d,Qt(d),d):(l=o,(d=ea.get(m))&&(l=y({},o),Wf(l,d)),e=e.ownerDocument||e,d=e.createElement("script"),Qt(d),rn(d,"link",l),e.head.appendChild(d),a.instance=d);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(l=a.instance,a.state.loading|=4,vc(l,o.precedence,e));return a.instance}function vc(e,a,o){for(var l=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),d=l.length?l[l.length-1]:null,m=d,x=0;x<l.length;x++){var _=l[x];if(_.dataset.precedence===a)m=_;else if(m!==d)break}m?m.parentNode.insertBefore(e,m.nextSibling):(a=o.nodeType===9?o.head:o,a.insertBefore(e,a.firstChild))}function Qf(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.title==null&&(e.title=a.title)}function Wf(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.integrity==null&&(e.integrity=a.integrity)}var bc=null;function Pv(e,a,o){if(bc===null){var l=new Map,d=bc=new Map;d.set(o,l)}else d=bc,l=d.get(o),l||(l=new Map,d.set(o,l));if(l.has(e))return l;for(l.set(e,null),o=o.getElementsByTagName(e),d=0;d<o.length;d++){var m=o[d];if(!(m[Ko]||m[en]||e==="link"&&m.getAttribute("rel")==="stylesheet")&&m.namespaceURI!=="http://www.w3.org/2000/svg"){var x=m.getAttribute(a)||"";x=e+x;var _=l.get(x);_?_.push(m):l.set(x,[m])}}return l}function Hv(e,a,o){e=e.ownerDocument||e,e.head.insertBefore(o,a==="title"?e.querySelector("head > title"):null)}function X_(e,a,o){if(o===1||a.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return e=a.disabled,typeof a.precedence=="string"&&e==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Vv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function K_(e,a,o,l){if(o.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var d=fo(l.href),m=a.querySelector(Mi(d));if(m){a=m._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=xc.bind(e),a.then(e,e)),o.state.loading|=4,o.instance=m,Qt(m);return}m=a.ownerDocument||a,l=Uv(l),(d=ea.get(d))&&Qf(l,d),m=m.createElement("link"),Qt(m);var x=m;x._p=new Promise(function(_,M){x.onload=_,x.onerror=M}),rn(m,"link",l),o.instance=m}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(e.count++,o=xc.bind(e),a.addEventListener("load",o),a.addEventListener("error",o))}}var Jf=0;function Q_(e,a){return e.stylesheets&&e.count===0&&Sc(e,e.stylesheets),0<e.count||0<e.imgCount?function(o){var l=setTimeout(function(){if(e.stylesheets&&Sc(e,e.stylesheets),e.unsuspend){var m=e.unsuspend;e.unsuspend=null,m()}},6e4+a);0<e.imgBytes&&Jf===0&&(Jf=62500*O_());var d=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Sc(e,e.stylesheets),e.unsuspend)){var m=e.unsuspend;e.unsuspend=null,m()}},(e.imgBytes>Jf?50:800)+a);return e.unsuspend=o,function(){e.unsuspend=null,clearTimeout(l),clearTimeout(d)}}:null}function xc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Sc(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var wc=null;function Sc(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,wc=new Map,a.forEach(W_,e),wc=null,xc.call(e))}function W_(e,a){if(!(a.state.loading&4)){var o=wc.get(e);if(o)var l=o.get(null);else{o=new Map,wc.set(e,o);for(var d=e.querySelectorAll("link[data-precedence],style[data-precedence]"),m=0;m<d.length;m++){var x=d[m];(x.nodeName==="LINK"||x.getAttribute("media")!=="not all")&&(o.set(x.dataset.precedence,x),l=x)}l&&o.set(null,l)}d=a.instance,x=d.getAttribute("data-precedence"),m=o.get(x)||l,m===l&&o.set(null,d),o.set(x,d),this.count++,l=xc.bind(this),d.addEventListener("load",l),d.addEventListener("error",l),m?m.parentNode.insertBefore(d,m.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(d,e.firstChild)),a.state.loading|=4}}var zi={$$typeof:R,Provider:null,Consumer:null,_currentValue:P,_currentValue2:P,_threadCount:0};function J_(e,a,o,l,d,m,x,_,M){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ur(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ur(0),this.hiddenUpdates=ur(null),this.identifierPrefix=l,this.onUncaughtError=d,this.onCaughtError=m,this.onRecoverableError=x,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=M,this.incompleteTransitions=new Map}function Iv(e,a,o,l,d,m,x,_,M,F,ne,ce){return e=new J_(e,a,o,x,M,F,ne,ce,_),a=1,m===!0&&(a|=24),m=On(3,null,null,a),e.current=m,m.stateNode=e,a=Od(),a.refCount++,e.pooledCache=a,a.refCount++,m.memoizedState={element:l,isDehydrated:o,cache:a},zd(m),e}function qv(e){return e?(e=qs,e):qs}function Fv(e,a,o,l,d,m){d=qv(d),l.context===null?l.context=d:l.pendingContext=d,l=vr(a),l.payload={element:o},m=m===void 0?null:m,m!==null&&(l.callback=m),o=br(e,l,a),o!==null&&(Cn(o,e,a),mi(o,e,a))}function $v(e,a){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var o=e.retryLane;e.retryLane=o!==0&&o<a?o:a}}function em(e,a){$v(e,a),(e=e.alternate)&&$v(e,a)}function Gv(e){if(e.tag===13||e.tag===31){var a=ts(e,67108864);a!==null&&Cn(a,e,67108864),em(e,67108864)}}function Yv(e){if(e.tag===13||e.tag===31){var a=Ln();a=Ts(a);var o=ts(e,a);o!==null&&Cn(o,e,a),em(e,a)}}var Ec=!0;function eC(e,a,o,l){var d=j.T;j.T=null;var m=Z.p;try{Z.p=2,tm(e,a,o,l)}finally{Z.p=m,j.T=d}}function tC(e,a,o,l){var d=j.T;j.T=null;var m=Z.p;try{Z.p=8,tm(e,a,o,l)}finally{Z.p=m,j.T=d}}function tm(e,a,o,l){if(Ec){var d=nm(l);if(d===null)Vf(e,a,l,_c,o),Xv(e,l);else if(aC(d,e,a,o,l))l.stopPropagation();else if(Xv(e,l),a&4&&-1<nC.indexOf(e)){for(;d!==null;){var m=ks(d);if(m!==null)switch(m.tag){case 3:if(m=m.stateNode,m.current.memoizedState.isDehydrated){var x=va(m.pendingLanes);if(x!==0){var _=m;for(_.pendingLanes|=2,_.entangledLanes|=2;x;){var M=1<<31-$t(x);_.entanglements[1]|=M,x&=~M}Sa(m),(dt&6)===0&&(oc=pe()+500,Ti(0))}}break;case 31:case 13:_=ts(m,2),_!==null&&Cn(_,m,2),lc(),em(m,2)}if(m=nm(l),m===null&&Vf(e,a,l,_c,o),m===d)break;d=m}d!==null&&l.stopPropagation()}else Vf(e,a,l,null,o)}}function nm(e){return e=ad(e),am(e)}var _c=null;function am(e){if(_c=null,e=Os(e),e!==null){var a=c(e);if(a===null)e=null;else{var o=a.tag;if(o===13){if(e=u(a),e!==null)return e;e=null}else if(o===31){if(e=f(a),e!==null)return e;e=null}else if(o===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;e=null}else a!==e&&(e=null)}}return _c=e,null}function Zv(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(ge()){case Se:return 2;case qe:return 8;case Xe:case Ot:return 32;case on:return 268435456;default:return 32}default:return 32}}var rm=!1,jr=null,Or=null,kr=null,Li=new Map,Ui=new Map,Mr=[],nC="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function Xv(e,a){switch(e){case"focusin":case"focusout":jr=null;break;case"dragenter":case"dragleave":Or=null;break;case"mouseover":case"mouseout":kr=null;break;case"pointerover":case"pointerout":Li.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ui.delete(a.pointerId)}}function Bi(e,a,o,l,d,m){return e===null||e.nativeEvent!==m?(e={blockedOn:a,domEventName:o,eventSystemFlags:l,nativeEvent:m,targetContainers:[d]},a!==null&&(a=ks(a),a!==null&&Gv(a)),e):(e.eventSystemFlags|=l,a=e.targetContainers,d!==null&&a.indexOf(d)===-1&&a.push(d),e)}function aC(e,a,o,l,d){switch(a){case"focusin":return jr=Bi(jr,e,a,o,l,d),!0;case"dragenter":return Or=Bi(Or,e,a,o,l,d),!0;case"mouseover":return kr=Bi(kr,e,a,o,l,d),!0;case"pointerover":var m=d.pointerId;return Li.set(m,Bi(Li.get(m)||null,e,a,o,l,d)),!0;case"gotpointercapture":return m=d.pointerId,Ui.set(m,Bi(Ui.get(m)||null,e,a,o,l,d)),!0}return!1}function Kv(e){var a=Os(e.target);if(a!==null){var o=c(a);if(o!==null){if(a=o.tag,a===13){if(a=u(o),a!==null){e.blockedOn=a,up(e.priority,function(){Yv(o)});return}}else if(a===31){if(a=f(o),a!==null){e.blockedOn=a,up(e.priority,function(){Yv(o)});return}}else if(a===3&&o.stateNode.current.memoizedState.isDehydrated){e.blockedOn=o.tag===3?o.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Cc(e){if(e.blockedOn!==null)return!1;for(var a=e.targetContainers;0<a.length;){var o=nm(e.nativeEvent);if(o===null){o=e.nativeEvent;var l=new o.constructor(o.type,o);nd=l,o.target.dispatchEvent(l),nd=null}else return a=ks(o),a!==null&&Gv(a),e.blockedOn=o,!1;a.shift()}return!0}function Qv(e,a,o){Cc(e)&&o.delete(a)}function rC(){rm=!1,jr!==null&&Cc(jr)&&(jr=null),Or!==null&&Cc(Or)&&(Or=null),kr!==null&&Cc(kr)&&(kr=null),Li.forEach(Qv),Ui.forEach(Qv)}function Nc(e,a){e.blockedOn===a&&(e.blockedOn=null,rm||(rm=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,rC)))}var Ac=null;function Wv(e){Ac!==e&&(Ac=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Ac===e&&(Ac=null);for(var a=0;a<e.length;a+=3){var o=e[a],l=e[a+1],d=e[a+2];if(typeof l!="function"){if(am(l||o)===null)continue;break}var m=ks(o);m!==null&&(e.splice(a,3),a-=3,tf(m,{pending:!0,data:d,method:o.method,action:l},l,d))}}))}function ho(e){function a(M){return Nc(M,e)}jr!==null&&Nc(jr,e),Or!==null&&Nc(Or,e),kr!==null&&Nc(kr,e),Li.forEach(a),Ui.forEach(a);for(var o=0;o<Mr.length;o++){var l=Mr[o];l.blockedOn===e&&(l.blockedOn=null)}for(;0<Mr.length&&(o=Mr[0],o.blockedOn===null);)Kv(o),o.blockedOn===null&&Mr.shift();if(o=(e.ownerDocument||e).$$reactFormReplay,o!=null)for(l=0;l<o.length;l+=3){var d=o[l],m=o[l+1],x=d[bn]||null;if(typeof m=="function")x||Wv(o);else if(x){var _=null;if(m&&m.hasAttribute("formAction")){if(d=m,x=m[bn]||null)_=x.formAction;else if(am(d)!==null)continue}else _=x.action;typeof _=="function"?o[l+1]=_:(o.splice(l,3),l-=3),Wv(o)}}}function Jv(){function e(m){m.canIntercept&&m.info==="react-transition"&&m.intercept({handler:function(){return new Promise(function(x){return d=x})},focusReset:"manual",scroll:"manual"})}function a(){d!==null&&(d(),d=null),l||setTimeout(o,20)}function o(){if(!l&&!navigation.transition){var m=navigation.currentEntry;m&&m.url!=null&&navigation.navigate(m.url,{state:m.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var l=!1,d=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(o,100),function(){l=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),d!==null&&(d(),d=null)}}}function sm(e){this._internalRoot=e}Rc.prototype.render=sm.prototype.render=function(e){var a=this._internalRoot;if(a===null)throw Error(s(409));var o=a.current,l=Ln();Fv(o,l,e,a,null,null)},Rc.prototype.unmount=sm.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var a=e.containerInfo;Fv(e.current,2,null,e,null,null),lc(),a[js]=null}};function Rc(e){this._internalRoot=e}Rc.prototype.unstable_scheduleHydration=function(e){if(e){var a=Xu();e={blockedOn:null,target:e,priority:a};for(var o=0;o<Mr.length&&a!==0&&a<Mr[o].priority;o++);Mr.splice(o,0,e),o===0&&Kv(e)}};var eb=n.version;if(eb!=="19.2.0")throw Error(s(527,eb,"19.2.0"));Z.findDOMNode=function(e){var a=e._reactInternals;if(a===void 0)throw typeof e.render=="function"?Error(s(188)):(e=Object.keys(e).join(","),Error(s(268,e)));return e=h(a),e=e!==null?v(e):null,e=e===null?null:e.stateNode,e};var sC={bundleType:0,version:"19.2.0",rendererPackageName:"react-dom",currentDispatcherRef:j,reconcilerVersion:"19.2.0"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Tc=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Tc.isDisabled&&Tc.supportsFiber)try{Ft=Tc.inject(sC),Nt=Tc}catch{}}return Hi.createRoot=function(e,a){if(!i(e))throw Error(s(299));var o=!1,l="",d=iy,m=ly,x=cy;return a!=null&&(a.unstable_strictMode===!0&&(o=!0),a.identifierPrefix!==void 0&&(l=a.identifierPrefix),a.onUncaughtError!==void 0&&(d=a.onUncaughtError),a.onCaughtError!==void 0&&(m=a.onCaughtError),a.onRecoverableError!==void 0&&(x=a.onRecoverableError)),a=Iv(e,1,!1,null,null,o,l,null,d,m,x,Jv),e[js]=a.current,Hf(e),new sm(a)},Hi.hydrateRoot=function(e,a,o){if(!i(e))throw Error(s(299));var l=!1,d="",m=iy,x=ly,_=cy,M=null;return o!=null&&(o.unstable_strictMode===!0&&(l=!0),o.identifierPrefix!==void 0&&(d=o.identifierPrefix),o.onUncaughtError!==void 0&&(m=o.onUncaughtError),o.onCaughtError!==void 0&&(x=o.onCaughtError),o.onRecoverableError!==void 0&&(_=o.onRecoverableError),o.formState!==void 0&&(M=o.formState)),a=Iv(e,1,!0,a,o??null,l,d,M,m,x,_,Jv),a.context=qv(null),o=a.current,l=Ln(),l=Ts(l),d=vr(l),d.callback=null,br(o,d,l),o=l,a.current.lanes=o,At(a,o),Sa(a),e[js]=a.current,Hf(e),new Rc(a)},Hi.version="19.2.0",Hi}var db;function yC(){if(db)return lm.exports;db=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),lm.exports=gC(),lm.exports}var vC=yC();/**+ * react-router v7.9.5+ *+ * 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+ */var fb="popstate";function bC(t={}){function n(s,i){let{pathname:c,search:u,hash:f}=s.location;return Um("",{pathname:c,search:u,hash:f},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function r(s,i){return typeof i=="string"?i:Wi(i)}return wC(n,r,null,t)}function Ct(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function da(t,n){if(!t){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function xC(){return Math.random().toString(36).substring(2,10)}function mb(t,n){return{usr:t.state,key:t.key,idx:n}}function Um(t,n,r=null,s){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?Bo(n):n,state:r,key:n&&n.key||s||xC()}}function Wi({pathname:t="/",search:n="",hash:r=""}){return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Bo(t){let n={};if(t){let r=t.indexOf("#");r>=0&&(n.hash=t.substring(r),t=t.substring(0,r));let s=t.indexOf("?");s>=0&&(n.search=t.substring(s),t=t.substring(0,s)),t&&(n.pathname=t)}return n}function wC(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,h=v();h==null&&(h=0,u.replaceState({...u.state,idx:h},""));function v(){return(u.state||{idx:null}).idx}function y(){f="POP";let C=v(),A=C==null?null:C-h;h=C,g&&g({action:f,location:S.location,delta:A})}function w(C,A){f="PUSH";let O=Um(S.location,C,A);h=v()+1;let R=mb(O,h),L=S.createHref(O);try{u.pushState(R,"",L)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;i.location.assign(L)}c&&g&&g({action:f,location:S.location,delta:1})}function N(C,A){f="REPLACE";let O=Um(S.location,C,A);h=v();let R=mb(O,h),L=S.createHref(O);u.replaceState(R,"",L),c&&g&&g({action:f,location:S.location,delta:0})}function E(C){return SC(C)}let S={get action(){return f},get location(){return t(i,u)},listen(C){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(fb,y),g=C,()=>{i.removeEventListener(fb,y),g=null}},createHref(C){return n(i,C)},createURL:E,encodeLocation(C){let A=E(C);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:w,replace:N,go(C){return u.go(C)}};return S}function SC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Ct(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:Wi(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function cx(t,n,r="/"){return EC(t,n,r,!1)}function EC(t,n,r,s){let i=typeof n=="string"?Bo(n):n,c=ar(i.pathname||"/",r);if(c==null)return null;let u=ux(t);_C(u);let f=null;for(let g=0;f==null&&g<u.length;++g){let h=zC(c);f=MC(u[g],h,s)}return f}function ux(t,n=[],r=[],s="",i=!1){let c=(u,f,g=i,h)=>{let v={relativePath:h===void 0?u.path||"":h,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(v.relativePath.startsWith("/")){if(!v.relativePath.startsWith(s)&&g)return;Ct(v.relativePath.startsWith(s),`Absolute route path "${v.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),v.relativePath=v.relativePath.slice(s.length)}let y=nr([s,v.relativePath]),w=r.concat(v);u.children&&u.children.length>0&&(Ct(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${y}".`),ux(u.children,n,w,y,g)),!(u.path==null&&!u.index)&&n.push({path:y,score:OC(y,u.index),routesMeta:w})};return t.forEach((u,f)=>{var g;if(u.path===""||!((g=u.path)!=null&&g.includes("?")))c(u,f);else for(let h of dx(u.path))c(u,f,!0,h)}),n}function dx(t){let n=t.split("/");if(n.length===0)return[];let[r,...s]=n,i=r.endsWith("?"),c=r.replace(/\?$/,"");if(s.length===0)return i?[c,""]:[c];let u=dx(s.join("/")),f=[];return f.push(...u.map(g=>g===""?c:[c,g].join("/"))),i&&f.push(...u),f.map(g=>t.startsWith("/")&&g===""?"/":g)}function _C(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:kC(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var CC=/^:[\w-]+$/,NC=3,AC=2,RC=1,TC=10,jC=-2,hb=t=>t==="*";function OC(t,n){let r=t.split("/"),s=r.length;return r.some(hb)&&(s+=jC),n&&(s+=AC),r.filter(i=>!hb(i)).reduce((i,c)=>i+(CC.test(c)?NC:c===""?RC:TC),s)}function kC(t,n){return t.length===n.length&&t.slice(0,-1).every((s,i)=>s===n[i])?t[t.length-1]-n[n.length-1]:0}function MC(t,n,r=!1){let{routesMeta:s}=t,i={},c="/",u=[];for(let f=0;f<s.length;++f){let g=s[f],h=f===s.length-1,v=c==="/"?n:n.slice(c.length)||"/",y=Wc({path:g.relativePath,caseSensitive:g.caseSensitive,end:h},v),w=g.route;if(!y&&h&&r&&!s[s.length-1].route.index&&(y=Wc({path:g.relativePath,caseSensitive:g.caseSensitive,end:!1},v)),!y)return null;Object.assign(i,y.params),u.push({params:i,pathname:nr([c,y.pathname]),pathnameBase:PC(nr([c,y.pathnameBase])),route:w}),y.pathnameBase!=="/"&&(c=nr([c,y.pathnameBase]))}return u}function Wc(t,n){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[r,s]=DC(t.path,t.caseSensitive,t.end),i=n.match(r);if(!i)return null;let c=i[0],u=c.replace(/(.)\/+$/,"$1"),f=i.slice(1);return{params:s.reduce((h,{paramName:v,isOptional:y},w)=>{if(v==="*"){let E=f[w]||"";u=c.slice(0,c.length-E.length).replace(/(.)\/+$/,"$1")}const N=f[w];return y&&!N?h[v]=void 0:h[v]=(N||"").replace(/%2F/g,"/"),h},{}),pathname:c,pathnameBase:u,pattern:t}}function DC(t,n=!1,r=!0){da(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let s=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(u,f,g)=>(s.push({paramName:f,isOptional:g!=null}),g?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(s.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,n?void 0:"i"),s]}function zC(t){try{return t.split("/").map(n=>decodeURIComponent(n).replace(/\//g,"%2F")).join("/")}catch(n){return da(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${n}).`),t}}function ar(t,n){if(n==="/")return t;if(!t.toLowerCase().startsWith(n.toLowerCase()))return null;let r=n.endsWith("/")?n.length-1:n.length,s=t.charAt(r);return s&&s!=="/"?null:t.slice(r)||"/"}function LC(t,n="/"){let{pathname:r,search:s="",hash:i=""}=typeof t=="string"?Bo(t):t;return{pathname:r?r.startsWith("/")?r:UC(r,n):n,search:HC(s),hash:VC(i)}}function UC(t,n){let r=n.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function fm(t,n,r,s){return`Cannot include a '${t}' character in a manually specified \`to.${n}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${r}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function BC(t){return t.filter((n,r)=>r===0||n.route.path&&n.route.path.length>0)}function hh(t){let n=BC(t);return n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase)}function ph(t,n,r,s=!1){let i;typeof t=="string"?i=Bo(t):(i={...t},Ct(!i.pathname||!i.pathname.includes("?"),fm("?","pathname","search",i)),Ct(!i.pathname||!i.pathname.includes("#"),fm("#","pathname","hash",i)),Ct(!i.search||!i.search.includes("#"),fm("#","search","hash",i)));let c=t===""||i.pathname==="",u=c?"/":i.pathname,f;if(u==null)f=r;else{let y=n.length-1;if(!s&&u.startsWith("..")){let w=u.split("/");for(;w[0]==="..";)w.shift(),y-=1;i.pathname=w.join("/")}f=y>=0?n[y]:"/"}let g=LC(i,f),h=u&&u!=="/"&&u.endsWith("/"),v=(c||u===".")&&r.endsWith("/");return!g.pathname.endsWith("/")&&(h||v)&&(g.pathname+="/"),g}var nr=t=>t.join("/").replace(/\/\/+/g,"/"),PC=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),HC=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,VC=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function IC(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var fx=["POST","PUT","PATCH","DELETE"];new Set(fx);var qC=["GET",...fx];new Set(qC);var Po=b.createContext(null);Po.displayName="DataRouter";var Cu=b.createContext(null);Cu.displayName="DataRouterState";b.createContext(!1);var mx=b.createContext({isTransitioning:!1});mx.displayName="ViewTransition";var FC=b.createContext(new Map);FC.displayName="Fetchers";var $C=b.createContext(null);$C.displayName="Await";var ha=b.createContext(null);ha.displayName="Navigation";var il=b.createContext(null);il.displayName="Location";var aa=b.createContext({outlet:null,matches:[],isDataRoute:!1});aa.displayName="Route";var gh=b.createContext(null);gh.displayName="RouteError";function GC(t,{relative:n}={}){Ct(Ho(),"useHref() may be used only in the context of a <Router> component.");let{basename:r,navigator:s}=b.useContext(ha),{hash:i,pathname:c,search:u}=ll(t,{relative:n}),f=c;return r!=="/"&&(f=c==="/"?r:nr([r,c])),s.createHref({pathname:f,search:u,hash:i})}function Ho(){return b.useContext(il)!=null}function Yr(){return Ct(Ho(),"useLocation() may be used only in the context of a <Router> component."),b.useContext(il).location}var hx="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function px(t){b.useContext(ha).static||b.useLayoutEffect(t)}function Vo(){let{isDataRoute:t}=b.useContext(aa);return t?l2():YC()}function YC(){Ct(Ho(),"useNavigate() may be used only in the context of a <Router> component.");let t=b.useContext(Po),{basename:n,navigator:r}=b.useContext(ha),{matches:s}=b.useContext(aa),{pathname:i}=Yr(),c=JSON.stringify(hh(s)),u=b.useRef(!1);return px(()=>{u.current=!0}),b.useCallback((g,h={})=>{if(da(u.current,hx),!u.current)return;if(typeof g=="number"){r.go(g);return}let v=ph(g,JSON.parse(c),i,h.relative==="path");t==null&&n!=="/"&&(v.pathname=v.pathname==="/"?n:nr([n,v.pathname])),(h.replace?r.replace:r.push)(v,h.state,h)},[n,r,c,i,t])}var ZC=b.createContext(null);function XC(t){let n=b.useContext(aa).outlet;return b.useMemo(()=>n&&b.createElement(ZC.Provider,{value:t},n),[n,t])}function KC(){let{matches:t}=b.useContext(aa),n=t[t.length-1];return n?n.params:{}}function ll(t,{relative:n}={}){let{matches:r}=b.useContext(aa),{pathname:s}=Yr(),i=JSON.stringify(hh(r));return b.useMemo(()=>ph(t,JSON.parse(i),s,n==="path"),[t,i,s,n])}function QC(t,n){return gx(t,n)}function gx(t,n,r,s,i){var O;Ct(Ho(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:c}=b.useContext(ha),{matches:u}=b.useContext(aa),f=u[u.length-1],g=f?f.params:{},h=f?f.pathname:"/",v=f?f.pathnameBase:"/",y=f&&f.route;{let R=y&&y.path||"";yx(h,!y||R.endsWith("*")||R.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${h}" (under <Route path="${R}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.++Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}/*`}">.`)}let w=Yr(),N;if(n){let R=typeof n=="string"?Bo(n):n;Ct(v==="/"||((O=R.pathname)==null?void 0:O.startsWith(v)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${v}" but pathname "${R.pathname}" was given in the \`location\` prop.`),N=R}else N=w;let E=N.pathname||"/",S=E;if(v!=="/"){let R=v.replace(/^\//,"").split("/");S="/"+E.replace(/^\//,"").split("/").slice(R.length).join("/")}let C=cx(t,{pathname:S});da(y||C!=null,`No routes matched location "${N.pathname}${N.search}${N.hash}" `),da(C==null||C[C.length-1].route.element!==void 0||C[C.length-1].route.Component!==void 0||C[C.length-1].route.lazy!==void 0,`Matched leaf route at location "${N.pathname}${N.search}${N.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let A=n2(C&&C.map(R=>Object.assign({},R,{params:Object.assign({},g,R.params),pathname:nr([v,c.encodeLocation?c.encodeLocation(R.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?v:nr([v,c.encodeLocation?c.encodeLocation(R.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),u,r,s,i);return n&&A?b.createElement(il.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...N},navigationType:"POP"}},A):A}function WC(){let t=i2(),n=IC(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,s="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:s},c={padding:"2px 4px",backgroundColor:s},u=null;return console.error("Error handled by React Router default ErrorBoundary:",t),u=b.createElement(b.Fragment,null,b.createElement("p",null,"💿 Hey developer 👋"),b.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",b.createElement("code",{style:c},"ErrorBoundary")," or"," ",b.createElement("code",{style:c},"errorElement")," prop on your route.")),b.createElement(b.Fragment,null,b.createElement("h2",null,"Unexpected Application Error!"),b.createElement("h3",{style:{fontStyle:"italic"}},n),r?b.createElement("pre",{style:i},r):null,u)}var JC=b.createElement(WC,null),e2=class extends b.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){this.props.unstable_onError?this.props.unstable_onError(t,n):console.error("React Router caught the following error during render",t)}render(){return this.state.error!==void 0?b.createElement(aa.Provider,{value:this.props.routeContext},b.createElement(gh.Provider,{value:this.state.error,children:this.props.component})):this.props.children}};function t2({routeContext:t,match:n,children:r}){let s=b.useContext(Po);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(aa.Provider,{value:t},r)}function n2(t,n=[],r=null,s=null,i=null){if(t==null){if(!r)return null;if(r.errors)t=r.matches;else if(n.length===0&&!r.initialized&&r.matches.length>0)t=r.matches;else return null}let c=t,u=r==null?void 0:r.errors;if(u!=null){let h=c.findIndex(v=>v.route.id&&(u==null?void 0:u[v.route.id])!==void 0);Ct(h>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(u).join(",")}`),c=c.slice(0,Math.min(c.length,h+1))}let f=!1,g=-1;if(r)for(let h=0;h<c.length;h++){let v=c[h];if((v.route.HydrateFallback||v.route.hydrateFallbackElement)&&(g=h),v.route.id){let{loaderData:y,errors:w}=r,N=v.route.loader&&!y.hasOwnProperty(v.route.id)&&(!w||w[v.route.id]===void 0);if(v.route.lazy||N){f=!0,g>=0?c=c.slice(0,g+1):c=[c[0]];break}}}return c.reduceRight((h,v,y)=>{let w,N=!1,E=null,S=null;r&&(w=u&&v.route.id?u[v.route.id]:void 0,E=v.route.errorElement||JC,f&&(g<0&&y===0?(yx("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),N=!0,S=null):g===y&&(N=!0,S=v.route.hydrateFallbackElement||null)));let C=n.concat(c.slice(0,y+1)),A=()=>{let O;return w?O=E:N?O=S:v.route.Component?O=b.createElement(v.route.Component,null):v.route.element?O=v.route.element:O=h,b.createElement(t2,{match:v,routeContext:{outlet:h,matches:C,isDataRoute:r!=null},children:O})};return r&&(v.route.ErrorBoundary||v.route.errorElement||y===0)?b.createElement(e2,{location:r.location,revalidation:r.revalidation,component:E,error:w,children:A(),routeContext:{outlet:null,matches:C,isDataRoute:!0},unstable_onError:s}):A()},null)}function yh(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function a2(t){let n=b.useContext(Po);return Ct(n,yh(t)),n}function r2(t){let n=b.useContext(Cu);return Ct(n,yh(t)),n}function s2(t){let n=b.useContext(aa);return Ct(n,yh(t)),n}function vh(t){let n=s2(t),r=n.matches[n.matches.length-1];return Ct(r.route.id,`${t} can only be used on routes that contain a unique "id"`),r.route.id}function o2(){return vh("useRouteId")}function i2(){var s;let t=b.useContext(gh),n=r2("useRouteError"),r=vh("useRouteError");return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function l2(){let{router:t}=a2("useNavigate"),n=vh("useNavigate"),r=b.useRef(!1);return px(()=>{r.current=!0}),b.useCallback(async(i,c={})=>{da(r.current,hx),r.current&&(typeof i=="number"?t.navigate(i):await t.navigate(i,{fromRouteId:n,...c}))},[t,n])}var pb={};function yx(t,n,r){!n&&!pb[t]&&(pb[t]=!0,da(!1,r))}b.memo(c2);function c2({routes:t,future:n,state:r,unstable_onError:s}){return gx(t,void 0,r,s,n)}function mm({to:t,replace:n,state:r,relative:s}){Ct(Ho(),"<Navigate> may be used only in the context of a <Router> component.");let{static:i}=b.useContext(ha);da(!i,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:c}=b.useContext(aa),{pathname:u}=Yr(),f=Vo(),g=ph(t,hh(c),u,s==="path"),h=JSON.stringify(g);return b.useEffect(()=>{f(JSON.parse(h),{replace:n,state:r,relative:s})},[f,h,s,n,r]),null}function u2(t){return XC(t.context)}function ta(t){Ct(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function d2({basename:t="/",children:n=null,location:r,navigationType:s="POP",navigator:i,static:c=!1}){Ct(!Ho(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=t.replace(/^\/*/,"/"),f=b.useMemo(()=>({basename:u,navigator:i,static:c,future:{}}),[u,i,c]);typeof r=="string"&&(r=Bo(r));let{pathname:g="/",search:h="",hash:v="",state:y=null,key:w="default"}=r,N=b.useMemo(()=>{let E=ar(g,u);return E==null?null:{location:{pathname:E,search:h,hash:v,state:y,key:w},navigationType:s}},[u,g,h,v,y,w,s]);return da(N!=null,`<Router basename="${u}"> is not able to match the URL "${g}${h}${v}" because it does not start with the basename, so the <Router> won't render anything.`),N==null?null:b.createElement(ha.Provider,{value:f},b.createElement(il.Provider,{children:n,value:N}))}function f2({children:t,location:n}){return QC(Bm(t),n)}function Bm(t,n=[]){let r=[];return b.Children.forEach(t,(s,i)=>{if(!b.isValidElement(s))return;let c=[...n,i];if(s.type===b.Fragment){r.push.apply(r,Bm(s.props.children,c));return}Ct(s.type===ta,`[${typeof s.type=="string"?s.type:s.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Ct(!s.props.index||!s.props.children,"An index route cannot have child routes.");let u={id:s.props.id||c.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,middleware:s.props.middleware,loader:s.props.loader,action:s.props.action,hydrateFallbackElement:s.props.hydrateFallbackElement,HydrateFallback:s.props.HydrateFallback,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.hasErrorBoundary===!0||s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(u.children=Bm(s.props.children,c)),r.push(u)}),r}var Fc="get",$c="application/x-www-form-urlencoded";function Nu(t){return t!=null&&typeof t.tagName=="string"}function m2(t){return Nu(t)&&t.tagName.toLowerCase()==="button"}function h2(t){return Nu(t)&&t.tagName.toLowerCase()==="form"}function p2(t){return Nu(t)&&t.tagName.toLowerCase()==="input"}function g2(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function y2(t,n){return t.button===0&&(!n||n==="_self")&&!g2(t)}var jc=null;function v2(){if(jc===null)try{new FormData(document.createElement("form"),0),jc=!1}catch{jc=!0}return jc}var b2=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function hm(t){return t!=null&&!b2.has(t)?(da(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${$c}"`),null):t}function x2(t,n){let r,s,i,c,u;if(h2(t)){let f=t.getAttribute("action");s=f?ar(f,n):null,r=t.getAttribute("method")||Fc,i=hm(t.getAttribute("enctype"))||$c,c=new FormData(t)}else if(m2(t)||p2(t)&&(t.type==="submit"||t.type==="image")){let f=t.form;if(f==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let g=t.getAttribute("formaction")||f.getAttribute("action");if(s=g?ar(g,n):null,r=t.getAttribute("formmethod")||f.getAttribute("method")||Fc,i=hm(t.getAttribute("formenctype"))||hm(f.getAttribute("enctype"))||$c,c=new FormData(f,t),!v2()){let{name:h,type:v,value:y}=t;if(v==="image"){let w=h?`${h}.`:"";c.append(`${w}x`,"0"),c.append(`${w}y`,"0")}else h&&c.append(h,y)}}else{if(Nu(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r=Fc,s=null,i=$c,u=t}return c&&i==="text/plain"&&(u=c,c=void 0),{action:s,method:r.toLowerCase(),encType:i,formData:c,body:u}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function bh(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function w2(t,n,r){let s=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return s.pathname==="/"?s.pathname=`_root.${r}`:n&&ar(s.pathname,n)==="/"?s.pathname=`${n.replace(/\/$/,"")}/_root.${r}`:s.pathname=`${s.pathname.replace(/\/$/,"")}.${r}`,s}async function S2(t,n){if(t.id in n)return n[t.id];try{let r=await import(t.module);return n[t.id]=r,r}catch(r){return console.error(`Error loading route module \`${t.module}\`, reloading page...`),console.error(r),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function E2(t){return t==null?!1:t.href==null?t.rel==="preload"&&typeof t.imageSrcSet=="string"&&typeof t.imageSizes=="string":typeof t.rel=="string"&&typeof t.href=="string"}async function _2(t,n,r){let s=await Promise.all(t.map(async i=>{let c=n.routes[i.route.id];if(c){let u=await S2(c,r);return u.links?u.links():[]}return[]}));return R2(s.flat(1).filter(E2).filter(i=>i.rel==="stylesheet"||i.rel==="preload").map(i=>i.rel==="stylesheet"?{...i,rel:"prefetch",as:"style"}:{...i,rel:"prefetch"}))}function gb(t,n,r,s,i,c){let u=(g,h)=>r[h]?g.route.id!==r[h].route.id:!0,f=(g,h)=>{var v;return r[h].pathname!==g.pathname||((v=r[h].route.path)==null?void 0:v.endsWith("*"))&&r[h].params["*"]!==g.params["*"]};return c==="assets"?n.filter((g,h)=>u(g,h)||f(g,h)):c==="data"?n.filter((g,h)=>{var y;let v=s.routes[g.route.id];if(!v||!v.hasLoader)return!1;if(u(g,h)||f(g,h))return!0;if(g.route.shouldRevalidate){let w=g.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:((y=r[0])==null?void 0:y.params)||{},nextUrl:new URL(t,window.origin),nextParams:g.params,defaultShouldRevalidate:!0});if(typeof w=="boolean")return w}return!0}):[]}function C2(t,n,{includeHydrateFallback:r}={}){return N2(t.map(s=>{let i=n.routes[s.route.id];if(!i)return[];let c=[i.module];return i.clientActionModule&&(c=c.concat(i.clientActionModule)),i.clientLoaderModule&&(c=c.concat(i.clientLoaderModule)),r&&i.hydrateFallbackModule&&(c=c.concat(i.hydrateFallbackModule)),i.imports&&(c=c.concat(i.imports)),c}).flat(1))}function N2(t){return[...new Set(t)]}function A2(t){let n={},r=Object.keys(t).sort();for(let s of r)n[s]=t[s];return n}function R2(t,n){let r=new Set;return new Set(n),t.reduce((s,i)=>{let c=JSON.stringify(A2(i));return r.has(c)||(r.add(c),s.push({key:c,link:i})),s},[])}function vx(){let t=b.useContext(Po);return bh(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function T2(){let t=b.useContext(Cu);return bh(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var xh=b.createContext(void 0);xh.displayName="FrameworkContext";function bx(){let t=b.useContext(xh);return bh(t,"You must render this element inside a <HydratedRouter> element"),t}function j2(t,n){let r=b.useContext(xh),[s,i]=b.useState(!1),[c,u]=b.useState(!1),{onFocus:f,onBlur:g,onMouseEnter:h,onMouseLeave:v,onTouchStart:y}=n,w=b.useRef(null);b.useEffect(()=>{if(t==="render"&&u(!0),t==="viewport"){let S=A=>{A.forEach(O=>{u(O.isIntersecting)})},C=new IntersectionObserver(S,{threshold:.5});return w.current&&C.observe(w.current),()=>{C.disconnect()}}},[t]),b.useEffect(()=>{if(s){let S=setTimeout(()=>{u(!0)},100);return()=>{clearTimeout(S)}}},[s]);let N=()=>{i(!0)},E=()=>{i(!1),u(!1)};return r?t!=="intent"?[c,w,{}]:[c,w,{onFocus:Vi(f,N),onBlur:Vi(g,E),onMouseEnter:Vi(h,N),onMouseLeave:Vi(v,E),onTouchStart:Vi(y,N)}]:[!1,w,{}]}function Vi(t,n){return r=>{t&&t(r),r.defaultPrevented||n(r)}}function O2({page:t,...n}){let{router:r}=vx(),s=b.useMemo(()=>cx(r.routes,t,r.basename),[r.routes,t,r.basename]);return s?b.createElement(M2,{page:t,matches:s,...n}):null}function k2(t){let{manifest:n,routeModules:r}=bx(),[s,i]=b.useState([]);return b.useEffect(()=>{let c=!1;return _2(t,n,r).then(u=>{c||i(u)}),()=>{c=!0}},[t,n,r]),s}function M2({page:t,matches:n,...r}){let s=Yr(),{manifest:i,routeModules:c}=bx(),{basename:u}=vx(),{loaderData:f,matches:g}=T2(),h=b.useMemo(()=>gb(t,n,g,i,s,"data"),[t,n,g,i,s]),v=b.useMemo(()=>gb(t,n,g,i,s,"assets"),[t,n,g,i,s]),y=b.useMemo(()=>{if(t===s.pathname+s.search+s.hash)return[];let E=new Set,S=!1;if(n.forEach(A=>{var R;let O=i.routes[A.route.id];!O||!O.hasLoader||(!h.some(L=>L.route.id===A.route.id)&&A.route.id in f&&((R=c[A.route.id])!=null&&R.shouldRevalidate)||O.hasClientLoader?S=!0:E.add(A.route.id))}),E.size===0)return[];let C=w2(t,u,"data");return S&&E.size>0&&C.searchParams.set("_routes",n.filter(A=>E.has(A.route.id)).map(A=>A.route.id).join(",")),[C.pathname+C.search]},[u,f,s,i,h,n,t,c]),w=b.useMemo(()=>C2(v,i),[v,i]),N=k2(v);return b.createElement(b.Fragment,null,y.map(E=>b.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...r})),w.map(E=>b.createElement("link",{key:E,rel:"modulepreload",href:E,...r})),N.map(({key:E,link:S})=>b.createElement("link",{key:E,nonce:r.nonce,...S})))}function D2(...t){return n=>{t.forEach(r=>{typeof r=="function"?r(n):r!=null&&(r.current=n)})}}var xx=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{xx&&(window.__reactRouterVersion="7.9.5")}catch{}function z2({basename:t,children:n,window:r}){let s=b.useRef();s.current==null&&(s.current=bC({window:r,v5Compat:!0}));let i=s.current,[c,u]=b.useState({action:i.action,location:i.location}),f=b.useCallback(g=>{b.startTransition(()=>u(g))},[u]);return b.useLayoutEffect(()=>i.listen(f),[i,f]),b.createElement(d2,{basename:t,children:n,location:c.location,navigationType:c.action,navigator:i})}var wx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Sx=b.forwardRef(function({onClick:n,discover:r="render",prefetch:s="none",relative:i,reloadDocument:c,replace:u,state:f,target:g,to:h,preventScrollReset:v,viewTransition:y,...w},N){let{basename:E}=b.useContext(ha),S=typeof h=="string"&&wx.test(h),C,A=!1;if(typeof h=="string"&&S&&(C=h,xx))try{let le=new URL(window.location.href),ue=h.startsWith("//")?new URL(le.protocol+h):new URL(h),me=ar(ue.pathname,E);ue.origin===le.origin&&me!=null?h=me+ue.search+ue.hash:A=!0}catch{da(!1,`<Link to="${h}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}let O=GC(h,{relative:i}),[R,L,I]=j2(s,w),ee=B2(h,{replace:u,state:f,target:g,preventScrollReset:v,relative:i,viewTransition:y});function U(le){n&&n(le),le.defaultPrevented||ee(le)}let Q=b.createElement("a",{...w,...I,href:C||O,onClick:A||c?n:U,ref:D2(N,L),target:g,"data-discover":!S&&r==="render"?"true":void 0});return R&&!S?b.createElement(b.Fragment,null,Q,b.createElement(O2,{page:O})):Q});Sx.displayName="Link";var Ex=b.forwardRef(function({"aria-current":n="page",caseSensitive:r=!1,className:s="",end:i=!1,style:c,to:u,viewTransition:f,children:g,...h},v){let y=ll(u,{relative:h.relative}),w=Yr(),N=b.useContext(Cu),{navigator:E,basename:S}=b.useContext(ha),C=N!=null&&q2(y)&&f===!0,A=E.encodeLocation?E.encodeLocation(y).pathname:y.pathname,O=w.pathname,R=N&&N.navigation&&N.navigation.location?N.navigation.location.pathname:null;r||(O=O.toLowerCase(),R=R?R.toLowerCase():null,A=A.toLowerCase()),R&&S&&(R=ar(R,S)||R);const L=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let I=O===A||!i&&O.startsWith(A)&&O.charAt(L)==="/",ee=R!=null&&(R===A||!i&&R.startsWith(A)&&R.charAt(A.length)==="/"),U={isActive:I,isPending:ee,isTransitioning:C},Q=I?n:void 0,le;typeof s=="function"?le=s(U):le=[s,I?"active":null,ee?"pending":null,C?"transitioning":null].filter(Boolean).join(" ");let ue=typeof c=="function"?c(U):c;return b.createElement(Sx,{...h,"aria-current":Q,className:le,ref:v,style:ue,to:u,viewTransition:f},typeof g=="function"?g(U):g)});Ex.displayName="NavLink";var L2=b.forwardRef(({discover:t="render",fetcherKey:n,navigate:r,reloadDocument:s,replace:i,state:c,method:u=Fc,action:f,onSubmit:g,relative:h,preventScrollReset:v,viewTransition:y,...w},N)=>{let E=V2(),S=I2(f,{relative:h}),C=u.toLowerCase()==="get"?"get":"post",A=typeof f=="string"&&wx.test(f),O=R=>{if(g&&g(R),R.defaultPrevented)return;R.preventDefault();let L=R.nativeEvent.submitter,I=(L==null?void 0:L.getAttribute("formmethod"))||u;E(L||R.currentTarget,{fetcherKey:n,method:I,navigate:r,replace:i,state:c,relative:h,preventScrollReset:v,viewTransition:y})};return b.createElement("form",{ref:N,method:C,action:S,onSubmit:s?g:O,...w,"data-discover":!A&&t==="render"?"true":void 0})});L2.displayName="Form";function U2(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function _x(t){let n=b.useContext(Po);return Ct(n,U2(t)),n}function B2(t,{target:n,replace:r,state:s,preventScrollReset:i,relative:c,viewTransition:u}={}){let f=Vo(),g=Yr(),h=ll(t,{relative:c});return b.useCallback(v=>{if(y2(v,n)){v.preventDefault();let y=r!==void 0?r:Wi(g)===Wi(h);f(t,{replace:y,state:s,preventScrollReset:i,relative:c,viewTransition:u})}},[g,f,h,r,s,n,t,i,c,u])}var P2=0,H2=()=>`__${String(++P2)}__`;function V2(){let{router:t}=_x("useSubmit"),{basename:n}=b.useContext(ha),r=o2();return b.useCallback(async(s,i={})=>{let{action:c,method:u,encType:f,formData:g,body:h}=x2(s,n);if(i.navigate===!1){let v=i.fetcherKey||H2();await t.fetch(v,r,i.action||c,{preventScrollReset:i.preventScrollReset,formData:g,body:h,formMethod:i.method||u,formEncType:i.encType||f,flushSync:i.flushSync})}else await t.navigate(i.action||c,{preventScrollReset:i.preventScrollReset,formData:g,body:h,formMethod:i.method||u,formEncType:i.encType||f,replace:i.replace,state:i.state,fromRouteId:r,flushSync:i.flushSync,viewTransition:i.viewTransition})},[t,n,r])}function I2(t,{relative:n}={}){let{basename:r}=b.useContext(ha),s=b.useContext(aa);Ct(s,"useFormAction must be used inside a RouteContext");let[i]=s.matches.slice(-1),c={...ll(t||".",{relative:n})},u=Yr();if(t==null){c.search=u.search;let f=new URLSearchParams(c.search),g=f.getAll("index");if(g.some(v=>v==="")){f.delete("index"),g.filter(y=>y).forEach(y=>f.append("index",y));let v=f.toString();c.search=v?`?${v}`:""}}return(!t||t===".")&&i.route.index&&(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),r!=="/"&&(c.pathname=c.pathname==="/"?r:nr([r,c.pathname])),Wi(c)}function q2(t,{relative:n}={}){let r=b.useContext(mx);Ct(r!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:s}=_x("useViewTransitionState"),i=ll(t,{relative:n});if(!r.isTransitioning)return!1;let c=ar(r.currentLocation.pathname,s)||r.currentLocation.pathname,u=ar(r.nextLocation.pathname,s)||r.nextLocation.pathname;return Wc(i.pathname,u)!=null||Wc(i.pathname,c)!=null}var wh=lx();const Cx=ix(wh);function F2(t){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}const $2=t=>{switch(t){case"success":return Z2;case"info":return K2;case"warning":return X2;case"error":return Q2;default:return null}},G2=Array(12).fill(0),Y2=({visible:t,className:n})=>ae.createElement("div",{className:["sonner-loading-wrapper",n].filter(Boolean).join(" "),"data-visible":t},ae.createElement("div",{className:"sonner-spinner"},G2.map((r,s)=>ae.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),Z2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),X2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),K2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Q2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),W2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ae.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ae.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),J2=()=>{const[t,n]=ae.useState(document.hidden);return ae.useEffect(()=>{const r=()=>{n(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t};let Pm=1;class eN{constructor(){this.subscribe=n=>(this.subscribers.push(n),()=>{const r=this.subscribers.indexOf(n);this.subscribers.splice(r,1)}),this.publish=n=>{this.subscribers.forEach(r=>r(n))},this.addToast=n=>{this.publish(n),this.toasts=[...this.toasts,n]},this.create=n=>{var r;const{message:s,...i}=n,c=typeof(n==null?void 0:n.id)=="number"||((r=n.id)==null?void 0:r.length)>0?n.id:Pm++,u=this.toasts.find(g=>g.id===c),f=n.dismissible===void 0?!0:n.dismissible;return this.dismissedToasts.has(c)&&this.dismissedToasts.delete(c),u?this.toasts=this.toasts.map(g=>g.id===c?(this.publish({...g,...n,id:c,title:s}),{...g,...n,id:c,dismissible:f,title:s}):g):this.addToast({title:s,...i,dismissible:f,id:c}),c},this.dismiss=n=>(n?(this.dismissedToasts.add(n),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:n,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),n),this.message=(n,r)=>this.create({...r,message:n}),this.error=(n,r)=>this.create({...r,message:n,type:"error"}),this.success=(n,r)=>this.create({...r,type:"success",message:n}),this.info=(n,r)=>this.create({...r,type:"info",message:n}),this.warning=(n,r)=>this.create({...r,type:"warning",message:n}),this.loading=(n,r)=>this.create({...r,type:"loading",message:n}),this.promise=(n,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:n,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const i=Promise.resolve(n instanceof Function?n():n);let c=s!==void 0,u;const f=i.then(async h=>{if(u=["resolve",h],ae.isValidElement(h))c=!1,this.create({id:s,type:"default",message:h});else if(nN(h)&&!h.ok){c=!1;const y=typeof r.error=="function"?await r.error(`HTTP error! status: ${h.status}`):r.error,w=typeof r.description=="function"?await r.description(`HTTP error! status: ${h.status}`):r.description,E=typeof y=="object"&&!ae.isValidElement(y)?y:{message:y};this.create({id:s,type:"error",description:w,...E})}else if(h instanceof Error){c=!1;const y=typeof r.error=="function"?await r.error(h):r.error,w=typeof r.description=="function"?await r.description(h):r.description,E=typeof y=="object"&&!ae.isValidElement(y)?y:{message:y};this.create({id:s,type:"error",description:w,...E})}else if(r.success!==void 0){c=!1;const y=typeof r.success=="function"?await r.success(h):r.success,w=typeof r.description=="function"?await r.description(h):r.description,E=typeof y=="object"&&!ae.isValidElement(y)?y:{message:y};this.create({id:s,type:"success",description:w,...E})}}).catch(async h=>{if(u=["reject",h],r.error!==void 0){c=!1;const v=typeof r.error=="function"?await r.error(h):r.error,y=typeof r.description=="function"?await r.description(h):r.description,N=typeof v=="object"&&!ae.isValidElement(v)?v:{message:v};this.create({id:s,type:"error",description:y,...N})}}).finally(()=>{c&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),g=()=>new Promise((h,v)=>f.then(()=>u[0]==="reject"?v(u[1]):h(u[1])).catch(v));return typeof s!="string"&&typeof s!="number"?{unwrap:g}:Object.assign(s,{unwrap:g})},this.custom=(n,r)=>{const s=(r==null?void 0:r.id)||Pm++;return this.create({jsx:n(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(n=>!this.dismissedToasts.has(n.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Nn=new eN,tN=(t,n)=>{const r=(n==null?void 0:n.id)||Pm++;return Nn.addToast({title:t,...n,id:r}),r},nN=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",aN=tN,rN=()=>Nn.toasts,sN=()=>Nn.getActiveToasts(),We=Object.assign(aN,{success:Nn.success,info:Nn.info,warning:Nn.warning,error:Nn.error,custom:Nn.custom,message:Nn.message,promise:Nn.promise,dismiss:Nn.dismiss,loading:Nn.loading},{getHistory:rN,getToasts:sN});F2("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Oc(t){return t.label!==void 0}const oN=3,iN="24px",lN="16px",yb=4e3,cN=356,uN=14,dN=45,fN=200;function Ea(...t){return t.filter(Boolean).join(" ")}function mN(t){const[n,r]=t.split("-"),s=[];return n&&s.push(n),r&&s.push(r),s}const hN=t=>{var n,r,s,i,c,u,f,g,h;const{invert:v,toast:y,unstyled:w,interacting:N,setHeights:E,visibleToasts:S,heights:C,index:A,toasts:O,expanded:R,removeToast:L,defaultRichColors:I,closeButton:ee,style:U,cancelButtonStyle:Q,actionButtonStyle:le,className:ue="",descriptionClassName:me="",duration:re,position:X,gap:he,expandByDefault:be,classNames:j,icons:Z,closeButtonAriaLabel:P="Close toast"}=t,[se,we]=ae.useState(null),[T,Y]=ae.useState(null),[D,V]=ae.useState(!1),[te,fe]=ae.useState(!1),[oe,K]=ae.useState(!1),[de,_e]=ae.useState(!1),[rt,De]=ae.useState(!1),[Le,xe]=ae.useState(0),[je,at]=ae.useState(0),pt=ae.useRef(y.duration||re||yb),Je=ae.useRef(null),Ue=ae.useRef(null),k=A===0,H=A+1<=S,$=y.type,ye=y.dismissible!==!1,pe=y.className||"",ge=y.descriptionClassName||"",Se=ae.useMemo(()=>C.findIndex(Be=>Be.toastId===y.id)||0,[C,y.id]),qe=ae.useMemo(()=>{var Be;return(Be=y.closeButton)!=null?Be:ee},[y.closeButton,ee]),Xe=ae.useMemo(()=>y.duration||re||yb,[y.duration,re]),Ot=ae.useRef(0),on=ae.useRef(0),dn=ae.useRef(0),Fn=ae.useRef(null),[Ft,Nt]=X.split("-"),fn=ae.useMemo(()=>C.reduce((Be,Et,Kt)=>Kt>=Se?Be:Be+Et.height,0),[C,Se]),$t=J2(),Xo=y.invert||v,cr=$==="loading";on.current=ae.useMemo(()=>Se*he+fn,[Se,fn]),ae.useEffect(()=>{pt.current=Xe},[Xe]),ae.useEffect(()=>{V(!0)},[]),ae.useEffect(()=>{const Be=Ue.current;if(Be){const Et=Be.getBoundingClientRect().height;return at(Et),E(Kt=>[{toastId:y.id,height:Et,position:y.position},...Kt]),()=>E(Kt=>Kt.filter(ln=>ln.toastId!==y.id))}},[E,y.id]),ae.useLayoutEffect(()=>{if(!D)return;const Be=Ue.current,Et=Be.style.height;Be.style.height="auto";const Kt=Be.getBoundingClientRect().height;Be.style.height=Et,at(Kt),E(ln=>ln.find(At=>At.toastId===y.id)?ln.map(At=>At.toastId===y.id?{...At,height:Kt}:At):[{toastId:y.id,height:Kt,position:y.position},...ln])},[D,y.title,y.description,E,y.id,y.jsx,y.action,y.cancel]);const ya=ae.useCallback(()=>{fe(!0),xe(on.current),E(Be=>Be.filter(Et=>Et.toastId!==y.id)),setTimeout(()=>{L(y)},fN)},[y,L,E,on]);ae.useEffect(()=>{if(y.promise&&$==="loading"||y.duration===1/0||y.type==="loading")return;let Be;return R||N||$t?(()=>{if(dn.current<Ot.current){const ln=new Date().getTime()-Ot.current;pt.current=pt.current-ln}dn.current=new Date().getTime()})():(()=>{pt.current!==1/0&&(Ot.current=new Date().getTime(),Be=setTimeout(()=>{y.onAutoClose==null||y.onAutoClose.call(y,y),ya()},pt.current))})(),()=>clearTimeout(Be)},[R,N,y,$,$t,ya]),ae.useEffect(()=>{y.delete&&(ya(),y.onDismiss==null||y.onDismiss.call(y,y))},[ya,y.delete]);function As(){var Be;if(Z!=null&&Z.loading){var Et;return ae.createElement("div",{className:Ea(j==null?void 0:j.loader,y==null||(Et=y.classNames)==null?void 0:Et.loader,"sonner-loader"),"data-visible":$==="loading"},Z.loading)}return ae.createElement(Y2,{className:Ea(j==null?void 0:j.loader,y==null||(Be=y.classNames)==null?void 0:Be.loader),visible:$==="loading"})}const Rs=y.icon||(Z==null?void 0:Z[$])||$2($);var Xr,va;return ae.createElement("li",{tabIndex:0,ref:Ue,className:Ea(ue,pe,j==null?void 0:j.toast,y==null||(n=y.classNames)==null?void 0:n.toast,j==null?void 0:j.default,j==null?void 0:j[$],y==null||(r=y.classNames)==null?void 0:r[$]),"data-sonner-toast":"","data-rich-colors":(Xr=y.richColors)!=null?Xr:I,"data-styled":!(y.jsx||y.unstyled||w),"data-mounted":D,"data-promise":!!y.promise,"data-swiped":rt,"data-removed":te,"data-visible":H,"data-y-position":Ft,"data-x-position":Nt,"data-index":A,"data-front":k,"data-swiping":oe,"data-dismissible":ye,"data-type":$,"data-invert":Xo,"data-swipe-out":de,"data-swipe-direction":T,"data-expanded":!!(R||be&&D),"data-testid":y.testId,style:{"--index":A,"--toasts-before":A,"--z-index":O.length-A,"--offset":`${te?Le:on.current}px`,"--initial-height":be?"auto":`${je}px`,...U,...y.style},onDragEnd:()=>{K(!1),we(null),Fn.current=null},onPointerDown:Be=>{Be.button!==2&&(cr||!ye||(Je.current=new Date,xe(on.current),Be.target.setPointerCapture(Be.pointerId),Be.target.tagName!=="BUTTON"&&(K(!0),Fn.current={x:Be.clientX,y:Be.clientY})))},onPointerUp:()=>{var Be,Et,Kt;if(de||!ye)return;Fn.current=null;const ln=Number(((Be=Ue.current)==null?void 0:Be.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ur=Number(((Et=Ue.current)==null?void 0:Et.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),At=new Date().getTime()-((Kt=Je.current)==null?void 0:Kt.getTime()),gn=se==="x"?ln:ur,Kr=Math.abs(gn)/At;if(Math.abs(gn)>=dN||Kr>.11){xe(on.current),y.onDismiss==null||y.onDismiss.call(y,y),Y(se==="x"?ln>0?"right":"left":ur>0?"down":"up"),ya(),_e(!0);return}else{var yn,vn;(yn=Ue.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(vn=Ue.current)==null||vn.style.setProperty("--swipe-amount-y","0px")}De(!1),K(!1),we(null)},onPointerMove:Be=>{var Et,Kt,ln;if(!Fn.current||!ye||((Et=window.getSelection())==null?void 0:Et.toString().length)>0)return;const At=Be.clientY-Fn.current.y,gn=Be.clientX-Fn.current.x;var Kr;const yn=(Kr=t.swipeDirections)!=null?Kr:mN(X);!se&&(Math.abs(gn)>1||Math.abs(At)>1)&&we(Math.abs(gn)>Math.abs(At)?"x":"y");let vn={x:0,y:0};const Ts=sa=>1/(1.5+Math.abs(sa)/20);if(se==="y"){if(yn.includes("top")||yn.includes("bottom"))if(yn.includes("top")&&At<0||yn.includes("bottom")&&At>0)vn.y=At;else{const sa=At*Ts(At);vn.y=Math.abs(sa)<Math.abs(At)?sa:At}}else if(se==="x"&&(yn.includes("left")||yn.includes("right")))if(yn.includes("left")&&gn<0||yn.includes("right")&&gn>0)vn.x=gn;else{const sa=gn*Ts(gn);vn.x=Math.abs(sa)<Math.abs(gn)?sa:gn}(Math.abs(vn.x)>0||Math.abs(vn.y)>0)&&De(!0),(Kt=Ue.current)==null||Kt.style.setProperty("--swipe-amount-x",`${vn.x}px`),(ln=Ue.current)==null||ln.style.setProperty("--swipe-amount-y",`${vn.y}px`)}},qe&&!y.jsx&&$!=="loading"?ae.createElement("button",{"aria-label":P,"data-disabled":cr,"data-close-button":!0,onClick:cr||!ye?()=>{}:()=>{ya(),y.onDismiss==null||y.onDismiss.call(y,y)},className:Ea(j==null?void 0:j.closeButton,y==null||(s=y.classNames)==null?void 0:s.closeButton)},(va=Z==null?void 0:Z.close)!=null?va:W2):null,($||y.icon||y.promise)&&y.icon!==null&&((Z==null?void 0:Z[$])!==null||y.icon)?ae.createElement("div",{"data-icon":"",className:Ea(j==null?void 0:j.icon,y==null||(i=y.classNames)==null?void 0:i.icon)},y.promise||y.type==="loading"&&!y.icon?y.icon||As():null,y.type!=="loading"?Rs:null):null,ae.createElement("div",{"data-content":"",className:Ea(j==null?void 0:j.content,y==null||(c=y.classNames)==null?void 0:c.content)},ae.createElement("div",{"data-title":"",className:Ea(j==null?void 0:j.title,y==null||(u=y.classNames)==null?void 0:u.title)},y.jsx?y.jsx:typeof y.title=="function"?y.title():y.title),y.description?ae.createElement("div",{"data-description":"",className:Ea(me,ge,j==null?void 0:j.description,y==null||(f=y.classNames)==null?void 0:f.description)},typeof y.description=="function"?y.description():y.description):null),ae.isValidElement(y.cancel)?y.cancel:y.cancel&&Oc(y.cancel)?ae.createElement("button",{"data-button":!0,"data-cancel":!0,style:y.cancelButtonStyle||Q,onClick:Be=>{Oc(y.cancel)&&ye&&(y.cancel.onClick==null||y.cancel.onClick.call(y.cancel,Be),ya())},className:Ea(j==null?void 0:j.cancelButton,y==null||(g=y.classNames)==null?void 0:g.cancelButton)},y.cancel.label):null,ae.isValidElement(y.action)?y.action:y.action&&Oc(y.action)?ae.createElement("button",{"data-button":!0,"data-action":!0,style:y.actionButtonStyle||le,onClick:Be=>{Oc(y.action)&&(y.action.onClick==null||y.action.onClick.call(y.action,Be),!Be.defaultPrevented&&ya())},className:Ea(j==null?void 0:j.actionButton,y==null||(h=y.classNames)==null?void 0:h.actionButton)},y.action.label):null)};function vb(){if(typeof window>"u"||typeof document>"u")return"ltr";const t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function pN(t,n){const r={};return[t,n].forEach((s,i)=>{const c=i===1,u=c?"--mobile-offset":"--offset",f=c?lN:iN;function g(h){["top","right","bottom","left"].forEach(v=>{r[`${u}-${v}`]=typeof h=="number"?`${h}px`:h})}typeof s=="number"||typeof s=="string"?g(s):typeof s=="object"?["top","right","bottom","left"].forEach(h=>{s[h]===void 0?r[`${u}-${h}`]=f:r[`${u}-${h}`]=typeof s[h]=="number"?`${s[h]}px`:s[h]}):g(f)}),r}const gN=ae.forwardRef(function(n,r){const{id:s,invert:i,position:c="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:g,className:h,offset:v,mobileOffset:y,theme:w="light",richColors:N,duration:E,style:S,visibleToasts:C=oN,toastOptions:A,dir:O=vb(),gap:R=uN,icons:L,containerAriaLabel:I="Notifications"}=n,[ee,U]=ae.useState([]),Q=ae.useMemo(()=>s?ee.filter(D=>D.toasterId===s):ee.filter(D=>!D.toasterId),[ee,s]),le=ae.useMemo(()=>Array.from(new Set([c].concat(Q.filter(D=>D.position).map(D=>D.position)))),[Q,c]),[ue,me]=ae.useState([]),[re,X]=ae.useState(!1),[he,be]=ae.useState(!1),[j,Z]=ae.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),P=ae.useRef(null),se=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),we=ae.useRef(null),T=ae.useRef(!1),Y=ae.useCallback(D=>{U(V=>{var te;return(te=V.find(fe=>fe.id===D.id))!=null&&te.delete||Nn.dismiss(D.id),V.filter(({id:fe})=>fe!==D.id)})},[]);return ae.useEffect(()=>Nn.subscribe(D=>{if(D.dismiss){requestAnimationFrame(()=>{U(V=>V.map(te=>te.id===D.id?{...te,delete:!0}:te))});return}setTimeout(()=>{Cx.flushSync(()=>{U(V=>{const te=V.findIndex(fe=>fe.id===D.id);return te!==-1?[...V.slice(0,te),{...V[te],...D},...V.slice(te+1)]:[D,...V]})})})}),[ee]),ae.useEffect(()=>{if(w!=="system"){Z(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;const D=window.matchMedia("(prefers-color-scheme: dark)");try{D.addEventListener("change",({matches:V})=>{Z(V?"dark":"light")})}catch{D.addListener(({matches:te})=>{try{Z(te?"dark":"light")}catch(fe){console.error(fe)}})}},[w]),ae.useEffect(()=>{ee.length<=1&&X(!1)},[ee]),ae.useEffect(()=>{const D=V=>{var te;if(u.every(K=>V[K]||V.code===K)){var oe;X(!0),(oe=P.current)==null||oe.focus()}V.code==="Escape"&&(document.activeElement===P.current||(te=P.current)!=null&&te.contains(document.activeElement))&&X(!1)};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[u]),ae.useEffect(()=>{if(P.current)return()=>{we.current&&(we.current.focus({preventScroll:!0}),we.current=null,T.current=!1)}},[P.current]),ae.createElement("section",{ref:r,"aria-label":`${I} ${se}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},le.map((D,V)=>{var te;const[fe,oe]=D.split("-");return Q.length?ae.createElement("ol",{key:D,dir:O==="auto"?vb():O,tabIndex:-1,ref:P,className:h,"data-sonner-toaster":!0,"data-sonner-theme":j,"data-y-position":fe,"data-x-position":oe,style:{"--front-toast-height":`${((te=ue[0])==null?void 0:te.height)||0}px`,"--width":`${cN}px`,"--gap":`${R}px`,...S,...pN(v,y)},onBlur:K=>{T.current&&!K.currentTarget.contains(K.relatedTarget)&&(T.current=!1,we.current&&(we.current.focus({preventScroll:!0}),we.current=null))},onFocus:K=>{K.target instanceof HTMLElement&&K.target.dataset.dismissible==="false"||T.current||(T.current=!0,we.current=K.relatedTarget)},onMouseEnter:()=>X(!0),onMouseMove:()=>X(!0),onMouseLeave:()=>{he||X(!1)},onDragEnd:()=>X(!1),onPointerDown:K=>{K.target instanceof HTMLElement&&K.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},Q.filter(K=>!K.position&&V===0||K.position===D).map((K,de)=>{var _e,rt;return ae.createElement(hN,{key:K.id,icons:L,index:de,toast:K,defaultRichColors:N,duration:(_e=A==null?void 0:A.duration)!=null?_e:E,className:A==null?void 0:A.className,descriptionClassName:A==null?void 0:A.descriptionClassName,invert:i,visibleToasts:C,closeButton:(rt=A==null?void 0:A.closeButton)!=null?rt:g,interacting:he,position:D,style:A==null?void 0:A.style,unstyled:A==null?void 0:A.unstyled,classNames:A==null?void 0:A.classNames,cancelButtonStyle:A==null?void 0:A.cancelButtonStyle,actionButtonStyle:A==null?void 0:A.actionButtonStyle,closeButtonAriaLabel:A==null?void 0:A.closeButtonAriaLabel,removeToast:Y,toasts:Q.filter(De=>De.position==K.position),heights:ue.filter(De=>De.position==K.position),setHeights:me,expandByDefault:f,gap:R,expanded:re,swipeDirections:n.swipeDirections})})):null}))});/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const yN=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),vN=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),bb=t=>{const n=vN(t);return n.charAt(0).toUpperCase()+n.slice(1)},Nx=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),bN=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */var xN={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.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const wN=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...xN,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:Nx("lucide",i),...!c&&!bN(f)&&{"aria-hidden":"true"},...f},[...u.map(([h,v])=>b.createElement(h,v)),...Array.isArray(c)?c:[c]]));/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const ot=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(wN,{ref:c,iconNode:n,className:Nx(`lucide-${yN(bb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=bb(t),r};/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const SN=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],xb=ot("arrow-left",SN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const EN=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],_N=ot("arrow-right",EN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const CN=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Hm=ot("chevron-down",CN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const NN=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],wb=ot("chevron-right",NN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const AN=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],RN=ot("chevron-up",AN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const TN=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],jN=ot("circle-alert",TN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const ON=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Sb=ot("circle-check",ON);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const kN=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],MN=ot("ellipsis-vertical",kN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const DN=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],zN=ot("eye-off",DN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const LN=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],UN=ot("eye",LN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const BN=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],PN=ot("funnel",BN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const HN=[["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"}]],VN=ot("globe",HN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const IN=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],qN=ot("layers",IN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const FN=[["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"}]],$N=ot("layout-dashboard",FN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const GN=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],YN=ot("loader-circle",GN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const ZN=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],XN=ot("log-out",ZN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const KN=[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]],QN=ot("message-square",KN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const WN=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],JN=ot("moon",WN);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const eA=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Vm=ot("plus",eA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const tA=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],nA=ot("power-off",tA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const aA=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Ax=ot("power",aA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const rA=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],Eb=ot("qr-code",rA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const sA=[["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"}]],_b=ot("refresh-cw",sA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const oA=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],Cb=ot("save",oA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const iA=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],lA=ot("search",iA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const cA=[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],uA=ot("settings",cA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const dA=[["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"}]],fA=ot("shield",dA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const mA=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],hA=ot("smartphone",mA);/**+ * @license lucide-react v0.525.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=[["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"}]],gA=ot("sun",pA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const yA=[["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"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]],Sh=ot("trash-2",yA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const vA=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],bA=ot("triangle-alert",vA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const xA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=ot("x",xA);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const wA=[["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"}]],SA=ot("zap",wA);class EA extends b.Component{constructor(r){super(r);tb(this,"handleReset",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r,errorInfo:null}}componentDidCatch(r,s){console.error("ErrorBoundary caught an error:",r,s),this.setState({error:r,errorInfo:s})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-50 px-4",children:p.jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-8 shadow-lg",children:[p.jsx("div",{className:"mb-4 flex items-center justify-center",children:p.jsx("div",{className:"rounded-full bg-red-100 p-3",children:p.jsx(bA,{className:"h-8 w-8 text-red-600"})})}),p.jsx("h1",{className:"mb-2 text-center text-2xl font-bold text-gray-900",children:"Algo deu errado"}),p.jsx("p",{className:"mb-6 text-center text-gray-600",children:"Ocorreu um erro inesperado na aplicação."}),this.state.error&&p.jsxs("div",{className:"mb-6 rounded-md bg-red-50 p-4",children:[p.jsx("p",{className:"text-sm font-medium text-red-800",children:this.state.error.message}),!1]}),p.jsxs("div",{className:"flex gap-3",children:[p.jsx("button",{onClick:this.handleReset,className:"flex-1 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Tentar novamente"}),p.jsx("button",{onClick:()=>window.location.href="/",className:"flex-1 rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Voltar ao início"})]})]})}):this.props.children}}function Rx(t){var n,r,s="";if(typeof t=="string"||typeof t=="number")s+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(n=0;n<i;n++)t[n]&&(r=Rx(t[n]))&&(s&&(s+=" "),s+=r)}else for(r in t)t[r]&&(s&&(s+=" "),s+=r);return s}function Eh(){for(var t,n,r=0,s="",i=arguments.length;r<i;r++)(t=arguments[r])&&(n=Rx(t))&&(s&&(s+=" "),s+=n);return s}const _A=(t,n)=>{const r=new Array(t.length+n.length);for(let s=0;s<t.length;s++)r[s]=t[s];for(let s=0;s<n.length;s++)r[t.length+s]=n[s];return r},CA=(t,n)=>({classGroupId:t,validator:n}),Tx=(t=new Map,n=null,r)=>({nextPart:t,validators:n,classGroupId:r}),Jc="-",Nb=[],NA="arbitrary..",AA=t=>{const n=TA(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=t;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return RA(u);const f=u.split(Jc),g=f[0]===""&&f.length>1?1:0;return jx(f,g,n)},getConflictingClassGroupIds:(u,f)=>{if(f){const g=s[u],h=r[u];return g?h?_A(h,g):g:h||Nb}return r[u]||Nb}}},jx=(t,n,r)=>{if(t.length-n===0)return r.classGroupId;const i=t[n],c=r.nextPart.get(i);if(c){const h=jx(t,n+1,c);if(h)return h}const u=r.validators;if(u===null)return;const f=n===0?t.join(Jc):t.slice(n).join(Jc),g=u.length;for(let h=0;h<g;h++){const v=u[h];if(v.validator(f))return v.classGroupId}},RA=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=t.slice(1,-1),r=n.indexOf(":"),s=n.slice(0,r);return s?NA+s:void 0})(),TA=t=>{const{theme:n,classGroups:r}=t;return jA(r,n)},jA=(t,n)=>{const r=Tx();for(const s in t){const i=t[s];_h(i,r,s,n)}return r},_h=(t,n,r,s)=>{const i=t.length;for(let c=0;c<i;c++){const u=t[c];OA(u,n,r,s)}},OA=(t,n,r,s)=>{if(typeof t=="string"){kA(t,n,r);return}if(typeof t=="function"){MA(t,n,r,s);return}DA(t,n,r,s)},kA=(t,n,r)=>{const s=t===""?n:Ox(n,t);s.classGroupId=r},MA=(t,n,r,s)=>{if(zA(t)){_h(t(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(CA(r,t))},DA=(t,n,r,s)=>{const i=Object.entries(t),c=i.length;for(let u=0;u<c;u++){const[f,g]=i[u];_h(g,Ox(n,f),r,s)}},Ox=(t,n)=>{let r=t;const s=n.split(Jc),i=s.length;for(let c=0;c<i;c++){const u=s[c];let f=r.nextPart.get(u);f||(f=Tx(),r.nextPart.set(u,f)),r=f}return r},zA=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,LA=t=>{if(t<1)return{get:()=>{},set:()=>{}};let n=0,r=Object.create(null),s=Object.create(null);const i=(c,u)=>{r[c]=u,n++,n>t&&(n=0,s=r,r=Object.create(null))};return{get(c){let u=r[c];if(u!==void 0)return u;if((u=s[c])!==void 0)return i(c,u),u},set(c,u){c in r?r[c]=u:i(c,u)}}},Im="!",Ab=":",UA=[],Rb=(t,n,r,s,i)=>({modifiers:t,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:i}),BA=t=>{const{prefix:n,experimentalParseClassName:r}=t;let s=i=>{const c=[];let u=0,f=0,g=0,h;const v=i.length;for(let S=0;S<v;S++){const C=i[S];if(u===0&&f===0){if(C===Ab){c.push(i.slice(g,S)),g=S+1;continue}if(C==="/"){h=S;continue}}C==="["?u++:C==="]"?u--:C==="("?f++:C===")"&&f--}const y=c.length===0?i:i.slice(g);let w=y,N=!1;y.endsWith(Im)?(w=y.slice(0,-1),N=!0):y.startsWith(Im)&&(w=y.slice(1),N=!0);const E=h&&h>g?h-g:void 0;return Rb(c,N,w,E)};if(n){const i=n+Ab,c=s;s=u=>u.startsWith(i)?c(u.slice(i.length)):Rb(UA,!1,u,void 0,!0)}if(r){const i=s;s=c=>r({className:c,parseClassName:i})}return s},PA=t=>{const n=new Map;return t.orderSensitiveModifiers.forEach((r,s)=>{n.set(r,1e6+s)}),r=>{const s=[];let i=[];for(let c=0;c<r.length;c++){const u=r[c],f=u[0]==="[",g=n.has(u);f||g?(i.length>0&&(i.sort(),s.push(...i),i=[]),s.push(u)):i.push(u)}return i.length>0&&(i.sort(),s.push(...i)),s}},HA=t=>({cache:LA(t.cacheSize),parseClassName:BA(t),sortModifiers:PA(t),...AA(t)}),VA=/\s+/,IA=(t,n)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:i,sortModifiers:c}=n,u=[],f=t.trim().split(VA);let g="";for(let h=f.length-1;h>=0;h-=1){const v=f[h],{isExternal:y,modifiers:w,hasImportantModifier:N,baseClassName:E,maybePostfixModifierPosition:S}=r(v);if(y){g=v+(g.length>0?" "+g:g);continue}let C=!!S,A=s(C?E.substring(0,S):E);if(!A){if(!C){g=v+(g.length>0?" "+g:g);continue}if(A=s(E),!A){g=v+(g.length>0?" "+g:g);continue}C=!1}const O=w.length===0?"":w.length===1?w[0]:c(w).join(":"),R=N?O+Im:O,L=R+A;if(u.indexOf(L)>-1)continue;u.push(L);const I=i(A,C);for(let ee=0;ee<I.length;++ee){const U=I[ee];u.push(R+U)}g=v+(g.length>0?" "+g:g)}return g},qA=(...t)=>{let n=0,r,s,i="";for(;n<t.length;)(r=t[n++])&&(s=kx(r))&&(i&&(i+=" "),i+=s);return i},kx=t=>{if(typeof t=="string")return t;let n,r="";for(let s=0;s<t.length;s++)t[s]&&(n=kx(t[s]))&&(r&&(r+=" "),r+=n);return r},FA=(t,...n)=>{let r,s,i,c;const u=g=>{const h=n.reduce((v,y)=>y(v),t());return r=HA(h),s=r.cache.get,i=r.cache.set,c=f,f(g)},f=g=>{const h=s(g);if(h)return h;const v=IA(g,r);return i(g,v),v};return c=u,(...g)=>c(qA(...g))},$A=[],Yt=t=>{const n=r=>r[t]||$A;return n.isThemeGetter=!0,n},Mx=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Dx=/^\((?:(\w[\w-]*):)?(.+)\)$/i,GA=/^\d+\/\d+$/,YA=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ZA=/\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$/,XA=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,KA=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,QA=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,po=t=>GA.test(t),Ye=t=>!!t&&!Number.isNaN(Number(t)),zr=t=>!!t&&Number.isInteger(Number(t)),pm=t=>t.endsWith("%")&&Ye(t.slice(0,-1)),Ja=t=>YA.test(t),WA=()=>!0,JA=t=>ZA.test(t)&&!XA.test(t),zx=()=>!1,eR=t=>KA.test(t),tR=t=>QA.test(t),nR=t=>!Ne(t)&&!Ae(t),aR=t=>Io(t,Bx,zx),Ne=t=>Mx.test(t),hs=t=>Io(t,Px,JA),gm=t=>Io(t,lR,Ye),Tb=t=>Io(t,Lx,zx),rR=t=>Io(t,Ux,tR),kc=t=>Io(t,Hx,eR),Ae=t=>Dx.test(t),Ii=t=>qo(t,Px),sR=t=>qo(t,cR),jb=t=>qo(t,Lx),oR=t=>qo(t,Bx),iR=t=>qo(t,Ux),Mc=t=>qo(t,Hx,!0),Io=(t,n,r)=>{const s=Mx.exec(t);return s?s[1]?n(s[1]):r(s[2]):!1},qo=(t,n,r=!1)=>{const s=Dx.exec(t);return s?s[1]?n(s[1]):r:!1},Lx=t=>t==="position"||t==="percentage",Ux=t=>t==="image"||t==="url",Bx=t=>t==="length"||t==="size"||t==="bg-size",Px=t=>t==="length",lR=t=>t==="number",cR=t=>t==="family-name",Hx=t=>t==="shadow",uR=()=>{const t=Yt("color"),n=Yt("font"),r=Yt("text"),s=Yt("font-weight"),i=Yt("tracking"),c=Yt("leading"),u=Yt("breakpoint"),f=Yt("container"),g=Yt("spacing"),h=Yt("radius"),v=Yt("shadow"),y=Yt("inset-shadow"),w=Yt("text-shadow"),N=Yt("drop-shadow"),E=Yt("blur"),S=Yt("perspective"),C=Yt("aspect"),A=Yt("ease"),O=Yt("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],I=()=>[...L(),Ae,Ne],ee=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto","contain","none"],Q=()=>[Ae,Ne,g],le=()=>[po,"full","auto",...Q()],ue=()=>[zr,"none","subgrid",Ae,Ne],me=()=>["auto",{span:["full",zr,Ae,Ne]},zr,Ae,Ne],re=()=>[zr,"auto",Ae,Ne],X=()=>["auto","min","max","fr",Ae,Ne],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],be=()=>["start","end","center","stretch","center-safe","end-safe"],j=()=>["auto",...Q()],Z=()=>[po,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...Q()],P=()=>[t,Ae,Ne],se=()=>[...L(),jb,Tb,{position:[Ae,Ne]}],we=()=>["no-repeat",{repeat:["","x","y","space","round"]}],T=()=>["auto","cover","contain",oR,aR,{size:[Ae,Ne]}],Y=()=>[pm,Ii,hs],D=()=>["","none","full",h,Ae,Ne],V=()=>["",Ye,Ii,hs],te=()=>["solid","dashed","dotted","double"],fe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>[Ye,pm,jb,Tb],K=()=>["","none",E,Ae,Ne],de=()=>["none",Ye,Ae,Ne],_e=()=>["none",Ye,Ae,Ne],rt=()=>[Ye,Ae,Ne],De=()=>[po,"full",...Q()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ja],breakpoint:[Ja],color:[WA],container:[Ja],"drop-shadow":[Ja],ease:["in","out","in-out"],font:[nR],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ja],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ja],shadow:[Ja],spacing:["px",Ye],text:[Ja],"text-shadow":[Ja],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",po,Ne,Ae,C]}],container:["container"],columns:[{columns:[Ye,Ne,Ae,f]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"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"],sr:["sr-only","not-sr-only"],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:I()}],overflow:[{overflow:ee()}],"overflow-x":[{"overflow-x":ee()}],"overflow-y":[{"overflow-y":ee()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:le()}],"inset-x":[{"inset-x":le()}],"inset-y":[{"inset-y":le()}],start:[{start:le()}],end:[{end:le()}],top:[{top:le()}],right:[{right:le()}],bottom:[{bottom:le()}],left:[{left:le()}],visibility:["visible","invisible","collapse"],z:[{z:[zr,"auto",Ae,Ne]}],basis:[{basis:[po,"full","auto",f,...Q()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,po,"auto","initial","none",Ne]}],grow:[{grow:["",Ye,Ae,Ne]}],shrink:[{shrink:["",Ye,Ae,Ne]}],order:[{order:[zr,"first","last","none",Ae,Ne]}],"grid-cols":[{"grid-cols":ue()}],"col-start-end":[{col:me()}],"col-start":[{"col-start":re()}],"col-end":[{"col-end":re()}],"grid-rows":[{"grid-rows":ue()}],"row-start-end":[{row:me()}],"row-start":[{"row-start":re()}],"row-end":[{"row-end":re()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":X()}],"auto-rows":[{"auto-rows":X()}],gap:[{gap:Q()}],"gap-x":[{"gap-x":Q()}],"gap-y":[{"gap-y":Q()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...be(),"normal"]}],"justify-self":[{"justify-self":["auto",...be()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...be(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...be(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...be(),"baseline"]}],"place-self":[{"place-self":["auto",...be()]}],p:[{p:Q()}],px:[{px:Q()}],py:[{py:Q()}],ps:[{ps:Q()}],pe:[{pe:Q()}],pt:[{pt:Q()}],pr:[{pr:Q()}],pb:[{pb:Q()}],pl:[{pl:Q()}],m:[{m:j()}],mx:[{mx:j()}],my:[{my:j()}],ms:[{ms:j()}],me:[{me:j()}],mt:[{mt:j()}],mr:[{mr:j()}],mb:[{mb:j()}],ml:[{ml:j()}],"space-x":[{"space-x":Q()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":Q()}],"space-y-reverse":["space-y-reverse"],size:[{size:Z()}],w:[{w:[f,"screen",...Z()]}],"min-w":[{"min-w":[f,"screen","none",...Z()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...Z()]}],h:[{h:["screen","lh",...Z()]}],"min-h":[{"min-h":["screen","lh","none",...Z()]}],"max-h":[{"max-h":["screen","lh",...Z()]}],"font-size":[{text:["base",r,Ii,hs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,Ae,gm]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",pm,Ne]}],"font-family":[{font:[sR,Ne,n]}],"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-fractions"],tracking:[{tracking:[i,Ae,Ne]}],"line-clamp":[{"line-clamp":[Ye,"none",Ae,gm]}],leading:[{leading:[c,...Q()]}],"list-image":[{"list-image":["none",Ae,Ne]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ae,Ne]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Ae,hs]}],"text-decoration-color":[{decoration:P()}],"underline-offset":[{"underline-offset":[Ye,"auto",Ae,Ne]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:Q()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ae,Ne]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ae,Ne]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:se()}],"bg-repeat":[{bg:we()}],"bg-size":[{bg:T()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},zr,Ae,Ne],radial:["",Ae,Ne],conic:[zr,Ae,Ne]},iR,rR]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:D()}],"rounded-s":[{"rounded-s":D()}],"rounded-e":[{"rounded-e":D()}],"rounded-t":[{"rounded-t":D()}],"rounded-r":[{"rounded-r":D()}],"rounded-b":[{"rounded-b":D()}],"rounded-l":[{"rounded-l":D()}],"rounded-ss":[{"rounded-ss":D()}],"rounded-se":[{"rounded-se":D()}],"rounded-ee":[{"rounded-ee":D()}],"rounded-es":[{"rounded-es":D()}],"rounded-tl":[{"rounded-tl":D()}],"rounded-tr":[{"rounded-tr":D()}],"rounded-br":[{"rounded-br":D()}],"rounded-bl":[{"rounded-bl":D()}],"border-w":[{border:V()}],"border-w-x":[{"border-x":V()}],"border-w-y":[{"border-y":V()}],"border-w-s":[{"border-s":V()}],"border-w-e":[{"border-e":V()}],"border-w-t":[{"border-t":V()}],"border-w-r":[{"border-r":V()}],"border-w-b":[{"border-b":V()}],"border-w-l":[{"border-l":V()}],"divide-x":[{"divide-x":V()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":V()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...te(),"hidden","none"]}],"divide-style":[{divide:[...te(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...te(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Ae,Ne]}],"outline-w":[{outline:["",Ye,Ii,hs]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",v,Mc,kc]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",y,Mc,kc]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:V()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[Ye,hs]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":V()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",w,Mc,kc]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[Ye,Ae,Ne]}],"mix-blend":[{"mix-blend":[...fe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":fe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":oe()}],"mask-image-linear-to-pos":[{"mask-linear-to":oe()}],"mask-image-linear-from-color":[{"mask-linear-from":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"mask-image-t-from-pos":[{"mask-t-from":oe()}],"mask-image-t-to-pos":[{"mask-t-to":oe()}],"mask-image-t-from-color":[{"mask-t-from":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"mask-image-r-from-pos":[{"mask-r-from":oe()}],"mask-image-r-to-pos":[{"mask-r-to":oe()}],"mask-image-r-from-color":[{"mask-r-from":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"mask-image-b-from-pos":[{"mask-b-from":oe()}],"mask-image-b-to-pos":[{"mask-b-to":oe()}],"mask-image-b-from-color":[{"mask-b-from":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"mask-image-l-from-pos":[{"mask-l-from":oe()}],"mask-image-l-to-pos":[{"mask-l-to":oe()}],"mask-image-l-from-color":[{"mask-l-from":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"mask-image-x-from-pos":[{"mask-x-from":oe()}],"mask-image-x-to-pos":[{"mask-x-to":oe()}],"mask-image-x-from-color":[{"mask-x-from":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"mask-image-y-from-pos":[{"mask-y-from":oe()}],"mask-image-y-to-pos":[{"mask-y-to":oe()}],"mask-image-y-from-color":[{"mask-y-from":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[Ae,Ne]}],"mask-image-radial-from-pos":[{"mask-radial-from":oe()}],"mask-image-radial-to-pos":[{"mask-radial-to":oe()}],"mask-image-radial-from-color":[{"mask-radial-from":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":L()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":oe()}],"mask-image-conic-to-pos":[{"mask-conic-to":oe()}],"mask-image-conic-from-color":[{"mask-conic-from":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:se()}],"mask-repeat":[{mask:we()}],"mask-size":[{mask:T()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ae,Ne]}],filter:[{filter:["","none",Ae,Ne]}],blur:[{blur:K()}],brightness:[{brightness:[Ye,Ae,Ne]}],contrast:[{contrast:[Ye,Ae,Ne]}],"drop-shadow":[{"drop-shadow":["","none",N,Mc,kc]}],"drop-shadow-color":[{"drop-shadow":P()}],grayscale:[{grayscale:["",Ye,Ae,Ne]}],"hue-rotate":[{"hue-rotate":[Ye,Ae,Ne]}],invert:[{invert:["",Ye,Ae,Ne]}],saturate:[{saturate:[Ye,Ae,Ne]}],sepia:[{sepia:["",Ye,Ae,Ne]}],"backdrop-filter":[{"backdrop-filter":["","none",Ae,Ne]}],"backdrop-blur":[{"backdrop-blur":K()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Ae,Ne]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Ae,Ne]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Ae,Ne]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Ae,Ne]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Ae,Ne]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Ae,Ne]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Ae,Ne]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Ae,Ne]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":Q()}],"border-spacing-x":[{"border-spacing-x":Q()}],"border-spacing-y":[{"border-spacing-y":Q()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ae,Ne]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Ae,Ne]}],ease:[{ease:["linear","initial",A,Ae,Ne]}],delay:[{delay:[Ye,Ae,Ne]}],animate:[{animate:["none",O,Ae,Ne]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,Ae,Ne]}],"perspective-origin":[{"perspective-origin":I()}],rotate:[{rotate:de()}],"rotate-x":[{"rotate-x":de()}],"rotate-y":[{"rotate-y":de()}],"rotate-z":[{"rotate-z":de()}],scale:[{scale:_e()}],"scale-x":[{"scale-x":_e()}],"scale-y":[{"scale-y":_e()}],"scale-z":[{"scale-z":_e()}],"scale-3d":["scale-3d"],skew:[{skew:rt()}],"skew-x":[{"skew-x":rt()}],"skew-y":[{"skew-y":rt()}],transform:[{transform:[Ae,Ne,"","none","gpu","cpu"]}],"transform-origin":[{origin:I()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",Ae,Ne]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":Q()}],"scroll-mx":[{"scroll-mx":Q()}],"scroll-my":[{"scroll-my":Q()}],"scroll-ms":[{"scroll-ms":Q()}],"scroll-me":[{"scroll-me":Q()}],"scroll-mt":[{"scroll-mt":Q()}],"scroll-mr":[{"scroll-mr":Q()}],"scroll-mb":[{"scroll-mb":Q()}],"scroll-ml":[{"scroll-ml":Q()}],"scroll-p":[{"scroll-p":Q()}],"scroll-px":[{"scroll-px":Q()}],"scroll-py":[{"scroll-py":Q()}],"scroll-ps":[{"scroll-ps":Q()}],"scroll-pe":[{"scroll-pe":Q()}],"scroll-pt":[{"scroll-pt":Q()}],"scroll-pr":[{"scroll-pr":Q()}],"scroll-pb":[{"scroll-pb":Q()}],"scroll-pl":[{"scroll-pl":Q()}],"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",Ae,Ne]}],fill:[{fill:["none",...P()]}],"stroke-w":[{stroke:[Ye,Ii,hs,gm]}],stroke:[{stroke:["none",...P()]}],"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-x","border-w-y","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-x","border-color-y","border-color-s","border-color-e","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"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"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Vx=FA(uR);function qm(...t){return Vx(Eh(t))}const dR=[{to:"/manager",label:"Dashboard",icon:$N},{to:"/manager/instances",label:"Instâncias",icon:hA}];function fR(){const t=new Date().getFullYear();return p.jsxs("div",{className:"hidden md:flex bg-sidebar text-sidebar-foreground flex-col w-56 border-r border-sidebar-border",children:[p.jsx("div",{className:"h-16 flex items-center px-4 border-b border-sidebar-border",children:p.jsx("h2",{className:"text-lg font-bold text-primary",children:"Evolution GO"})}),p.jsx("nav",{className:"space-y-1.5 flex-1 px-2 py-4",children:dR.map(n=>p.jsx(Ex,{to:n.to,end:n.to==="/manager",className:({isActive:r})=>qm("flex items-center gap-3 px-3 py-2.5 rounded-md transition-all",r?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-accent"),children:({isActive:r})=>p.jsxs(p.Fragment,{children:[p.jsx(n.icon,{className:qm("flex-shrink-0 h-5 w-5",r&&"text-primary")}),p.jsx("span",{className:"font-medium",children:n.label})]})},n.to))}),p.jsxs("div",{className:"mt-auto p-4 border-t border-sidebar-border",children:[p.jsx("div",{className:"text-sm text-primary font-medium",children:"Evolution GO"}),p.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["© ",t," All rights reserved"]})]})]})}const Ob=t=>{let n;const r=new Set,s=(h,v)=>{const y=typeof h=="function"?h(n):h;if(!Object.is(y,n)){const w=n;n=v??(typeof y!="object"||y===null)?y:Object.assign({},n,y),r.forEach(N=>N(n,w))}},i=()=>n,f={setState:s,getState:i,getInitialState:()=>g,subscribe:h=>(r.add(h),()=>r.delete(h))},g=n=t(s,i,f);return f},mR=(t=>t?Ob(t):Ob),hR=t=>t;function pR(t,n=hR){const r=ae.useSyncExternalStore(t.subscribe,ae.useCallback(()=>n(t.getState()),[t,n]),ae.useCallback(()=>n(t.getInitialState()),[t,n]));return ae.useDebugValue(r),r}const gR=t=>{const n=mR(t),r=s=>pR(n,s);return Object.assign(r,n),r},Ix=(t=>gR);function yR(t,n){let r;try{r=t()}catch{return}return{getItem:i=>{var c;const u=g=>g===null?null:JSON.parse(g,void 0),f=(c=r.getItem(i))!=null?c:null;return f instanceof Promise?f.then(u):u(f)},setItem:(i,c)=>r.setItem(i,JSON.stringify(c,void 0)),removeItem:i=>r.removeItem(i)}}const Fm=t=>n=>{try{const r=t(n);return r instanceof Promise?r:{then(s){return Fm(s)(r)},catch(s){return this}}}catch(r){return{then(s){return this},catch(s){return Fm(s)(r)}}}},vR=(t,n)=>(r,s,i)=>{let c={storage:yR(()=>localStorage),partialize:S=>S,version:0,merge:(S,C)=>({...C,...S}),...n},u=!1;const f=new Set,g=new Set;let h=c.storage;if(!h)return t((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${c.name}', the given storage is currently unavailable.`),r(...S)},s,i);const v=()=>{const S=c.partialize({...s()});return h.setItem(c.name,{state:S,version:c.version})},y=i.setState;i.setState=(S,C)=>(y(S,C),v());const w=t((...S)=>(r(...S),v()),s,i);i.getInitialState=()=>w;let N;const E=()=>{var S,C;if(!h)return;u=!1,f.forEach(O=>{var R;return O((R=s())!=null?R:w)});const A=((C=c.onRehydrateStorage)==null?void 0:C.call(c,(S=s())!=null?S:w))||void 0;return Fm(h.getItem.bind(h))(c.name).then(O=>{if(O)if(typeof O.version=="number"&&O.version!==c.version){if(c.migrate){const R=c.migrate(O.state,O.version);return R instanceof Promise?R.then(L=>[!0,L]):[!0,R]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,O.state];return[!1,void 0]}).then(O=>{var R;const[L,I]=O;if(N=c.merge(I,(R=s())!=null?R:w),r(N,!0),L)return v()}).then(()=>{A==null||A(N,void 0),N=s(),u=!0,g.forEach(O=>O(N))}).catch(O=>{A==null||A(void 0,O)})};return i.persist={setOptions:S=>{c={...c,...S},S.storage&&(h=S.storage)},clearStorage:()=>{h==null||h.removeItem(c.name)},getOptions:()=>c,rehydrate:()=>E(),hasHydrated:()=>u,onHydrate:S=>(f.add(S),()=>{f.delete(S)}),onFinishHydration:S=>(g.add(S),()=>{g.delete(S)})},c.skipHydration||E(),N||w},bR=vR;function qx(t,n){return function(){return t.apply(n,arguments)}}const{toString:xR}=Object.prototype,{getPrototypeOf:Ch}=Object,{iterator:Au,toStringTag:Fx}=Symbol,Ru=(t=>n=>{const r=xR.call(n);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),pa=t=>(t=t.toLowerCase(),n=>Ru(n)===t),Tu=t=>n=>typeof n===t,{isArray:Fo}=Array,To=Tu("undefined");function cl(t){return t!==null&&!To(t)&&t.constructor!==null&&!To(t.constructor)&&Rn(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const $x=pa("ArrayBuffer");function wR(t){let n;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?n=ArrayBuffer.isView(t):n=t&&t.buffer&&$x(t.buffer),n}const SR=Tu("string"),Rn=Tu("function"),Gx=Tu("number"),ul=t=>t!==null&&typeof t=="object",ER=t=>t===!0||t===!1,Gc=t=>{if(Ru(t)!=="object")return!1;const n=Ch(t);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Fx in t)&&!(Au in t)},_R=t=>{if(!ul(t)||cl(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},CR=pa("Date"),NR=pa("File"),AR=pa("Blob"),RR=pa("FileList"),TR=t=>ul(t)&&Rn(t.pipe),jR=t=>{let n;return t&&(typeof FormData=="function"&&t instanceof FormData||Rn(t.append)&&((n=Ru(t))==="formdata"||n==="object"&&Rn(t.toString)&&t.toString()==="[object FormData]"))},OR=pa("URLSearchParams"),[kR,MR,DR,zR]=["ReadableStream","Request","Response","Headers"].map(pa),LR=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function dl(t,n,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let s,i;if(typeof t!="object"&&(t=[t]),Fo(t))for(s=0,i=t.length;s<i;s++)n.call(null,t[s],s,t);else{if(cl(t))return;const c=r?Object.getOwnPropertyNames(t):Object.keys(t),u=c.length;let f;for(s=0;s<u;s++)f=c[s],n.call(null,t[f],f,t)}}function Yx(t,n){if(cl(t))return null;n=n.toLowerCase();const r=Object.keys(t);let s=r.length,i;for(;s-- >0;)if(i=r[s],n===i.toLowerCase())return i;return null}const gs=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Zx=t=>!To(t)&&t!==gs;function $m(){const{caseless:t,skipUndefined:n}=Zx(this)&&this||{},r={},s=(i,c)=>{const u=t&&Yx(r,c)||c;Gc(r[u])&&Gc(i)?r[u]=$m(r[u],i):Gc(i)?r[u]=$m({},i):Fo(i)?r[u]=i.slice():(!n||!To(i))&&(r[u]=i)};for(let i=0,c=arguments.length;i<c;i++)arguments[i]&&dl(arguments[i],s);return r}const UR=(t,n,r,{allOwnKeys:s}={})=>(dl(n,(i,c)=>{r&&Rn(i)?t[c]=qx(i,r):t[c]=i},{allOwnKeys:s}),t),BR=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),PR=(t,n,r,s)=>{t.prototype=Object.create(n.prototype,s),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:n.prototype}),r&&Object.assign(t.prototype,r)},HR=(t,n,r,s)=>{let i,c,u;const f={};if(n=n||{},t==null)return n;do{for(i=Object.getOwnPropertyNames(t),c=i.length;c-- >0;)u=i[c],(!s||s(u,t,n))&&!f[u]&&(n[u]=t[u],f[u]=!0);t=r!==!1&&Ch(t)}while(t&&(!r||r(t,n))&&t!==Object.prototype);return n},VR=(t,n,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=n.length;const s=t.indexOf(n,r);return s!==-1&&s===r},IR=t=>{if(!t)return null;if(Fo(t))return t;let n=t.length;if(!Gx(n))return null;const r=new Array(n);for(;n-- >0;)r[n]=t[n];return r},qR=(t=>n=>t&&n instanceof t)(typeof Uint8Array<"u"&&Ch(Uint8Array)),FR=(t,n)=>{const s=(t&&t[Au]).call(t);let i;for(;(i=s.next())&&!i.done;){const c=i.value;n.call(t,c[0],c[1])}},$R=(t,n)=>{let r;const s=[];for(;(r=t.exec(n))!==null;)s.push(r);return s},GR=pa("HTMLFormElement"),YR=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,s,i){return s.toUpperCase()+i}),kb=(({hasOwnProperty:t})=>(n,r)=>t.call(n,r))(Object.prototype),ZR=pa("RegExp"),Xx=(t,n)=>{const r=Object.getOwnPropertyDescriptors(t),s={};dl(r,(i,c)=>{let u;(u=n(i,c,t))!==!1&&(s[c]=u||i)}),Object.defineProperties(t,s)},XR=t=>{Xx(t,(n,r)=>{if(Rn(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const s=t[r];if(Rn(s)){if(n.enumerable=!1,"writable"in n){n.writable=!1;return}n.set||(n.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},KR=(t,n)=>{const r={},s=i=>{i.forEach(c=>{r[c]=!0})};return Fo(t)?s(t):s(String(t).split(n)),r},QR=()=>{},WR=(t,n)=>t!=null&&Number.isFinite(t=+t)?t:n;function JR(t){return!!(t&&Rn(t.append)&&t[Fx]==="FormData"&&t[Au])}const eT=t=>{const n=new Array(10),r=(s,i)=>{if(ul(s)){if(n.indexOf(s)>=0)return;if(cl(s))return s;if(!("toJSON"in s)){n[i]=s;const c=Fo(s)?[]:{};return dl(s,(u,f)=>{const g=r(u,i+1);!To(g)&&(c[f]=g)}),n[i]=void 0,c}}return s};return r(t,0)},tT=pa("AsyncFunction"),nT=t=>t&&(ul(t)||Rn(t))&&Rn(t.then)&&Rn(t.catch),Kx=((t,n)=>t?setImmediate:n?((r,s)=>(gs.addEventListener("message",({source:i,data:c})=>{i===gs&&c===r&&s.length&&s.shift()()},!1),i=>{s.push(i),gs.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Rn(gs.postMessage)),aT=typeof queueMicrotask<"u"?queueMicrotask.bind(gs):typeof process<"u"&&process.nextTick||Kx,rT=t=>t!=null&&Rn(t[Au]),W={isArray:Fo,isArrayBuffer:$x,isBuffer:cl,isFormData:jR,isArrayBufferView:wR,isString:SR,isNumber:Gx,isBoolean:ER,isObject:ul,isPlainObject:Gc,isEmptyObject:_R,isReadableStream:kR,isRequest:MR,isResponse:DR,isHeaders:zR,isUndefined:To,isDate:CR,isFile:NR,isBlob:AR,isRegExp:ZR,isFunction:Rn,isStream:TR,isURLSearchParams:OR,isTypedArray:qR,isFileList:RR,forEach:dl,merge:$m,extend:UR,trim:LR,stripBOM:BR,inherits:PR,toFlatObject:HR,kindOf:Ru,kindOfTest:pa,endsWith:VR,toArray:IR,forEachEntry:FR,matchAll:$R,isHTMLForm:GR,hasOwnProperty:kb,hasOwnProp:kb,reduceDescriptors:Xx,freezeMethods:XR,toObjectSet:KR,toCamelCase:YR,noop:QR,toFiniteNumber:WR,findKey:Yx,global:gs,isContextDefined:Zx,isSpecCompliantForm:JR,toJSONObject:eT,isAsyncFn:tT,isThenable:nT,setImmediate:Kx,asap:aT,isIterable:rT};function $e(t,n,r,s,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",n&&(this.code=n),r&&(this.config=r),s&&(this.request=s),i&&(this.response=i,this.status=i.status?i.status:null)}W.inherits($e,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:W.toJSONObject(this.config),code:this.code,status:this.status}}});const Qx=$e.prototype,Wx={};["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(t=>{Wx[t]={value:t}});Object.defineProperties($e,Wx);Object.defineProperty(Qx,"isAxiosError",{value:!0});$e.from=(t,n,r,s,i,c)=>{const u=Object.create(Qx);W.toFlatObject(t,u,function(v){return v!==Error.prototype},h=>h!=="isAxiosError");const f=t&&t.message?t.message:"Error",g=n==null&&t?t.code:n;return $e.call(u,f,g,r,s,i),t&&u.cause==null&&Object.defineProperty(u,"cause",{value:t,configurable:!0}),u.name=t&&t.name||"Error",c&&Object.assign(u,c),u};const sT=null;function Gm(t){return W.isPlainObject(t)||W.isArray(t)}function Jx(t){return W.endsWith(t,"[]")?t.slice(0,-2):t}function Mb(t,n,r){return t?t.concat(n).map(function(i,c){return i=Jx(i),!r&&c?"["+i+"]":i}).join(r?".":""):n}function oT(t){return W.isArray(t)&&!t.some(Gm)}const iT=W.toFlatObject(W,{},null,function(n){return/^is[A-Z]/.test(n)});function ju(t,n,r){if(!W.isObject(t))throw new TypeError("target must be an object");n=n||new FormData,r=W.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,C){return!W.isUndefined(C[S])});const s=r.metaTokens,i=r.visitor||v,c=r.dots,u=r.indexes,g=(r.Blob||typeof Blob<"u"&&Blob)&&W.isSpecCompliantForm(n);if(!W.isFunction(i))throw new TypeError("visitor must be a function");function h(E){if(E===null)return"";if(W.isDate(E))return E.toISOString();if(W.isBoolean(E))return E.toString();if(!g&&W.isBlob(E))throw new $e("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(E)||W.isTypedArray(E)?g&&typeof Blob=="function"?new Blob([E]):Buffer.from(E):E}function v(E,S,C){let A=E;if(E&&!C&&typeof E=="object"){if(W.endsWith(S,"{}"))S=s?S:S.slice(0,-2),E=JSON.stringify(E);else if(W.isArray(E)&&oT(E)||(W.isFileList(E)||W.endsWith(S,"[]"))&&(A=W.toArray(E)))return S=Jx(S),A.forEach(function(R,L){!(W.isUndefined(R)||R===null)&&n.append(u===!0?Mb([S],L,c):u===null?S:S+"[]",h(R))}),!1}return Gm(E)?!0:(n.append(Mb(C,S,c),h(E)),!1)}const y=[],w=Object.assign(iT,{defaultVisitor:v,convertValue:h,isVisitable:Gm});function N(E,S){if(!W.isUndefined(E)){if(y.indexOf(E)!==-1)throw Error("Circular reference detected in "+S.join("."));y.push(E),W.forEach(E,function(A,O){(!(W.isUndefined(A)||A===null)&&i.call(n,A,W.isString(O)?O.trim():O,S,w))===!0&&N(A,S?S.concat(O):[O])}),y.pop()}}if(!W.isObject(t))throw new TypeError("data must be an object");return N(t),n}function Db(t){const n={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return n[s]})}function Nh(t,n){this._pairs=[],t&&ju(t,this,n)}const e1=Nh.prototype;e1.append=function(n,r){this._pairs.push([n,r])};e1.toString=function(n){const r=n?function(s){return n.call(this,s,Db)}:Db;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function lT(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function t1(t,n,r){if(!n)return t;const s=r&&r.encode||lT;W.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let c;if(i?c=i(n,r):c=W.isURLSearchParams(n)?n.toString():new Nh(n,r).toString(s),c){const u=t.indexOf("#");u!==-1&&(t=t.slice(0,u)),t+=(t.indexOf("?")===-1?"?":"&")+c}return t}class zb{constructor(){this.handlers=[]}use(n,r,s){return this.handlers.push({fulfilled:n,rejected:r,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(n){this.handlers[n]&&(this.handlers[n]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(n){W.forEach(this.handlers,function(s){s!==null&&n(s)})}}const n1={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},cT=typeof URLSearchParams<"u"?URLSearchParams:Nh,uT=typeof FormData<"u"?FormData:null,dT=typeof Blob<"u"?Blob:null,fT={isBrowser:!0,classes:{URLSearchParams:cT,FormData:uT,Blob:dT},protocols:["http","https","file","blob","url","data"]},Ah=typeof window<"u"&&typeof document<"u",Ym=typeof navigator=="object"&&navigator||void 0,mT=Ah&&(!Ym||["ReactNative","NativeScript","NS"].indexOf(Ym.product)<0),hT=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",pT=Ah&&window.location.href||"http://localhost",gT=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ah,hasStandardBrowserEnv:mT,hasStandardBrowserWebWorkerEnv:hT,navigator:Ym,origin:pT},Symbol.toStringTag,{value:"Module"})),un={...gT,...fT};function yT(t,n){return ju(t,new un.classes.URLSearchParams,{visitor:function(r,s,i,c){return un.isNode&&W.isBuffer(r)?(this.append(s,r.toString("base64")),!1):c.defaultVisitor.apply(this,arguments)},...n})}function vT(t){return W.matchAll(/\w+|\[(\w*)]/g,t).map(n=>n[0]==="[]"?"":n[1]||n[0])}function bT(t){const n={},r=Object.keys(t);let s;const i=r.length;let c;for(s=0;s<i;s++)c=r[s],n[c]=t[c];return n}function a1(t){function n(r,s,i,c){let u=r[c++];if(u==="__proto__")return!0;const f=Number.isFinite(+u),g=c>=r.length;return u=!u&&W.isArray(i)?i.length:u,g?(W.hasOwnProp(i,u)?i[u]=[i[u],s]:i[u]=s,!f):((!i[u]||!W.isObject(i[u]))&&(i[u]=[]),n(r,s,i[u],c)&&W.isArray(i[u])&&(i[u]=bT(i[u])),!f)}if(W.isFormData(t)&&W.isFunction(t.entries)){const r={};return W.forEachEntry(t,(s,i)=>{n(vT(s),i,r,0)}),r}return null}function xT(t,n,r){if(W.isString(t))try{return(n||JSON.parse)(t),W.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(r||JSON.stringify)(t)}const fl={transitional:n1,adapter:["xhr","http","fetch"],transformRequest:[function(n,r){const s=r.getContentType()||"",i=s.indexOf("application/json")>-1,c=W.isObject(n);if(c&&W.isHTMLForm(n)&&(n=new FormData(n)),W.isFormData(n))return i?JSON.stringify(a1(n)):n;if(W.isArrayBuffer(n)||W.isBuffer(n)||W.isStream(n)||W.isFile(n)||W.isBlob(n)||W.isReadableStream(n))return n;if(W.isArrayBufferView(n))return n.buffer;if(W.isURLSearchParams(n))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),n.toString();let f;if(c){if(s.indexOf("application/x-www-form-urlencoded")>-1)return yT(n,this.formSerializer).toString();if((f=W.isFileList(n))||s.indexOf("multipart/form-data")>-1){const g=this.env&&this.env.FormData;return ju(f?{"files[]":n}:n,g&&new g,this.formSerializer)}}return c||i?(r.setContentType("application/json",!1),xT(n)):n}],transformResponse:[function(n){const r=this.transitional||fl.transitional,s=r&&r.forcedJSONParsing,i=this.responseType==="json";if(W.isResponse(n)||W.isReadableStream(n))return n;if(n&&W.isString(n)&&(s&&!this.responseType||i)){const u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(n,this.parseReviver)}catch(f){if(u)throw f.name==="SyntaxError"?$e.from(f,$e.ERR_BAD_RESPONSE,this,null,this.response):f}}return n}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:un.classes.FormData,Blob:un.classes.Blob},validateStatus:function(n){return n>=200&&n<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};W.forEach(["delete","get","head","post","put","patch"],t=>{fl.headers[t]={}});const wT=W.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"]),ST=t=>{const n={};let r,s,i;return t&&t.split(`+`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),s=u.substring(i+1).trim(),!(!r||n[r]&&wT[r])&&(r==="set-cookie"?n[r]?n[r].push(s):n[r]=[s]:n[r]=n[r]?n[r]+", "+s:s)}),n},Lb=Symbol("internals");function qi(t){return t&&String(t).trim().toLowerCase()}function Yc(t){return t===!1||t==null?t:W.isArray(t)?t.map(Yc):String(t)}function ET(t){const n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(t);)n[s[1]]=s[2];return n}const _T=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ym(t,n,r,s,i){if(W.isFunction(s))return s.call(this,n,r);if(i&&(n=r),!!W.isString(n)){if(W.isString(s))return n.indexOf(s)!==-1;if(W.isRegExp(s))return s.test(n)}}function CT(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(n,r,s)=>r.toUpperCase()+s)}function NT(t,n){const r=W.toCamelCase(" "+n);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+r,{value:function(i,c,u){return this[s].call(this,n,i,c,u)},configurable:!0})})}let Tn=class{constructor(n){n&&this.set(n)}set(n,r,s){const i=this;function c(f,g,h){const v=qi(g);if(!v)throw new Error("header name must be a non-empty string");const y=W.findKey(i,v);(!y||i[y]===void 0||h===!0||h===void 0&&i[y]!==!1)&&(i[y||g]=Yc(f))}const u=(f,g)=>W.forEach(f,(h,v)=>c(h,v,g));if(W.isPlainObject(n)||n instanceof this.constructor)u(n,r);else if(W.isString(n)&&(n=n.trim())&&!_T(n))u(ST(n),r);else if(W.isObject(n)&&W.isIterable(n)){let f={},g,h;for(const v of n){if(!W.isArray(v))throw TypeError("Object iterator must return a key-value pair");f[h=v[0]]=(g=f[h])?W.isArray(g)?[...g,v[1]]:[g,v[1]]:v[1]}u(f,r)}else n!=null&&c(r,n,s);return this}get(n,r){if(n=qi(n),n){const s=W.findKey(this,n);if(s){const i=this[s];if(!r)return i;if(r===!0)return ET(i);if(W.isFunction(r))return r.call(this,i,s);if(W.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(n,r){if(n=qi(n),n){const s=W.findKey(this,n);return!!(s&&this[s]!==void 0&&(!r||ym(this,this[s],s,r)))}return!1}delete(n,r){const s=this;let i=!1;function c(u){if(u=qi(u),u){const f=W.findKey(s,u);f&&(!r||ym(s,s[f],f,r))&&(delete s[f],i=!0)}}return W.isArray(n)?n.forEach(c):c(n),i}clear(n){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const c=r[s];(!n||ym(this,this[c],c,n,!0))&&(delete this[c],i=!0)}return i}normalize(n){const r=this,s={};return W.forEach(this,(i,c)=>{const u=W.findKey(s,c);if(u){r[u]=Yc(i),delete r[c];return}const f=n?CT(c):String(c).trim();f!==c&&delete r[c],r[f]=Yc(i),s[f]=!0}),this}concat(...n){return this.constructor.concat(this,...n)}toJSON(n){const r=Object.create(null);return W.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=n&&W.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([n,r])=>n+": "+r).join(`+`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(n){return n instanceof this?n:new this(n)}static concat(n,...r){const s=new this(n);return r.forEach(i=>s.set(i)),s}static accessor(n){const s=(this[Lb]=this[Lb]={accessors:{}}).accessors,i=this.prototype;function c(u){const f=qi(u);s[f]||(NT(i,u),s[f]=!0)}return W.isArray(n)?n.forEach(c):c(n),this}};Tn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);W.reduceDescriptors(Tn.prototype,({value:t},n)=>{let r=n[0].toUpperCase()+n.slice(1);return{get:()=>t,set(s){this[r]=s}}});W.freezeMethods(Tn);function vm(t,n){const r=this||fl,s=n||r,i=Tn.from(s.headers);let c=s.data;return W.forEach(t,function(f){c=f.call(r,c,i.normalize(),n?n.status:void 0)}),i.normalize(),c}function r1(t){return!!(t&&t.__CANCEL__)}function $o(t,n,r){$e.call(this,t??"canceled",$e.ERR_CANCELED,n,r),this.name="CanceledError"}W.inherits($o,$e,{__CANCEL__:!0});function s1(t,n,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):n(new $e("Request failed with status code "+r.status,[$e.ERR_BAD_REQUEST,$e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function AT(t){const n=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return n&&n[1]||""}function RT(t,n){t=t||10;const r=new Array(t),s=new Array(t);let i=0,c=0,u;return n=n!==void 0?n:1e3,function(g){const h=Date.now(),v=s[c];u||(u=h),r[i]=g,s[i]=h;let y=c,w=0;for(;y!==i;)w+=r[y++],y=y%t;if(i=(i+1)%t,i===c&&(c=(c+1)%t),h-u<n)return;const N=v&&h-v;return N?Math.round(w*1e3/N):void 0}}function TT(t,n){let r=0,s=1e3/n,i,c;const u=(h,v=Date.now())=>{r=v,i=null,c&&(clearTimeout(c),c=null),t(...h)};return[(...h)=>{const v=Date.now(),y=v-r;y>=s?u(h,v):(i=h,c||(c=setTimeout(()=>{c=null,u(i)},s-y)))},()=>i&&u(i)]}const eu=(t,n,r=3)=>{let s=0;const i=RT(50,250);return TT(c=>{const u=c.loaded,f=c.lengthComputable?c.total:void 0,g=u-s,h=i(g),v=u<=f;s=u;const y={loaded:u,total:f,progress:f?u/f:void 0,bytes:g,rate:h||void 0,estimated:h&&f&&v?(f-u)/h:void 0,event:c,lengthComputable:f!=null,[n?"download":"upload"]:!0};t(y)},r)},Ub=(t,n)=>{const r=t!=null;return[s=>n[0]({lengthComputable:r,total:t,loaded:s}),n[1]]},Bb=t=>(...n)=>W.asap(()=>t(...n)),jT=un.hasStandardBrowserEnv?((t,n)=>r=>(r=new URL(r,un.origin),t.protocol===r.protocol&&t.host===r.host&&(n||t.port===r.port)))(new URL(un.origin),un.navigator&&/(msie|trident)/i.test(un.navigator.userAgent)):()=>!0,OT=un.hasStandardBrowserEnv?{write(t,n,r,s,i,c,u){if(typeof document>"u")return;const f=[`${t}=${encodeURIComponent(n)}`];W.isNumber(r)&&f.push(`expires=${new Date(r).toUTCString()}`),W.isString(s)&&f.push(`path=${s}`),W.isString(i)&&f.push(`domain=${i}`),c===!0&&f.push("secure"),W.isString(u)&&f.push(`SameSite=${u}`),document.cookie=f.join("; ")},read(t){if(typeof document>"u")return null;const n=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return n?decodeURIComponent(n[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function kT(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function MT(t,n){return n?t.replace(/\/?\/$/,"")+"/"+n.replace(/^\/+/,""):t}function o1(t,n,r){let s=!kT(n);return t&&(s||r==!1)?MT(t,n):n}const Pb=t=>t instanceof Tn?{...t}:t;function bs(t,n){n=n||{};const r={};function s(h,v,y,w){return W.isPlainObject(h)&&W.isPlainObject(v)?W.merge.call({caseless:w},h,v):W.isPlainObject(v)?W.merge({},v):W.isArray(v)?v.slice():v}function i(h,v,y,w){if(W.isUndefined(v)){if(!W.isUndefined(h))return s(void 0,h,y,w)}else return s(h,v,y,w)}function c(h,v){if(!W.isUndefined(v))return s(void 0,v)}function u(h,v){if(W.isUndefined(v)){if(!W.isUndefined(h))return s(void 0,h)}else return s(void 0,v)}function f(h,v,y){if(y in n)return s(h,v);if(y in t)return s(void 0,h)}const g={url:c,method:c,data:c,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:f,headers:(h,v,y)=>i(Pb(h),Pb(v),y,!0)};return W.forEach(Object.keys({...t,...n}),function(v){const y=g[v]||i,w=y(t[v],n[v],v);W.isUndefined(w)&&y!==f||(r[v]=w)}),r}const i1=t=>{const n=bs({},t);let{data:r,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:c,headers:u,auth:f}=n;if(n.headers=u=Tn.from(u),n.url=t1(o1(n.baseURL,n.url,n.allowAbsoluteUrls),t.params,t.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):""))),W.isFormData(r)){if(un.hasStandardBrowserEnv||un.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if(W.isFunction(r.getHeaders)){const g=r.getHeaders(),h=["content-type","content-length"];Object.entries(g).forEach(([v,y])=>{h.includes(v.toLowerCase())&&u.set(v,y)})}}if(un.hasStandardBrowserEnv&&(s&&W.isFunction(s)&&(s=s(n)),s||s!==!1&&jT(n.url))){const g=i&&c&&OT.read(c);g&&u.set(i,g)}return n},DT=typeof XMLHttpRequest<"u",zT=DT&&function(t){return new Promise(function(r,s){const i=i1(t);let c=i.data;const u=Tn.from(i.headers).normalize();let{responseType:f,onUploadProgress:g,onDownloadProgress:h}=i,v,y,w,N,E;function S(){N&&N(),E&&E(),i.cancelToken&&i.cancelToken.unsubscribe(v),i.signal&&i.signal.removeEventListener("abort",v)}let C=new XMLHttpRequest;C.open(i.method.toUpperCase(),i.url,!0),C.timeout=i.timeout;function A(){if(!C)return;const R=Tn.from("getAllResponseHeaders"in C&&C.getAllResponseHeaders()),I={data:!f||f==="text"||f==="json"?C.responseText:C.response,status:C.status,statusText:C.statusText,headers:R,config:t,request:C};s1(function(U){r(U),S()},function(U){s(U),S()},I),C=null}"onloadend"in C?C.onloadend=A:C.onreadystatechange=function(){!C||C.readyState!==4||C.status===0&&!(C.responseURL&&C.responseURL.indexOf("file:")===0)||setTimeout(A)},C.onabort=function(){C&&(s(new $e("Request aborted",$e.ECONNABORTED,t,C)),C=null)},C.onerror=function(L){const I=L&&L.message?L.message:"Network Error",ee=new $e(I,$e.ERR_NETWORK,t,C);ee.event=L||null,s(ee),C=null},C.ontimeout=function(){let L=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const I=i.transitional||n1;i.timeoutErrorMessage&&(L=i.timeoutErrorMessage),s(new $e(L,I.clarifyTimeoutError?$e.ETIMEDOUT:$e.ECONNABORTED,t,C)),C=null},c===void 0&&u.setContentType(null),"setRequestHeader"in C&&W.forEach(u.toJSON(),function(L,I){C.setRequestHeader(I,L)}),W.isUndefined(i.withCredentials)||(C.withCredentials=!!i.withCredentials),f&&f!=="json"&&(C.responseType=i.responseType),h&&([w,E]=eu(h,!0),C.addEventListener("progress",w)),g&&C.upload&&([y,N]=eu(g),C.upload.addEventListener("progress",y),C.upload.addEventListener("loadend",N)),(i.cancelToken||i.signal)&&(v=R=>{C&&(s(!R||R.type?new $o(null,t,C):R),C.abort(),C=null)},i.cancelToken&&i.cancelToken.subscribe(v),i.signal&&(i.signal.aborted?v():i.signal.addEventListener("abort",v)));const O=AT(i.url);if(O&&un.protocols.indexOf(O)===-1){s(new $e("Unsupported protocol "+O+":",$e.ERR_BAD_REQUEST,t));return}C.send(c||null)})},LT=(t,n)=>{const{length:r}=t=t?t.filter(Boolean):[];if(n||r){let s=new AbortController,i;const c=function(h){if(!i){i=!0,f();const v=h instanceof Error?h:this.reason;s.abort(v instanceof $e?v:new $o(v instanceof Error?v.message:v))}};let u=n&&setTimeout(()=>{u=null,c(new $e(`timeout ${n} of ms exceeded`,$e.ETIMEDOUT))},n);const f=()=>{t&&(u&&clearTimeout(u),u=null,t.forEach(h=>{h.unsubscribe?h.unsubscribe(c):h.removeEventListener("abort",c)}),t=null)};t.forEach(h=>h.addEventListener("abort",c));const{signal:g}=s;return g.unsubscribe=()=>W.asap(f),g}},UT=function*(t,n){let r=t.byteLength;if(r<n){yield t;return}let s=0,i;for(;s<r;)i=s+n,yield t.slice(s,i),s=i},BT=async function*(t,n){for await(const r of PT(t))yield*UT(r,n)},PT=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const n=t.getReader();try{for(;;){const{done:r,value:s}=await n.read();if(r)break;yield s}}finally{await n.cancel()}},Hb=(t,n,r,s)=>{const i=BT(t,n);let c=0,u,f=g=>{u||(u=!0,s&&s(g))};return new ReadableStream({async pull(g){try{const{done:h,value:v}=await i.next();if(h){f(),g.close();return}let y=v.byteLength;if(r){let w=c+=y;r(w)}g.enqueue(new Uint8Array(v))}catch(h){throw f(h),h}},cancel(g){return f(g),i.return()}},{highWaterMark:2})},Vb=64*1024,{isFunction:Dc}=W,HT=(({Request:t,Response:n})=>({Request:t,Response:n}))(W.global),{ReadableStream:Ib,TextEncoder:qb}=W.global,Fb=(t,...n)=>{try{return!!t(...n)}catch{return!1}},VT=t=>{t=W.merge.call({skipUndefined:!0},HT,t);const{fetch:n,Request:r,Response:s}=t,i=n?Dc(n):typeof fetch=="function",c=Dc(r),u=Dc(s);if(!i)return!1;const f=i&&Dc(Ib),g=i&&(typeof qb=="function"?(E=>S=>E.encode(S))(new qb):async E=>new Uint8Array(await new r(E).arrayBuffer())),h=c&&f&&Fb(()=>{let E=!1;const S=new r(un.origin,{body:new Ib,method:"POST",get duplex(){return E=!0,"half"}}).headers.has("Content-Type");return E&&!S}),v=u&&f&&Fb(()=>W.isReadableStream(new s("").body)),y={stream:v&&(E=>E.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(E=>{!y[E]&&(y[E]=(S,C)=>{let A=S&&S[E];if(A)return A.call(S);throw new $e(`Response type '${E}' is not supported`,$e.ERR_NOT_SUPPORT,C)})});const w=async E=>{if(E==null)return 0;if(W.isBlob(E))return E.size;if(W.isSpecCompliantForm(E))return(await new r(un.origin,{method:"POST",body:E}).arrayBuffer()).byteLength;if(W.isArrayBufferView(E)||W.isArrayBuffer(E))return E.byteLength;if(W.isURLSearchParams(E)&&(E=E+""),W.isString(E))return(await g(E)).byteLength},N=async(E,S)=>{const C=W.toFiniteNumber(E.getContentLength());return C??w(S)};return async E=>{let{url:S,method:C,data:A,signal:O,cancelToken:R,timeout:L,onDownloadProgress:I,onUploadProgress:ee,responseType:U,headers:Q,withCredentials:le="same-origin",fetchOptions:ue}=i1(E),me=n||fetch;U=U?(U+"").toLowerCase():"text";let re=LT([O,R&&R.toAbortSignal()],L),X=null;const he=re&&re.unsubscribe&&(()=>{re.unsubscribe()});let be;try{if(ee&&h&&C!=="get"&&C!=="head"&&(be=await N(Q,A))!==0){let T=new r(S,{method:"POST",body:A,duplex:"half"}),Y;if(W.isFormData(A)&&(Y=T.headers.get("content-type"))&&Q.setContentType(Y),T.body){const[D,V]=Ub(be,eu(Bb(ee)));A=Hb(T.body,Vb,D,V)}}W.isString(le)||(le=le?"include":"omit");const j=c&&"credentials"in r.prototype,Z={...ue,signal:re,method:C.toUpperCase(),headers:Q.normalize().toJSON(),body:A,duplex:"half",credentials:j?le:void 0};X=c&&new r(S,Z);let P=await(c?me(X,ue):me(S,Z));const se=v&&(U==="stream"||U==="response");if(v&&(I||se&&he)){const T={};["status","statusText","headers"].forEach(te=>{T[te]=P[te]});const Y=W.toFiniteNumber(P.headers.get("content-length")),[D,V]=I&&Ub(Y,eu(Bb(I),!0))||[];P=new s(Hb(P.body,Vb,D,()=>{V&&V(),he&&he()}),T)}U=U||"text";let we=await y[W.findKey(y,U)||"text"](P,E);return!se&&he&&he(),await new Promise((T,Y)=>{s1(T,Y,{data:we,headers:Tn.from(P.headers),status:P.status,statusText:P.statusText,config:E,request:X})})}catch(j){throw he&&he(),j&&j.name==="TypeError"&&/Load failed|fetch/i.test(j.message)?Object.assign(new $e("Network Error",$e.ERR_NETWORK,E,X),{cause:j.cause||j}):$e.from(j,j&&j.code,E,X)}}},IT=new Map,l1=t=>{let n=t&&t.env||{};const{fetch:r,Request:s,Response:i}=n,c=[s,i,r];let u=c.length,f=u,g,h,v=IT;for(;f--;)g=c[f],h=v.get(g),h===void 0&&v.set(g,h=f?new Map:VT(n)),v=h;return h};l1();const Rh={http:sT,xhr:zT,fetch:{get:l1}};W.forEach(Rh,(t,n)=>{if(t){try{Object.defineProperty(t,"name",{value:n})}catch{}Object.defineProperty(t,"adapterName",{value:n})}});const $b=t=>`- ${t}`,qT=t=>W.isFunction(t)||t===null||t===!1;function FT(t,n){t=W.isArray(t)?t:[t];const{length:r}=t;let s,i;const c={};for(let u=0;u<r;u++){s=t[u];let f;if(i=s,!qT(s)&&(i=Rh[(f=String(s)).toLowerCase()],i===void 0))throw new $e(`Unknown adapter '${f}'`);if(i&&(W.isFunction(i)||(i=i.get(n))))break;c[f||"#"+u]=i}if(!i){const u=Object.entries(c).map(([g,h])=>`adapter ${g} `+(h===!1?"is not supported by the environment":"is not available in the build"));let f=r?u.length>1?`since :+`+u.map($b).join(`+`):" "+$b(u[0]):"as no adapter specified";throw new $e("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return i}const c1={getAdapter:FT,adapters:Rh};function bm(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new $o(null,t)}function Gb(t){return bm(t),t.headers=Tn.from(t.headers),t.data=vm.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),c1.getAdapter(t.adapter||fl.adapter,t)(t).then(function(s){return bm(t),s.data=vm.call(t,t.transformResponse,s),s.headers=Tn.from(s.headers),s},function(s){return r1(s)||(bm(t),s&&s.response&&(s.response.data=vm.call(t,t.transformResponse,s.response),s.response.headers=Tn.from(s.response.headers))),Promise.reject(s)})}const u1="1.13.2",Ou={};["object","boolean","number","function","string","symbol"].forEach((t,n)=>{Ou[t]=function(s){return typeof s===t||"a"+(n<1?"n ":" ")+t}});const Yb={};Ou.transitional=function(n,r,s){function i(c,u){return"[Axios v"+u1+"] Transitional option '"+c+"'"+u+(s?". "+s:"")}return(c,u,f)=>{if(n===!1)throw new $e(i(u," has been removed"+(r?" in "+r:"")),$e.ERR_DEPRECATED);return r&&!Yb[u]&&(Yb[u]=!0,console.warn(i(u," has been deprecated since v"+r+" and will be removed in the near future"))),n?n(c,u,f):!0}};Ou.spelling=function(n){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${n}`),!0)};function $T(t,n,r){if(typeof t!="object")throw new $e("options must be an object",$e.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let i=s.length;for(;i-- >0;){const c=s[i],u=n[c];if(u){const f=t[c],g=f===void 0||u(f,c,t);if(g!==!0)throw new $e("option "+c+" must be "+g,$e.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new $e("Unknown option "+c,$e.ERR_BAD_OPTION)}}const Zc={assertOptions:$T,validators:Ou},_a=Zc.validators;let vs=class{constructor(n){this.defaults=n||{},this.interceptors={request:new zb,response:new zb}}async request(n,r){try{return await this._request(n,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const c=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?c&&!String(s.stack).endsWith(c.replace(/^.+\n.+\n/,""))&&(s.stack+=`+`+c):s.stack=c}catch{}}throw s}}_request(n,r){typeof n=="string"?(r=r||{},r.url=n):r=n||{},r=bs(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:c}=r;s!==void 0&&Zc.assertOptions(s,{silentJSONParsing:_a.transitional(_a.boolean),forcedJSONParsing:_a.transitional(_a.boolean),clarifyTimeoutError:_a.transitional(_a.boolean)},!1),i!=null&&(W.isFunction(i)?r.paramsSerializer={serialize:i}:Zc.assertOptions(i,{encode:_a.function,serialize:_a.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Zc.assertOptions(r,{baseUrl:_a.spelling("baseURL"),withXsrfToken:_a.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let u=c&&W.merge(c.common,c[r.method]);c&&W.forEach(["delete","get","head","post","put","patch","common"],E=>{delete c[E]}),r.headers=Tn.concat(u,c);const f=[];let g=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(r)===!1||(g=g&&S.synchronous,f.unshift(S.fulfilled,S.rejected))});const h=[];this.interceptors.response.forEach(function(S){h.push(S.fulfilled,S.rejected)});let v,y=0,w;if(!g){const E=[Gb.bind(this),void 0];for(E.unshift(...f),E.push(...h),w=E.length,v=Promise.resolve(r);y<w;)v=v.then(E[y++],E[y++]);return v}w=f.length;let N=r;for(;y<w;){const E=f[y++],S=f[y++];try{N=E(N)}catch(C){S.call(this,C);break}}try{v=Gb.call(this,N)}catch(E){return Promise.reject(E)}for(y=0,w=h.length;y<w;)v=v.then(h[y++],h[y++]);return v}getUri(n){n=bs(this.defaults,n);const r=o1(n.baseURL,n.url,n.allowAbsoluteUrls);return t1(r,n.params,n.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(n){vs.prototype[n]=function(r,s){return this.request(bs(s||{},{method:n,url:r,data:(s||{}).data}))}});W.forEach(["post","put","patch"],function(n){function r(s){return function(c,u,f){return this.request(bs(f||{},{method:n,headers:s?{"Content-Type":"multipart/form-data"}:{},url:c,data:u}))}}vs.prototype[n]=r(),vs.prototype[n+"Form"]=r(!0)});let GT=class d1{constructor(n){if(typeof n!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(c){r=c});const s=this;this.promise.then(i=>{if(!s._listeners)return;let c=s._listeners.length;for(;c-- >0;)s._listeners[c](i);s._listeners=null}),this.promise.then=i=>{let c;const u=new Promise(f=>{s.subscribe(f),c=f}).then(i);return u.cancel=function(){s.unsubscribe(c)},u},n(function(c,u,f){s.reason||(s.reason=new $o(c,u,f),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(n){if(this.reason){n(this.reason);return}this._listeners?this._listeners.push(n):this._listeners=[n]}unsubscribe(n){if(!this._listeners)return;const r=this._listeners.indexOf(n);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const n=new AbortController,r=s=>{n.abort(s)};return this.subscribe(r),n.signal.unsubscribe=()=>this.unsubscribe(r),n.signal}static source(){let n;return{token:new d1(function(i){n=i}),cancel:n}}};function YT(t){return function(r){return t.apply(null,r)}}function ZT(t){return W.isObject(t)&&t.isAxiosError===!0}const Zm={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Zm).forEach(([t,n])=>{Zm[n]=t});function f1(t){const n=new vs(t),r=qx(vs.prototype.request,n);return W.extend(r,vs.prototype,n,{allOwnKeys:!0}),W.extend(r,n,null,{allOwnKeys:!0}),r.create=function(i){return f1(bs(t,i))},r}const zt=f1(fl);zt.Axios=vs;zt.CanceledError=$o;zt.CancelToken=GT;zt.isCancel=r1;zt.VERSION=u1;zt.toFormData=ju;zt.AxiosError=$e;zt.Cancel=zt.CanceledError;zt.all=function(n){return Promise.all(n)};zt.spread=YT;zt.isAxiosError=ZT;zt.mergeConfig=bs;zt.AxiosHeaders=Tn;zt.formToJSON=t=>a1(W.isHTMLForm(t)?new FormData(t):t);zt.getAdapter=c1.getAdapter;zt.HttpStatusCode=Zm;zt.default=zt;const{Axios:U5,AxiosError:B5,CanceledError:P5,isCancel:H5,CancelToken:V5,VERSION:I5,all:q5,Cancel:F5,isAxiosError:$5,spread:G5,toFormData:Y5,AxiosHeaders:Z5,HttpStatusCode:X5,formToJSON:K5,getAdapter:Q5,mergeConfig:W5}=zt,qn=zt.create({timeout:3e4,headers:{"Content-Type":"application/json"}});qn.interceptors.request.use(t=>{const n=localStorage.getItem("evolution-auth");if(n)try{const r=JSON.parse(n),{apiUrl:s,apiKey:i}=r.state||r;s&&(t.baseURL=s),i&&!t.headers.has("apikey")&&t.headers.set("apikey",i)}catch(r){console.error("Error parsing auth data:",r)}return t},t=>Promise.reject(t));qn.interceptors.response.use(t=>t,t=>{var r,s,i;if(((r=t.response)==null?void 0:r.status)===401&&(console.error("Unauthorized - clearing auth data"),localStorage.removeItem("evolution-auth"),window.location.href="/"),!t.response)return console.error("Network error:",t.message),Promise.reject({message:"Erro de conexão. Verifique sua internet e tente novamente.",originalError:t});const n=(s=t.response)!=null&&s.data?t.response.data.error||t.response.data.message||"Erro desconhecido":t.message;return console.error("API Error:",n),Promise.reject({message:n,status:(i=t.response)==null?void 0:i.status,originalError:t})});const XT=Ix()(bR(t=>({apiUrl:typeof window<"u"?window.location.origin:"http://localhost:8082",apiKey:"",isAuthenticated:!1,login:async(n,r)=>{var s;try{const i=n.replace(/\/$/,""),c=await qn.get("/server/ok",{baseURL:i,headers:{apikey:r}});if(c.status===200&&((s=c.data)==null?void 0:s.status)==="ok")t({apiUrl:i,apiKey:r,isAuthenticated:!0});else throw new Error("Falha ao conectar com a API")}catch(i){throw console.error("Login error:",i),new Error("Não foi possível conectar. Verifique a URL e API Key.")}},logout:()=>{localStorage.removeItem("evolution-auth"),t({apiUrl:typeof window<"u"?window.location.origin:"http://localhost:8082",apiKey:"",isAuthenticated:!1}),window.location.href="/manager/login"},setApiUrl:n=>{t({apiUrl:n.replace(/\/$/,"")})},setApiKey:n=>{t({apiKey:n})}}),{name:"evolution-auth",partialize:t=>({apiUrl:t.apiUrl,apiKey:t.apiKey,isAuthenticated:t.isAuthenticated})}));function Th(){const t=XT();return{isAuthenticated:t.isAuthenticated,apiUrl:t.apiUrl,apiKey:t.apiKey,login:t.login,logout:t.logout,setApiUrl:t.setApiUrl,setApiKey:t.setApiKey}}const m1=b.createContext(void 0);function KT({children:t}){const[n,r]=b.useState(()=>{if(typeof window>"u")return"light";const c=localStorage.getItem("evolution-theme");return c||(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")});b.useEffect(()=>{const c=window.document.documentElement;n==="dark"?c.classList.add("dark"):c.classList.remove("dark"),localStorage.setItem("evolution-theme",n)},[n]),b.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{localStorage.getItem("evolution-theme")||r(c.matches?"dark":"light")};return c.addEventListener("change",u),()=>c.removeEventListener("change",u)},[]);const s=()=>{r(c=>c==="light"?"dark":"light")},i=b.useMemo(()=>({theme:n,toggleTheme:s}),[n]);return p.jsx(m1.Provider,{value:i,children:t})}function QT(){const t=b.useContext(m1);if(t===void 0)throw new Error("useDarkMode deve ser usado dentro de um DarkModeProvider");return t}function WT(){const{logout:t}=Th(),{theme:n,toggleTheme:r}=QT(),s=()=>{t()};return p.jsxs("header",{className:"flex h-16 items-center justify-between border-b border-sidebar-border bg-sidebar px-0 py-3 shadow-sm",children:[p.jsx("div",{className:"w-56 flex items-center px-4"}),p.jsxs("div",{className:"flex items-center gap-2 px-4",children:[p.jsx("button",{onClick:r,className:"flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-200 dark:hover:bg-sidebar-accent",title:n==="dark"?"Modo claro":"Modo escuro",children:n==="dark"?p.jsx(gA,{className:"h-4 w-4"}):p.jsx(JN,{className:"h-4 w-4"})}),p.jsxs("button",{onClick:s,className:"flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-200 dark:hover:bg-sidebar-accent",children:[p.jsx(XN,{className:"h-4 w-4"}),"Sair"]})]})]})}function JT({children:t}){return p.jsxs("div",{className:"flex h-screen bg-background",children:[p.jsx(fR,{}),p.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[p.jsx(WT,{}),p.jsx("main",{className:"flex-1 overflow-y-auto",children:t||p.jsx(u2,{})})]})]})}function ej(t,n){const r=b.createContext(n),s=c=>{const{children:u,...f}=c,g=b.useMemo(()=>f,Object.values(f));return p.jsx(r.Provider,{value:g,children:u})};s.displayName=t+"Provider";function i(c){const u=b.useContext(r);if(u)return u;if(n!==void 0)return n;throw new Error(`\`${c}\` must be used within \`${t}\``)}return[s,i]}function _s(t,n=[]){let r=[];function s(c,u){const f=b.createContext(u),g=r.length;r=[...r,u];const h=y=>{var A;const{scope:w,children:N,...E}=y,S=((A=w==null?void 0:w[t])==null?void 0:A[g])||f,C=b.useMemo(()=>E,Object.values(E));return p.jsx(S.Provider,{value:C,children:N})};h.displayName=c+"Provider";function v(y,w){var S;const N=((S=w==null?void 0:w[t])==null?void 0:S[g])||f,E=b.useContext(N);if(E)return E;if(u!==void 0)return u;throw new Error(`\`${y}\` must be used within \`${c}\``)}return[h,v]}const i=()=>{const c=r.map(u=>b.createContext(u));return function(f){const g=(f==null?void 0:f[t])||c;return b.useMemo(()=>({[`__scope${t}`]:{...f,[t]:g}}),[f,g])}};return i.scopeName=t,[s,tj(i,...n)]}function tj(...t){const n=t[0];if(t.length===1)return n;const r=()=>{const s=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(c){const u=s.reduce((f,{useScope:g,scopeName:h})=>{const y=g(c)[`__scope${h}`];return{...f,...y}},{});return b.useMemo(()=>({[`__scope${n.scopeName}`]:u}),[u])}};return r.scopeName=n.scopeName,r}function Zb(t,n){if(typeof t=="function")return t(n);t!=null&&(t.current=n)}function lr(...t){return n=>{let r=!1;const s=t.map(i=>{const c=Zb(i,n);return!r&&typeof c=="function"&&(r=!0),c});if(r)return()=>{for(let i=0;i<s.length;i++){const c=s[i];typeof c=="function"?c():Zb(t[i],null)}}}}function Zt(...t){return b.useCallback(lr(...t),t)}function Xb(t){const n=nj(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(rj);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function nj(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=oj(i),f=sj(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var aj=Symbol("radix.slottable");function rj(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===aj}function sj(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function oj(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function h1(t){const n=t+"CollectionProvider",[r,s]=_s(n),[i,c]=r(n,{collectionRef:{current:null},itemMap:new Map}),u=S=>{const{scope:C,children:A}=S,O=ae.useRef(null),R=ae.useRef(new Map).current;return p.jsx(i,{scope:C,itemMap:R,collectionRef:O,children:A})};u.displayName=n;const f=t+"CollectionSlot",g=Xb(f),h=ae.forwardRef((S,C)=>{const{scope:A,children:O}=S,R=c(f,A),L=Zt(C,R.collectionRef);return p.jsx(g,{ref:L,children:O})});h.displayName=f;const v=t+"CollectionItemSlot",y="data-radix-collection-item",w=Xb(v),N=ae.forwardRef((S,C)=>{const{scope:A,children:O,...R}=S,L=ae.useRef(null),I=Zt(C,L),ee=c(v,A);return ae.useEffect(()=>(ee.itemMap.set(L,{ref:L,...R}),()=>void ee.itemMap.delete(L))),p.jsx(w,{[y]:"",ref:I,children:O})});N.displayName=v;function E(S){const C=c(t+"CollectionConsumer",S);return ae.useCallback(()=>{const O=C.collectionRef.current;if(!O)return[];const R=Array.from(O.querySelectorAll(`[${y}]`));return Array.from(C.itemMap.values()).sort((ee,U)=>R.indexOf(ee.ref.current)-R.indexOf(U.ref.current))},[C.collectionRef,C.itemMap])}return[{Provider:u,Slot:h,ItemSlot:N},E,s]}function Ve(t,n,{checkForDefaultPrevented:r=!0}={}){return function(i){if(t==null||t(i),r===!1||!i.defaultPrevented)return n==null?void 0:n(i)}}var Ir=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},ij=_u[" useInsertionEffect ".trim().toString()]||Ir;function jh({prop:t,defaultProp:n,onChange:r=()=>{},caller:s}){const[i,c,u]=lj({defaultProp:n,onChange:r}),f=t!==void 0,g=f?t:i;{const v=b.useRef(t!==void 0);b.useEffect(()=>{const y=v.current;y!==f&&console.warn(`${s} is changing from ${y?"controlled":"uncontrolled"} to ${f?"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.`),v.current=f},[f,s])}const h=b.useCallback(v=>{var y;if(f){const w=cj(v)?v(t):v;w!==t&&((y=u.current)==null||y.call(u,w))}else c(v)},[f,t,c,u]);return[g,h]}function lj({defaultProp:t,onChange:n}){const[r,s]=b.useState(t),i=b.useRef(r),c=b.useRef(n);return ij(()=>{c.current=n},[n]),b.useEffect(()=>{var u;i.current!==r&&((u=c.current)==null||u.call(c,r),i.current=r)},[r,i]),[r,s,c]}function cj(t){return typeof t=="function"}function uj(t){const n=dj(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(mj);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function dj(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=pj(i),f=hj(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var fj=Symbol("radix.slottable");function mj(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===fj}function hj(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function pj(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var gj=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],jt=gj.reduce((t,n)=>{const r=uj(`Primitive.${n}`),s=b.forwardRef((i,c)=>{const{asChild:u,...f}=i,g=u?r:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{});function p1(t,n){t&&wh.flushSync(()=>t.dispatchEvent(n))}function yj(t,n){return b.useReducer((r,s)=>n[r][s]??r,t)}var Ma=t=>{const{present:n,children:r}=t,s=vj(n),i=typeof r=="function"?r({present:s.isPresent}):b.Children.only(r),c=Zt(s.ref,bj(i));return typeof r=="function"||s.isPresent?b.cloneElement(i,{ref:c}):null};Ma.displayName="Presence";function vj(t){const[n,r]=b.useState(),s=b.useRef(null),i=b.useRef(t),c=b.useRef("none"),u=t?"mounted":"unmounted",[f,g]=yj(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const h=zc(s.current);c.current=f==="mounted"?h:"none"},[f]),Ir(()=>{const h=s.current,v=i.current;if(v!==t){const w=c.current,N=zc(h);t?g("MOUNT"):N==="none"||(h==null?void 0:h.display)==="none"?g("UNMOUNT"):g(v&&w!==N?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,g]),Ir(()=>{if(n){let h;const v=n.ownerDocument.defaultView??window,y=N=>{const S=zc(s.current).includes(CSS.escape(N.animationName));if(N.target===n&&S&&(g("ANIMATION_END"),!i.current)){const C=n.style.animationFillMode;n.style.animationFillMode="forwards",h=v.setTimeout(()=>{n.style.animationFillMode==="forwards"&&(n.style.animationFillMode=C)})}},w=N=>{N.target===n&&(c.current=zc(s.current))};return n.addEventListener("animationstart",w),n.addEventListener("animationcancel",y),n.addEventListener("animationend",y),()=>{v.clearTimeout(h),n.removeEventListener("animationstart",w),n.removeEventListener("animationcancel",y),n.removeEventListener("animationend",y)}}else g("ANIMATION_END")},[n,g]),{isPresent:["mounted","unmountSuspended"].includes(f),ref:b.useCallback(h=>{s.current=h?getComputedStyle(h):null,r(h)},[])}}function zc(t){return(t==null?void 0:t.animationName)||"none"}function bj(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var xj=_u[" useId ".trim().toString()]||(()=>{}),wj=0;function Co(t){const[n,r]=b.useState(xj());return Ir(()=>{r(s=>s??String(wj++))},[t]),t||(n?`radix-${n}`:"")}var Sj=b.createContext(void 0);function g1(t){const n=b.useContext(Sj);return t||n||"ltr"}/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Ej=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_j=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),Kb=t=>{const n=_j(t);return n.charAt(0).toUpperCase()+n.slice(1)},y1=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),Cj=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */var Nj={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.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Aj=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...Nj,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:y1("lucide",i),...!c&&!Cj(f)&&{"aria-hidden":"true"},...f},[...u.map(([h,v])=>b.createElement(h,v)),...Array.isArray(c)?c:[c]]));/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Rj=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(Aj,{ref:c,iconNode:n,className:y1(`lucide-${Ej(Kb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=Kb(t),r};/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Tj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],jj=Rj("x",Tj),Qb=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Wb=Eh,Oh=(t,n)=>r=>{var s;if((n==null?void 0:n.variants)==null)return Wb(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:c}=n,u=Object.keys(i).map(h=>{const v=r==null?void 0:r[h],y=c==null?void 0:c[h];if(v===null)return null;const w=Qb(v)||Qb(y);return i[h][w]}),f=r&&Object.entries(r).reduce((h,v)=>{let[y,w]=v;return w===void 0||(h[y]=w),h},{}),g=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((h,v)=>{let{class:y,className:w,...N}=v;return Object.entries(N).every(E=>{let[S,C]=E;return Array.isArray(C)?C.includes({...c,...f}[S]):{...c,...f}[S]===C})?[...h,y,w]:h},[]);return Wb(t,u,g,r==null?void 0:r.class,r==null?void 0:r.className)};function rr(t){const n=b.useRef(t);return b.useEffect(()=>{n.current=t}),b.useMemo(()=>(...r)=>{var s;return(s=n.current)==null?void 0:s.call(n,...r)},[])}function Oj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(t);b.useEffect(()=>{const s=i=>{i.key==="Escape"&&r(i)};return n.addEventListener("keydown",s,{capture:!0}),()=>n.removeEventListener("keydown",s,{capture:!0})},[r,n])}var kj="DismissableLayer",Xm="dismissableLayer.update",Mj="dismissableLayer.pointerDownOutside",Dj="dismissableLayer.focusOutside",Jb,v1=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ku=b.forwardRef((t,n)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:c,onInteractOutside:u,onDismiss:f,...g}=t,h=b.useContext(v1),[v,y]=b.useState(null),w=(v==null?void 0:v.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,N]=b.useState({}),E=Zt(n,U=>y(U)),S=Array.from(h.layers),[C]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),A=S.indexOf(C),O=v?S.indexOf(v):-1,R=h.layersWithOutsidePointerEventsDisabled.size>0,L=O>=A,I=Uj(U=>{const Q=U.target,le=[...h.branches].some(ue=>ue.contains(Q));!L||le||(i==null||i(U),u==null||u(U),U.defaultPrevented||f==null||f())},w),ee=Bj(U=>{const Q=U.target;[...h.branches].some(ue=>ue.contains(Q))||(c==null||c(U),u==null||u(U),U.defaultPrevented||f==null||f())},w);return Oj(U=>{O===h.layers.size-1&&(s==null||s(U),!U.defaultPrevented&&f&&(U.preventDefault(),f()))},w),b.useEffect(()=>{if(v)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(Jb=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(v)),h.layers.add(v),e0(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=Jb)}},[v,w,r,h]),b.useEffect(()=>()=>{v&&(h.layers.delete(v),h.layersWithOutsidePointerEventsDisabled.delete(v),e0())},[v,h]),b.useEffect(()=>{const U=()=>N({});return document.addEventListener(Xm,U),()=>document.removeEventListener(Xm,U)},[]),p.jsx(jt.div,{...g,ref:E,style:{pointerEvents:R?L?"auto":"none":void 0,...t.style},onFocusCapture:Ve(t.onFocusCapture,ee.onFocusCapture),onBlurCapture:Ve(t.onBlurCapture,ee.onBlurCapture),onPointerDownCapture:Ve(t.onPointerDownCapture,I.onPointerDownCapture)})});ku.displayName=kj;var zj="DismissableLayerBranch",Lj=b.forwardRef((t,n)=>{const r=b.useContext(v1),s=b.useRef(null),i=Zt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return r.branches.add(c),()=>{r.branches.delete(c)}},[r.branches]),p.jsx(jt.div,{...t,ref:i})});Lj.displayName=zj;function Uj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(t),s=b.useRef(!1),i=b.useRef(()=>{});return b.useEffect(()=>{const c=f=>{if(f.target&&!s.current){let g=function(){b1(Mj,r,h,{discrete:!0})};const h={originalEvent:f};f.pointerType==="touch"?(n.removeEventListener("click",i.current),i.current=g,n.addEventListener("click",i.current,{once:!0})):g()}else n.removeEventListener("click",i.current);s.current=!1},u=window.setTimeout(()=>{n.addEventListener("pointerdown",c)},0);return()=>{window.clearTimeout(u),n.removeEventListener("pointerdown",c),n.removeEventListener("click",i.current)}},[n,r]),{onPointerDownCapture:()=>s.current=!0}}function Bj(t,n=globalThis==null?void 0:globalThis.document){const r=rr(t),s=b.useRef(!1);return b.useEffect(()=>{const i=c=>{c.target&&!s.current&&b1(Dj,r,{originalEvent:c},{discrete:!1})};return n.addEventListener("focusin",i),()=>n.removeEventListener("focusin",i)},[n,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function e0(){const t=new CustomEvent(Xm);document.dispatchEvent(t)}function b1(t,n,r,{discrete:s}){const i=r.originalEvent.target,c=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});n&&i.addEventListener(t,n,{once:!0}),s?p1(i,c):i.dispatchEvent(c)}var xm="focusScope.autoFocusOnMount",wm="focusScope.autoFocusOnUnmount",t0={bubbles:!1,cancelable:!0},Pj="FocusScope",Mu=b.forwardRef((t,n)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:i,onUnmountAutoFocus:c,...u}=t,[f,g]=b.useState(null),h=rr(i),v=rr(c),y=b.useRef(null),w=Zt(n,S=>g(S)),N=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(s){let S=function(R){if(N.paused||!f)return;const L=R.target;f.contains(L)?y.current=L:Lr(y.current,{select:!0})},C=function(R){if(N.paused||!f)return;const L=R.relatedTarget;L!==null&&(f.contains(L)||Lr(y.current,{select:!0}))},A=function(R){if(document.activeElement===document.body)for(const I of R)I.removedNodes.length>0&&Lr(f)};document.addEventListener("focusin",S),document.addEventListener("focusout",C);const O=new MutationObserver(A);return f&&O.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",S),document.removeEventListener("focusout",C),O.disconnect()}}},[s,f,N.paused]),b.useEffect(()=>{if(f){a0.add(N);const S=document.activeElement;if(!f.contains(S)){const A=new CustomEvent(xm,t0);f.addEventListener(xm,h),f.dispatchEvent(A),A.defaultPrevented||(Hj($j(x1(f)),{select:!0}),document.activeElement===S&&Lr(f))}return()=>{f.removeEventListener(xm,h),setTimeout(()=>{const A=new CustomEvent(wm,t0);f.addEventListener(wm,v),f.dispatchEvent(A),A.defaultPrevented||Lr(S??document.body,{select:!0}),f.removeEventListener(wm,v),a0.remove(N)},0)}}},[f,h,v,N]);const E=b.useCallback(S=>{if(!r&&!s||N.paused)return;const C=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,A=document.activeElement;if(C&&A){const O=S.currentTarget,[R,L]=Vj(O);R&&L?!S.shiftKey&&A===L?(S.preventDefault(),r&&Lr(R,{select:!0})):S.shiftKey&&A===R&&(S.preventDefault(),r&&Lr(L,{select:!0})):A===O&&S.preventDefault()}},[r,s,N.paused]);return p.jsx(jt.div,{tabIndex:-1,...u,ref:w,onKeyDown:E})});Mu.displayName=Pj;function Hj(t,{select:n=!1}={}){const r=document.activeElement;for(const s of t)if(Lr(s,{select:n}),document.activeElement!==r)return}function Vj(t){const n=x1(t),r=n0(n,t),s=n0(n.reverse(),t);return[r,s]}function x1(t){const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const i=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||i?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)n.push(r.currentNode);return n}function n0(t,n){for(const r of t)if(!Ij(r,{upTo:n}))return r}function Ij(t,{upTo:n}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(n!==void 0&&t===n)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function qj(t){return t instanceof HTMLInputElement&&"select"in t}function Lr(t,{select:n=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&qj(t)&&n&&t.select()}}var a0=Fj();function Fj(){let t=[];return{add(n){const r=t[0];n!==r&&(r==null||r.pause()),t=r0(t,n),t.unshift(n)},remove(n){var r;t=r0(t,n),(r=t[0])==null||r.resume()}}}function r0(t,n){const r=[...t],s=r.indexOf(n);return s!==-1&&r.splice(s,1),r}function $j(t){return t.filter(n=>n.tagName!=="A")}var Gj="Portal",Du=b.forwardRef((t,n)=>{var f;const{container:r,...s}=t,[i,c]=b.useState(!1);Ir(()=>c(!0),[]);const u=r||i&&((f=globalThis==null?void 0:globalThis.document)==null?void 0:f.body);return u?Cx.createPortal(p.jsx(jt.div,{...s,ref:n}),u):null});Du.displayName=Gj;var Sm=0;function kh(){b.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??s0()),document.body.insertAdjacentElement("beforeend",t[1]??s0()),Sm++,()=>{Sm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(n=>n.remove()),Sm--}},[])}function s0(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Aa=function(){return Aa=Object.assign||function(n){for(var r,s=1,i=arguments.length;s<i;s++){r=arguments[s];for(var c in r)Object.prototype.hasOwnProperty.call(r,c)&&(n[c]=r[c])}return n},Aa.apply(this,arguments)};function w1(t,n){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&n.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(t);i<s.length;i++)n.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(t,s[i])&&(r[s[i]]=t[s[i]]);return r}function Yj(t,n,r){if(r||arguments.length===2)for(var s=0,i=n.length,c;s<i;s++)(c||!(s in n))&&(c||(c=Array.prototype.slice.call(n,0,s)),c[s]=n[s]);return t.concat(c||Array.prototype.slice.call(n))}var Xc="right-scroll-bar-position",Kc="width-before-scroll-bar",Zj="with-scroll-bars-hidden",Xj="--removed-body-scroll-bar-size";function Em(t,n){return typeof t=="function"?t(n):t&&(t.current=n),t}function Kj(t,n){var r=b.useState(function(){return{value:t,callback:n,facade:{get current(){return r.value},set current(s){var i=r.value;i!==s&&(r.value=s,r.callback(s,i))}}}})[0];return r.callback=n,r.facade}var Qj=typeof window<"u"?b.useLayoutEffect:b.useEffect,o0=new WeakMap;function Wj(t,n){var r=Kj(null,function(s){return t.forEach(function(i){return Em(i,s)})});return Qj(function(){var s=o0.get(r);if(s){var i=new Set(s),c=new Set(t),u=r.current;i.forEach(function(f){c.has(f)||Em(f,null)}),c.forEach(function(f){i.has(f)||Em(f,u)})}o0.set(r,t)},[t]),r}function Jj(t){return t}function eO(t,n){n===void 0&&(n=Jj);var r=[],s=!1,i={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:t},useMedium:function(c){var u=n(c,s);return r.push(u),function(){r=r.filter(function(f){return f!==u})}},assignSyncMedium:function(c){for(s=!0;r.length;){var u=r;r=[],u.forEach(c)}r={push:function(f){return c(f)},filter:function(){return r}}},assignMedium:function(c){s=!0;var u=[];if(r.length){var f=r;r=[],f.forEach(c),u=r}var g=function(){var v=u;u=[],v.forEach(c)},h=function(){return Promise.resolve().then(g)};h(),r={push:function(v){u.push(v),h()},filter:function(v){return u=u.filter(v),r}}}};return i}function tO(t){t===void 0&&(t={});var n=eO(null);return n.options=Aa({async:!0,ssr:!1},t),n}var S1=function(t){var n=t.sideCar,r=w1(t,["sideCar"]);if(!n)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=n.read();if(!s)throw new Error("Sidecar medium not found");return b.createElement(s,Aa({},r))};S1.isSideCarExport=!0;function nO(t,n){return t.useMedium(n),S1}var E1=tO(),_m=function(){},zu=b.forwardRef(function(t,n){var r=b.useRef(null),s=b.useState({onScrollCapture:_m,onWheelCapture:_m,onTouchMoveCapture:_m}),i=s[0],c=s[1],u=t.forwardProps,f=t.children,g=t.className,h=t.removeScrollBar,v=t.enabled,y=t.shards,w=t.sideCar,N=t.noRelative,E=t.noIsolation,S=t.inert,C=t.allowPinchZoom,A=t.as,O=A===void 0?"div":A,R=t.gapMode,L=w1(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=w,ee=Wj([r,n]),U=Aa(Aa({},L),i);return b.createElement(b.Fragment,null,v&&b.createElement(I,{sideCar:E1,removeScrollBar:h,shards:y,noRelative:N,noIsolation:E,inert:S,setCallbacks:c,allowPinchZoom:!!C,lockRef:r,gapMode:R}),u?b.cloneElement(b.Children.only(f),Aa(Aa({},U),{ref:ee})):b.createElement(O,Aa({},U,{className:g,ref:ee}),f))});zu.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};zu.classNames={fullWidth:Kc,zeroRight:Xc};var aO=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function rO(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var n=aO();return n&&t.setAttribute("nonce",n),t}function sO(t,n){t.styleSheet?t.styleSheet.cssText=n:t.appendChild(document.createTextNode(n))}function oO(t){var n=document.head||document.getElementsByTagName("head")[0];n.appendChild(t)}var iO=function(){var t=0,n=null;return{add:function(r){t==0&&(n=rO())&&(sO(n,r),oO(n)),t++},remove:function(){t--,!t&&n&&(n.parentNode&&n.parentNode.removeChild(n),n=null)}}},lO=function(){var t=iO();return function(n,r){b.useEffect(function(){return t.add(n),function(){t.remove()}},[n&&r])}},_1=function(){var t=lO(),n=function(r){var s=r.styles,i=r.dynamic;return t(s,i),null};return n},cO={left:0,top:0,right:0,gap:0},Cm=function(t){return parseInt(t||"",10)||0},uO=function(t){var n=window.getComputedStyle(document.body),r=n[t==="padding"?"paddingLeft":"marginLeft"],s=n[t==="padding"?"paddingTop":"marginTop"],i=n[t==="padding"?"paddingRight":"marginRight"];return[Cm(r),Cm(s),Cm(i)]},dO=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return cO;var n=uO(t),r=document.documentElement.clientWidth,s=window.innerWidth;return{left:n[0],top:n[1],right:n[2],gap:Math.max(0,s-r+n[2]-n[0])}},fO=_1(),No="data-scroll-locked",mO=function(t,n,r,s){var i=t.left,c=t.top,u=t.right,f=t.gap;return r===void 0&&(r="margin"),`+ .`.concat(Zj,` {+ overflow: hidden `).concat(s,`;+ padding-right: `).concat(f,"px ").concat(s,`;+ }+ body[`).concat(No,`] {+ overflow: hidden `).concat(s,`;+ overscroll-behavior: contain;+ `).concat([n&&"position: relative ".concat(s,";"),r==="margin"&&`+ padding-left: `.concat(i,`px;+ padding-top: `).concat(c,`px;+ padding-right: `).concat(u,`px;+ margin-left:0;+ margin-top:0;+ margin-right: `).concat(f,"px ").concat(s,`;+ `),r==="padding"&&"padding-right: ".concat(f,"px ").concat(s,";")].filter(Boolean).join(""),`+ }++ .`).concat(Xc,` {+ right: `).concat(f,"px ").concat(s,`;+ }++ .`).concat(Kc,` {+ margin-right: `).concat(f,"px ").concat(s,`;+ }++ .`).concat(Xc," .").concat(Xc,` {+ right: 0 `).concat(s,`;+ }++ .`).concat(Kc," .").concat(Kc,` {+ margin-right: 0 `).concat(s,`;+ }++ body[`).concat(No,`] {+ `).concat(Xj,": ").concat(f,`px;+ }+`)},i0=function(){var t=parseInt(document.body.getAttribute(No)||"0",10);return isFinite(t)?t:0},hO=function(){b.useEffect(function(){return document.body.setAttribute(No,(i0()+1).toString()),function(){var t=i0()-1;t<=0?document.body.removeAttribute(No):document.body.setAttribute(No,t.toString())}},[])},pO=function(t){var n=t.noRelative,r=t.noImportant,s=t.gapMode,i=s===void 0?"margin":s;hO();var c=b.useMemo(function(){return dO(i)},[i]);return b.createElement(fO,{styles:mO(c,!n,i,r?"":"!important")})},Km=!1;if(typeof window<"u")try{var Lc=Object.defineProperty({},"passive",{get:function(){return Km=!0,!0}});window.addEventListener("test",Lc,Lc),window.removeEventListener("test",Lc,Lc)}catch{Km=!1}var go=Km?{passive:!1}:!1,gO=function(t){return t.tagName==="TEXTAREA"},C1=function(t,n){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[n]!=="hidden"&&!(r.overflowY===r.overflowX&&!gO(t)&&r[n]==="visible")},yO=function(t){return C1(t,"overflowY")},vO=function(t){return C1(t,"overflowX")},l0=function(t,n){var r=n.ownerDocument,s=n;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var i=N1(t,s);if(i){var c=A1(t,s),u=c[1],f=c[2];if(u>f)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},bO=function(t){var n=t.scrollTop,r=t.scrollHeight,s=t.clientHeight;return[n,r,s]},xO=function(t){var n=t.scrollLeft,r=t.scrollWidth,s=t.clientWidth;return[n,r,s]},N1=function(t,n){return t==="v"?yO(n):vO(n)},A1=function(t,n){return t==="v"?bO(n):xO(n)},wO=function(t,n){return t==="h"&&n==="rtl"?-1:1},SO=function(t,n,r,s,i){var c=wO(t,window.getComputedStyle(n).direction),u=c*s,f=r.target,g=n.contains(f),h=!1,v=u>0,y=0,w=0;do{if(!f)break;var N=A1(t,f),E=N[0],S=N[1],C=N[2],A=S-C-c*E;(E||A)&&N1(t,f)&&(y+=A,w+=E);var O=f.parentNode;f=O&&O.nodeType===Node.DOCUMENT_FRAGMENT_NODE?O.host:O}while(!g&&f!==document.body||g&&(n.contains(f)||n===f));return(v&&Math.abs(y)<1||!v&&Math.abs(w)<1)&&(h=!0),h},Uc=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},c0=function(t){return[t.deltaX,t.deltaY]},u0=function(t){return t&&"current"in t?t.current:t},EO=function(t,n){return t[0]===n[0]&&t[1]===n[1]},_O=function(t){return`+ .block-interactivity-`.concat(t,` {pointer-events: none;}+ .allow-interactivity-`).concat(t,` {pointer-events: all;}+`)},CO=0,yo=[];function NO(t){var n=b.useRef([]),r=b.useRef([0,0]),s=b.useRef(),i=b.useState(CO++)[0],c=b.useState(_1)[0],u=b.useRef(t);b.useEffect(function(){u.current=t},[t]),b.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var S=Yj([t.lockRef.current],(t.shards||[]).map(u0),!0).filter(Boolean);return S.forEach(function(C){return C.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),S.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var f=b.useCallback(function(S,C){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!u.current.allowPinchZoom;var A=Uc(S),O=r.current,R="deltaX"in S?S.deltaX:O[0]-A[0],L="deltaY"in S?S.deltaY:O[1]-A[1],I,ee=S.target,U=Math.abs(R)>Math.abs(L)?"h":"v";if("touches"in S&&U==="h"&&ee.type==="range")return!1;var Q=l0(U,ee);if(!Q)return!0;if(Q?I=U:(I=U==="v"?"h":"v",Q=l0(U,ee)),!Q)return!1;if(!s.current&&"changedTouches"in S&&(R||L)&&(s.current=I),!I)return!0;var le=s.current||I;return SO(le,C,S,le==="h"?R:L)},[]),g=b.useCallback(function(S){var C=S;if(!(!yo.length||yo[yo.length-1]!==c)){var A="deltaY"in C?c0(C):Uc(C),O=n.current.filter(function(I){return I.name===C.type&&(I.target===C.target||C.target===I.shadowParent)&&EO(I.delta,A)})[0];if(O&&O.should){C.cancelable&&C.preventDefault();return}if(!O){var R=(u.current.shards||[]).map(u0).filter(Boolean).filter(function(I){return I.contains(C.target)}),L=R.length>0?f(C,R[0]):!u.current.noIsolation;L&&C.cancelable&&C.preventDefault()}}},[]),h=b.useCallback(function(S,C,A,O){var R={name:S,delta:C,target:A,should:O,shadowParent:AO(A)};n.current.push(R),setTimeout(function(){n.current=n.current.filter(function(L){return L!==R})},1)},[]),v=b.useCallback(function(S){r.current=Uc(S),s.current=void 0},[]),y=b.useCallback(function(S){h(S.type,c0(S),S.target,f(S,t.lockRef.current))},[]),w=b.useCallback(function(S){h(S.type,Uc(S),S.target,f(S,t.lockRef.current))},[]);b.useEffect(function(){return yo.push(c),t.setCallbacks({onScrollCapture:y,onWheelCapture:y,onTouchMoveCapture:w}),document.addEventListener("wheel",g,go),document.addEventListener("touchmove",g,go),document.addEventListener("touchstart",v,go),function(){yo=yo.filter(function(S){return S!==c}),document.removeEventListener("wheel",g,go),document.removeEventListener("touchmove",g,go),document.removeEventListener("touchstart",v,go)}},[]);var N=t.removeScrollBar,E=t.inert;return b.createElement(b.Fragment,null,E?b.createElement(c,{styles:_O(i)}):null,N?b.createElement(pO,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function AO(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const RO=nO(E1,NO);var Lu=b.forwardRef(function(t,n){return b.createElement(zu,Aa({},t,{ref:n,sideCar:RO}))});Lu.classNames=zu.classNames;var TO=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},vo=new WeakMap,Bc=new WeakMap,Pc={},Nm=0,R1=function(t){return t&&(t.host||R1(t.parentNode))},jO=function(t,n){return n.map(function(r){if(t.contains(r))return r;var s=R1(r);return s&&t.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",t,". Doing nothing"),null)}).filter(function(r){return!!r})},OO=function(t,n,r,s){var i=jO(n,Array.isArray(t)?t:[t]);Pc[r]||(Pc[r]=new WeakMap);var c=Pc[r],u=[],f=new Set,g=new Set(i),h=function(y){!y||f.has(y)||(f.add(y),h(y.parentNode))};i.forEach(h);var v=function(y){!y||g.has(y)||Array.prototype.forEach.call(y.children,function(w){if(f.has(w))v(w);else try{var N=w.getAttribute(s),E=N!==null&&N!=="false",S=(vo.get(w)||0)+1,C=(c.get(w)||0)+1;vo.set(w,S),c.set(w,C),u.push(w),S===1&&E&&Bc.set(w,!0),C===1&&w.setAttribute(r,"true"),E||w.setAttribute(s,"true")}catch(A){console.error("aria-hidden: cannot operate on ",w,A)}})};return v(n),f.clear(),Nm++,function(){u.forEach(function(y){var w=vo.get(y)-1,N=c.get(y)-1;vo.set(y,w),c.set(y,N),w||(Bc.has(y)||y.removeAttribute(s),Bc.delete(y)),N||y.removeAttribute(r)}),Nm--,Nm||(vo=new WeakMap,vo=new WeakMap,Bc=new WeakMap,Pc={})}},Mh=function(t,n,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),i=TO(t);return i?(s.push.apply(s,Array.from(i.querySelectorAll("[aria-live], script"))),OO(s,i,r,"aria-hidden")):function(){return null}};function kO(t){const n=MO(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(zO);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function MO(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=UO(i),f=LO(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var DO=Symbol("radix.slottable");function zO(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===DO}function LO(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function UO(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var Uu="Dialog",[T1]=_s(Uu),[BO,ga]=T1(Uu),j1=t=>{const{__scopeDialog:n,children:r,open:s,defaultOpen:i,onOpenChange:c,modal:u=!0}=t,f=b.useRef(null),g=b.useRef(null),[h,v]=jh({prop:s,defaultProp:i??!1,onChange:c,caller:Uu});return p.jsx(BO,{scope:n,triggerRef:f,contentRef:g,contentId:Co(),titleId:Co(),descriptionId:Co(),open:h,onOpenChange:v,onOpenToggle:b.useCallback(()=>v(y=>!y),[v]),modal:u,children:r})};j1.displayName=Uu;var O1="DialogTrigger",PO=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ga(O1,r),c=Zt(n,i.triggerRef);return p.jsx(jt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Lh(i.open),...s,ref:c,onClick:Ve(t.onClick,i.onOpenToggle)})});PO.displayName=O1;var Dh="DialogPortal",[HO,k1]=T1(Dh,{forceMount:void 0}),M1=t=>{const{__scopeDialog:n,forceMount:r,children:s,container:i}=t,c=ga(Dh,n);return p.jsx(HO,{scope:n,forceMount:r,children:b.Children.map(s,u=>p.jsx(Ma,{present:r||c.open,children:p.jsx(Du,{asChild:!0,container:i,children:u})}))})};M1.displayName=Dh;var tu="DialogOverlay",D1=b.forwardRef((t,n)=>{const r=k1(tu,t.__scopeDialog),{forceMount:s=r.forceMount,...i}=t,c=ga(tu,t.__scopeDialog);return c.modal?p.jsx(Ma,{present:s||c.open,children:p.jsx(IO,{...i,ref:n})}):null});D1.displayName=tu;var VO=kO("DialogOverlay.RemoveScroll"),IO=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ga(tu,r);return p.jsx(Lu,{as:VO,allowPinchZoom:!0,shards:[i.contentRef],children:p.jsx(jt.div,{"data-state":Lh(i.open),...s,ref:n,style:{pointerEvents:"auto",...s.style}})})}),xs="DialogContent",z1=b.forwardRef((t,n)=>{const r=k1(xs,t.__scopeDialog),{forceMount:s=r.forceMount,...i}=t,c=ga(xs,t.__scopeDialog);return p.jsx(Ma,{present:s||c.open,children:c.modal?p.jsx(qO,{...i,ref:n}):p.jsx(FO,{...i,ref:n})})});z1.displayName=xs;var qO=b.forwardRef((t,n)=>{const r=ga(xs,t.__scopeDialog),s=b.useRef(null),i=Zt(n,r.contentRef,s);return b.useEffect(()=>{const c=s.current;if(c)return Mh(c)},[]),p.jsx(L1,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(t.onCloseAutoFocus,c=>{var u;c.preventDefault(),(u=r.triggerRef.current)==null||u.focus()}),onPointerDownOutside:Ve(t.onPointerDownOutside,c=>{const u=c.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&c.preventDefault()}),onFocusOutside:Ve(t.onFocusOutside,c=>c.preventDefault())})}),FO=b.forwardRef((t,n)=>{const r=ga(xs,t.__scopeDialog),s=b.useRef(!1),i=b.useRef(!1);return p.jsx(L1,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var u,f;(u=t.onCloseAutoFocus)==null||u.call(t,c),c.defaultPrevented||(s.current||(f=r.triggerRef.current)==null||f.focus(),c.preventDefault()),s.current=!1,i.current=!1},onInteractOutside:c=>{var g,h;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(s.current=!0,c.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=c.target;((h=r.triggerRef.current)==null?void 0:h.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),L1=b.forwardRef((t,n)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,...u}=t,f=ga(xs,r),g=b.useRef(null),h=Zt(n,g);return kh(),p.jsxs(p.Fragment,{children:[p.jsx(Mu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:p.jsx(ku,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Lh(f.open),...u,ref:h,onDismiss:()=>f.onOpenChange(!1)})}),p.jsxs(p.Fragment,{children:[p.jsx($O,{titleId:f.titleId}),p.jsx(YO,{contentRef:g,descriptionId:f.descriptionId})]})]})}),zh="DialogTitle",U1=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ga(zh,r);return p.jsx(jt.h2,{id:i.titleId,...s,ref:n})});U1.displayName=zh;var B1="DialogDescription",P1=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ga(B1,r);return p.jsx(jt.p,{id:i.descriptionId,...s,ref:n})});P1.displayName=B1;var H1="DialogClose",V1=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ga(H1,r);return p.jsx(jt.button,{type:"button",...s,ref:n,onClick:Ve(t.onClick,()=>i.onOpenChange(!1))})});V1.displayName=H1;function Lh(t){return t?"open":"closed"}var I1="DialogTitleWarning",[J5,q1]=ej(I1,{contentName:xs,titleName:zh,docsSlug:"dialog"}),$O=({titleId:t})=>{const n=q1(I1),r=`\`${n.contentName}\` requires a \`${n.titleName}\` for the component to be accessible for screen reader users.++If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component.++For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return b.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},GO="DialogDescriptionWarning",YO=({contentRef:t,descriptionId:n})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${q1(GO).contentName}}.`;return b.useEffect(()=>{var c;const i=(c=t.current)==null?void 0:c.getAttribute("aria-describedby");n&&i&&(document.getElementById(n)||console.warn(s))},[s,t,n]),null},ZO=j1,XO=M1,F1=D1,$1=z1,KO=U1,QO=P1,WO=V1,JO=Symbol.for("react.lazy"),nu=_u[" use ".trim().toString()];function ek(t){return typeof t=="object"&&t!==null&&"then"in t}function G1(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===JO&&"_payload"in t&&ek(t._payload)}function Y1(t){const n=tk(t),r=b.forwardRef((s,i)=>{let{children:c,...u}=s;G1(c)&&typeof nu=="function"&&(c=nu(c._payload));const f=b.Children.toArray(c),g=f.find(ak);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}var Z1=Y1("Slot");function tk(t){const n=b.forwardRef((r,s)=>{let{children:i,...c}=r;if(G1(i)&&typeof nu=="function"&&(i=nu(i._payload)),b.isValidElement(i)){const u=sk(i),f=rk(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var nk=Symbol("radix.slottable");function ak(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===nk}function rk(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function sk(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function ok(t){const[n,r]=b.useState(void 0);return Ir(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const s=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const c=i[0];let u,f;if("borderBoxSize"in c){const g=c.borderBoxSize,h=Array.isArray(g)?g[0]:g;u=h.inlineSize,f=h.blockSize}else u=t.offsetWidth,f=t.offsetHeight;r({width:u,height:f})});return s.observe(t,{box:"border-box"}),()=>s.unobserve(t)}else r(void 0)},[t]),n}const ik=["top","right","bottom","left"],qr=Math.min,Bn=Math.max,au=Math.round,Hc=Math.floor,ja=t=>({x:t,y:t}),lk={left:"right",right:"left",bottom:"top",top:"bottom"},ck={start:"end",end:"start"};function Qm(t,n,r){return Bn(t,qr(n,r))}function sr(t,n){return typeof t=="function"?t(n):t}function or(t){return t.split("-")[0]}function Go(t){return t.split("-")[1]}function Uh(t){return t==="x"?"y":"x"}function Bh(t){return t==="y"?"height":"width"}const uk=new Set(["top","bottom"]);function Ta(t){return uk.has(or(t))?"y":"x"}function Ph(t){return Uh(Ta(t))}function dk(t,n,r){r===void 0&&(r=!1);const s=Go(t),i=Ph(t),c=Bh(i);let u=i==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return n.reference[c]>n.floating[c]&&(u=ru(u)),[u,ru(u)]}function fk(t){const n=ru(t);return[Wm(t),n,Wm(n)]}function Wm(t){return t.replace(/start|end/g,n=>ck[n])}const d0=["left","right"],f0=["right","left"],mk=["top","bottom"],hk=["bottom","top"];function pk(t,n,r){switch(t){case"top":case"bottom":return r?n?f0:d0:n?d0:f0;case"left":case"right":return n?mk:hk;default:return[]}}function gk(t,n,r,s){const i=Go(t);let c=pk(or(t),r==="start",s);return i&&(c=c.map(u=>u+"-"+i),n&&(c=c.concat(c.map(Wm)))),c}function ru(t){return t.replace(/left|right|bottom|top/g,n=>lk[n])}function yk(t){return{top:0,right:0,bottom:0,left:0,...t}}function X1(t){return typeof t!="number"?yk(t):{top:t,right:t,bottom:t,left:t}}function su(t){const{x:n,y:r,width:s,height:i}=t;return{width:s,height:i,top:r,left:n,right:n+s,bottom:r+i,x:n,y:r}}function m0(t,n,r){let{reference:s,floating:i}=t;const c=Ta(n),u=Ph(n),f=Bh(u),g=or(n),h=c==="y",v=s.x+s.width/2-i.width/2,y=s.y+s.height/2-i.height/2,w=s[f]/2-i[f]/2;let N;switch(g){case"top":N={x:v,y:s.y-i.height};break;case"bottom":N={x:v,y:s.y+s.height};break;case"right":N={x:s.x+s.width,y};break;case"left":N={x:s.x-i.width,y};break;default:N={x:s.x,y:s.y}}switch(Go(n)){case"start":N[u]-=w*(r&&h?-1:1);break;case"end":N[u]+=w*(r&&h?-1:1);break}return N}const vk=async(t,n,r)=>{const{placement:s="bottom",strategy:i="absolute",middleware:c=[],platform:u}=r,f=c.filter(Boolean),g=await(u.isRTL==null?void 0:u.isRTL(n));let h=await u.getElementRects({reference:t,floating:n,strategy:i}),{x:v,y}=m0(h,s,g),w=s,N={},E=0;for(let S=0;S<f.length;S++){const{name:C,fn:A}=f[S],{x:O,y:R,data:L,reset:I}=await A({x:v,y,initialPlacement:s,placement:w,strategy:i,middlewareData:N,rects:h,platform:u,elements:{reference:t,floating:n}});v=O??v,y=R??y,N={...N,[C]:{...N[C],...L}},I&&E<=50&&(E++,typeof I=="object"&&(I.placement&&(w=I.placement),I.rects&&(h=I.rects===!0?await u.getElementRects({reference:t,floating:n,strategy:i}):I.rects),{x:v,y}=m0(h,w,g)),S=-1)}return{x:v,y,placement:w,strategy:i,middlewareData:N}};async function el(t,n){var r;n===void 0&&(n={});const{x:s,y:i,platform:c,rects:u,elements:f,strategy:g}=t,{boundary:h="clippingAncestors",rootBoundary:v="viewport",elementContext:y="floating",altBoundary:w=!1,padding:N=0}=sr(n,t),E=X1(N),C=f[w?y==="floating"?"reference":"floating":y],A=su(await c.getClippingRect({element:(r=await(c.isElement==null?void 0:c.isElement(C)))==null||r?C:C.contextElement||await(c.getDocumentElement==null?void 0:c.getDocumentElement(f.floating)),boundary:h,rootBoundary:v,strategy:g})),O=y==="floating"?{x:s,y:i,width:u.floating.width,height:u.floating.height}:u.reference,R=await(c.getOffsetParent==null?void 0:c.getOffsetParent(f.floating)),L=await(c.isElement==null?void 0:c.isElement(R))?await(c.getScale==null?void 0:c.getScale(R))||{x:1,y:1}:{x:1,y:1},I=su(c.convertOffsetParentRelativeRectToViewportRelativeRect?await c.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:O,offsetParent:R,strategy:g}):O);return{top:(A.top-I.top+E.top)/L.y,bottom:(I.bottom-A.bottom+E.bottom)/L.y,left:(A.left-I.left+E.left)/L.x,right:(I.right-A.right+E.right)/L.x}}const bk=t=>({name:"arrow",options:t,async fn(n){const{x:r,y:s,placement:i,rects:c,platform:u,elements:f,middlewareData:g}=n,{element:h,padding:v=0}=sr(t,n)||{};if(h==null)return{};const y=X1(v),w={x:r,y:s},N=Ph(i),E=Bh(N),S=await u.getDimensions(h),C=N==="y",A=C?"top":"left",O=C?"bottom":"right",R=C?"clientHeight":"clientWidth",L=c.reference[E]+c.reference[N]-w[N]-c.floating[E],I=w[N]-c.reference[N],ee=await(u.getOffsetParent==null?void 0:u.getOffsetParent(h));let U=ee?ee[R]:0;(!U||!await(u.isElement==null?void 0:u.isElement(ee)))&&(U=f.floating[R]||c.floating[E]);const Q=L/2-I/2,le=U/2-S[E]/2-1,ue=qr(y[A],le),me=qr(y[O],le),re=ue,X=U-S[E]-me,he=U/2-S[E]/2+Q,be=Qm(re,he,X),j=!g.arrow&&Go(i)!=null&&he!==be&&c.reference[E]/2-(he<re?ue:me)-S[E]/2<0,Z=j?he<re?he-re:he-X:0;return{[N]:w[N]+Z,data:{[N]:be,centerOffset:he-be-Z,...j&&{alignmentOffset:Z}},reset:j}}}),xk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(n){var r,s;const{placement:i,middlewareData:c,rects:u,initialPlacement:f,platform:g,elements:h}=n,{mainAxis:v=!0,crossAxis:y=!0,fallbackPlacements:w,fallbackStrategy:N="bestFit",fallbackAxisSideDirection:E="none",flipAlignment:S=!0,...C}=sr(t,n);if((r=c.arrow)!=null&&r.alignmentOffset)return{};const A=or(i),O=Ta(f),R=or(f)===f,L=await(g.isRTL==null?void 0:g.isRTL(h.floating)),I=w||(R||!S?[ru(f)]:fk(f)),ee=E!=="none";!w&&ee&&I.push(...gk(f,S,E,L));const U=[f,...I],Q=await el(n,C),le=[];let ue=((s=c.flip)==null?void 0:s.overflows)||[];if(v&&le.push(Q[A]),y){const he=dk(i,u,L);le.push(Q[he[0]],Q[he[1]])}if(ue=[...ue,{placement:i,overflows:le}],!le.every(he=>he<=0)){var me,re;const he=(((me=c.flip)==null?void 0:me.index)||0)+1,be=U[he];if(be&&(!(y==="alignment"?O!==Ta(be):!1)||ue.every(P=>Ta(P.placement)===O?P.overflows[0]>0:!0)))return{data:{index:he,overflows:ue},reset:{placement:be}};let j=(re=ue.filter(Z=>Z.overflows[0]<=0).sort((Z,P)=>Z.overflows[1]-P.overflows[1])[0])==null?void 0:re.placement;if(!j)switch(N){case"bestFit":{var X;const Z=(X=ue.filter(P=>{if(ee){const se=Ta(P.placement);return se===O||se==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(se=>se>0).reduce((se,we)=>se+we,0)]).sort((P,se)=>P[1]-se[1])[0])==null?void 0:X[0];Z&&(j=Z);break}case"initialPlacement":j=f;break}if(i!==j)return{reset:{placement:j}}}return{}}}};function h0(t,n){return{top:t.top-n.height,right:t.right-n.width,bottom:t.bottom-n.height,left:t.left-n.width}}function p0(t){return ik.some(n=>t[n]>=0)}const wk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(n){const{rects:r}=n,{strategy:s="referenceHidden",...i}=sr(t,n);switch(s){case"referenceHidden":{const c=await el(n,{...i,elementContext:"reference"}),u=h0(c,r.reference);return{data:{referenceHiddenOffsets:u,referenceHidden:p0(u)}}}case"escaped":{const c=await el(n,{...i,altBoundary:!0}),u=h0(c,r.floating);return{data:{escapedOffsets:u,escaped:p0(u)}}}default:return{}}}}},K1=new Set(["left","top"]);async function Sk(t,n){const{placement:r,platform:s,elements:i}=t,c=await(s.isRTL==null?void 0:s.isRTL(i.floating)),u=or(r),f=Go(r),g=Ta(r)==="y",h=K1.has(u)?-1:1,v=c&&g?-1:1,y=sr(n,t);let{mainAxis:w,crossAxis:N,alignmentAxis:E}=typeof y=="number"?{mainAxis:y,crossAxis:0,alignmentAxis:null}:{mainAxis:y.mainAxis||0,crossAxis:y.crossAxis||0,alignmentAxis:y.alignmentAxis};return f&&typeof E=="number"&&(N=f==="end"?E*-1:E),g?{x:N*v,y:w*h}:{x:w*h,y:N*v}}const Ek=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(n){var r,s;const{x:i,y:c,placement:u,middlewareData:f}=n,g=await Sk(n,t);return u===((r=f.offset)==null?void 0:r.placement)&&(s=f.arrow)!=null&&s.alignmentOffset?{}:{x:i+g.x,y:c+g.y,data:{...g,placement:u}}}}},_k=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(n){const{x:r,y:s,placement:i}=n,{mainAxis:c=!0,crossAxis:u=!1,limiter:f={fn:C=>{let{x:A,y:O}=C;return{x:A,y:O}}},...g}=sr(t,n),h={x:r,y:s},v=await el(n,g),y=Ta(or(i)),w=Uh(y);let N=h[w],E=h[y];if(c){const C=w==="y"?"top":"left",A=w==="y"?"bottom":"right",O=N+v[C],R=N-v[A];N=Qm(O,N,R)}if(u){const C=y==="y"?"top":"left",A=y==="y"?"bottom":"right",O=E+v[C],R=E-v[A];E=Qm(O,E,R)}const S=f.fn({...n,[w]:N,[y]:E});return{...S,data:{x:S.x-r,y:S.y-s,enabled:{[w]:c,[y]:u}}}}}},Ck=function(t){return t===void 0&&(t={}),{options:t,fn(n){const{x:r,y:s,placement:i,rects:c,middlewareData:u}=n,{offset:f=0,mainAxis:g=!0,crossAxis:h=!0}=sr(t,n),v={x:r,y:s},y=Ta(i),w=Uh(y);let N=v[w],E=v[y];const S=sr(f,n),C=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(g){const R=w==="y"?"height":"width",L=c.reference[w]-c.floating[R]+C.mainAxis,I=c.reference[w]+c.reference[R]-C.mainAxis;N<L?N=L:N>I&&(N=I)}if(h){var A,O;const R=w==="y"?"width":"height",L=K1.has(or(i)),I=c.reference[y]-c.floating[R]+(L&&((A=u.offset)==null?void 0:A[y])||0)+(L?0:C.crossAxis),ee=c.reference[y]+c.reference[R]+(L?0:((O=u.offset)==null?void 0:O[y])||0)-(L?C.crossAxis:0);E<I?E=I:E>ee&&(E=ee)}return{[w]:N,[y]:E}}}},Nk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(n){var r,s;const{placement:i,rects:c,platform:u,elements:f}=n,{apply:g=()=>{},...h}=sr(t,n),v=await el(n,h),y=or(i),w=Go(i),N=Ta(i)==="y",{width:E,height:S}=c.floating;let C,A;y==="top"||y==="bottom"?(C=y,A=w===(await(u.isRTL==null?void 0:u.isRTL(f.floating))?"start":"end")?"left":"right"):(A=y,C=w==="end"?"top":"bottom");const O=S-v.top-v.bottom,R=E-v.left-v.right,L=qr(S-v[C],O),I=qr(E-v[A],R),ee=!n.middlewareData.shift;let U=L,Q=I;if((r=n.middlewareData.shift)!=null&&r.enabled.x&&(Q=R),(s=n.middlewareData.shift)!=null&&s.enabled.y&&(U=O),ee&&!w){const ue=Bn(v.left,0),me=Bn(v.right,0),re=Bn(v.top,0),X=Bn(v.bottom,0);N?Q=E-2*(ue!==0||me!==0?ue+me:Bn(v.left,v.right)):U=S-2*(re!==0||X!==0?re+X:Bn(v.top,v.bottom))}await g({...n,availableWidth:Q,availableHeight:U});const le=await u.getDimensions(f.floating);return E!==le.width||S!==le.height?{reset:{rects:!0}}:{}}}};function Bu(){return typeof window<"u"}function Yo(t){return Q1(t)?(t.nodeName||"").toLowerCase():"#document"}function Vn(t){var n;return(t==null||(n=t.ownerDocument)==null?void 0:n.defaultView)||window}function Da(t){var n;return(n=(Q1(t)?t.ownerDocument:t.document)||window.document)==null?void 0:n.documentElement}function Q1(t){return Bu()?t instanceof Node||t instanceof Vn(t).Node:!1}function fa(t){return Bu()?t instanceof Element||t instanceof Vn(t).Element:!1}function ka(t){return Bu()?t instanceof HTMLElement||t instanceof Vn(t).HTMLElement:!1}function g0(t){return!Bu()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Vn(t).ShadowRoot}const Ak=new Set(["inline","contents"]);function ml(t){const{overflow:n,overflowX:r,overflowY:s,display:i}=ma(t);return/auto|scroll|overlay|hidden|clip/.test(n+s+r)&&!Ak.has(i)}const Rk=new Set(["table","td","th"]);function Tk(t){return Rk.has(Yo(t))}const jk=[":popover-open",":modal"];function Pu(t){return jk.some(n=>{try{return t.matches(n)}catch{return!1}})}const Ok=["transform","translate","scale","rotate","perspective"],kk=["transform","translate","scale","rotate","perspective","filter"],Mk=["paint","layout","strict","content"];function Hh(t){const n=Vh(),r=fa(t)?ma(t):t;return Ok.some(s=>r[s]?r[s]!=="none":!1)||(r.containerType?r.containerType!=="normal":!1)||!n&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!n&&(r.filter?r.filter!=="none":!1)||kk.some(s=>(r.willChange||"").includes(s))||Mk.some(s=>(r.contain||"").includes(s))}function Dk(t){let n=Fr(t);for(;ka(n)&&!jo(n);){if(Hh(n))return n;if(Pu(n))return null;n=Fr(n)}return null}function Vh(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const zk=new Set(["html","body","#document"]);function jo(t){return zk.has(Yo(t))}function ma(t){return Vn(t).getComputedStyle(t)}function Hu(t){return fa(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Fr(t){if(Yo(t)==="html")return t;const n=t.assignedSlot||t.parentNode||g0(t)&&t.host||Da(t);return g0(n)?n.host:n}function W1(t){const n=Fr(t);return jo(n)?t.ownerDocument?t.ownerDocument.body:t.body:ka(n)&&ml(n)?n:W1(n)}function tl(t,n,r){var s;n===void 0&&(n=[]),r===void 0&&(r=!0);const i=W1(t),c=i===((s=t.ownerDocument)==null?void 0:s.body),u=Vn(i);if(c){const f=Jm(u);return n.concat(u,u.visualViewport||[],ml(i)?i:[],f&&r?tl(f):[])}return n.concat(i,tl(i,[],r))}function Jm(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function J1(t){const n=ma(t);let r=parseFloat(n.width)||0,s=parseFloat(n.height)||0;const i=ka(t),c=i?t.offsetWidth:r,u=i?t.offsetHeight:s,f=au(r)!==c||au(s)!==u;return f&&(r=c,s=u),{width:r,height:s,$:f}}function Ih(t){return fa(t)?t:t.contextElement}function Ao(t){const n=Ih(t);if(!ka(n))return ja(1);const r=n.getBoundingClientRect(),{width:s,height:i,$:c}=J1(n);let u=(c?au(r.width):r.width)/s,f=(c?au(r.height):r.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const Lk=ja(0);function ew(t){const n=Vn(t);return!Vh()||!n.visualViewport?Lk:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Uk(t,n,r){return n===void 0&&(n=!1),!r||n&&r!==Vn(t)?!1:n}function ws(t,n,r,s){n===void 0&&(n=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),c=Ih(t);let u=ja(1);n&&(s?fa(s)&&(u=Ao(s)):u=Ao(t));const f=Uk(c,r,s)?ew(c):ja(0);let g=(i.left+f.x)/u.x,h=(i.top+f.y)/u.y,v=i.width/u.x,y=i.height/u.y;if(c){const w=Vn(c),N=s&&fa(s)?Vn(s):s;let E=w,S=Jm(E);for(;S&&s&&N!==E;){const C=Ao(S),A=S.getBoundingClientRect(),O=ma(S),R=A.left+(S.clientLeft+parseFloat(O.paddingLeft))*C.x,L=A.top+(S.clientTop+parseFloat(O.paddingTop))*C.y;g*=C.x,h*=C.y,v*=C.x,y*=C.y,g+=R,h+=L,E=Vn(S),S=Jm(E)}}return su({width:v,height:y,x:g,y:h})}function Vu(t,n){const r=Hu(t).scrollLeft;return n?n.left+r:ws(Da(t)).left+r}function tw(t,n){const r=t.getBoundingClientRect(),s=r.left+n.scrollLeft-Vu(t,r),i=r.top+n.scrollTop;return{x:s,y:i}}function Bk(t){let{elements:n,rect:r,offsetParent:s,strategy:i}=t;const c=i==="fixed",u=Da(s),f=n?Pu(n.floating):!1;if(s===u||f&&c)return r;let g={scrollLeft:0,scrollTop:0},h=ja(1);const v=ja(0),y=ka(s);if((y||!y&&!c)&&((Yo(s)!=="body"||ml(u))&&(g=Hu(s)),ka(s))){const N=ws(s);h=Ao(s),v.x=N.x+s.clientLeft,v.y=N.y+s.clientTop}const w=u&&!y&&!c?tw(u,g):ja(0);return{width:r.width*h.x,height:r.height*h.y,x:r.x*h.x-g.scrollLeft*h.x+v.x+w.x,y:r.y*h.y-g.scrollTop*h.y+v.y+w.y}}function Pk(t){return Array.from(t.getClientRects())}function Hk(t){const n=Da(t),r=Hu(t),s=t.ownerDocument.body,i=Bn(n.scrollWidth,n.clientWidth,s.scrollWidth,s.clientWidth),c=Bn(n.scrollHeight,n.clientHeight,s.scrollHeight,s.clientHeight);let u=-r.scrollLeft+Vu(t);const f=-r.scrollTop;return ma(s).direction==="rtl"&&(u+=Bn(n.clientWidth,s.clientWidth)-i),{width:i,height:c,x:u,y:f}}const y0=25;function Vk(t,n){const r=Vn(t),s=Da(t),i=r.visualViewport;let c=s.clientWidth,u=s.clientHeight,f=0,g=0;if(i){c=i.width,u=i.height;const v=Vh();(!v||v&&n==="fixed")&&(f=i.offsetLeft,g=i.offsetTop)}const h=Vu(s);if(h<=0){const v=s.ownerDocument,y=v.body,w=getComputedStyle(y),N=v.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,E=Math.abs(s.clientWidth-y.clientWidth-N);E<=y0&&(c-=E)}else h<=y0&&(c+=h);return{width:c,height:u,x:f,y:g}}const Ik=new Set(["absolute","fixed"]);function qk(t,n){const r=ws(t,!0,n==="fixed"),s=r.top+t.clientTop,i=r.left+t.clientLeft,c=ka(t)?Ao(t):ja(1),u=t.clientWidth*c.x,f=t.clientHeight*c.y,g=i*c.x,h=s*c.y;return{width:u,height:f,x:g,y:h}}function v0(t,n,r){let s;if(n==="viewport")s=Vk(t,r);else if(n==="document")s=Hk(Da(t));else if(fa(n))s=qk(n,r);else{const i=ew(t);s={x:n.x-i.x,y:n.y-i.y,width:n.width,height:n.height}}return su(s)}function nw(t,n){const r=Fr(t);return r===n||!fa(r)||jo(r)?!1:ma(r).position==="fixed"||nw(r,n)}function Fk(t,n){const r=n.get(t);if(r)return r;let s=tl(t,[],!1).filter(f=>fa(f)&&Yo(f)!=="body"),i=null;const c=ma(t).position==="fixed";let u=c?Fr(t):t;for(;fa(u)&&!jo(u);){const f=ma(u),g=Hh(u);!g&&f.position==="fixed"&&(i=null),(c?!g&&!i:!g&&f.position==="static"&&!!i&&Ik.has(i.position)||ml(u)&&!g&&nw(t,u))?s=s.filter(v=>v!==u):i=f,u=Fr(u)}return n.set(t,s),s}function $k(t){let{element:n,boundary:r,rootBoundary:s,strategy:i}=t;const u=[...r==="clippingAncestors"?Pu(n)?[]:Fk(n,this._c):[].concat(r),s],f=u[0],g=u.reduce((h,v)=>{const y=v0(n,v,i);return h.top=Bn(y.top,h.top),h.right=qr(y.right,h.right),h.bottom=qr(y.bottom,h.bottom),h.left=Bn(y.left,h.left),h},v0(n,f,i));return{width:g.right-g.left,height:g.bottom-g.top,x:g.left,y:g.top}}function Gk(t){const{width:n,height:r}=J1(t);return{width:n,height:r}}function Yk(t,n,r){const s=ka(n),i=Da(n),c=r==="fixed",u=ws(t,!0,c,n);let f={scrollLeft:0,scrollTop:0};const g=ja(0);function h(){g.x=Vu(i)}if(s||!s&&!c)if((Yo(n)!=="body"||ml(i))&&(f=Hu(n)),s){const N=ws(n,!0,c,n);g.x=N.x+n.clientLeft,g.y=N.y+n.clientTop}else i&&h();c&&!s&&i&&h();const v=i&&!s&&!c?tw(i,f):ja(0),y=u.left+f.scrollLeft-g.x-v.x,w=u.top+f.scrollTop-g.y-v.y;return{x:y,y:w,width:u.width,height:u.height}}function Am(t){return ma(t).position==="static"}function b0(t,n){if(!ka(t)||ma(t).position==="fixed")return null;if(n)return n(t);let r=t.offsetParent;return Da(t)===r&&(r=r.ownerDocument.body),r}function aw(t,n){const r=Vn(t);if(Pu(t))return r;if(!ka(t)){let i=Fr(t);for(;i&&!jo(i);){if(fa(i)&&!Am(i))return i;i=Fr(i)}return r}let s=b0(t,n);for(;s&&Tk(s)&&Am(s);)s=b0(s,n);return s&&jo(s)&&Am(s)&&!Hh(s)?r:s||Dk(t)||r}const Zk=async function(t){const n=this.getOffsetParent||aw,r=this.getDimensions,s=await r(t.floating);return{reference:Yk(t.reference,await n(t.floating),t.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function Xk(t){return ma(t).direction==="rtl"}const Kk={convertOffsetParentRelativeRectToViewportRelativeRect:Bk,getDocumentElement:Da,getClippingRect:$k,getOffsetParent:aw,getElementRects:Zk,getClientRects:Pk,getDimensions:Gk,getScale:Ao,isElement:fa,isRTL:Xk};function rw(t,n){return t.x===n.x&&t.y===n.y&&t.width===n.width&&t.height===n.height}function Qk(t,n){let r=null,s;const i=Da(t);function c(){var f;clearTimeout(s),(f=r)==null||f.disconnect(),r=null}function u(f,g){f===void 0&&(f=!1),g===void 0&&(g=1),c();const h=t.getBoundingClientRect(),{left:v,top:y,width:w,height:N}=h;if(f||n(),!w||!N)return;const E=Hc(y),S=Hc(i.clientWidth-(v+w)),C=Hc(i.clientHeight-(y+N)),A=Hc(v),R={rootMargin:-E+"px "+-S+"px "+-C+"px "+-A+"px",threshold:Bn(0,qr(1,g))||1};let L=!0;function I(ee){const U=ee[0].intersectionRatio;if(U!==g){if(!L)return u();U?u(!1,U):s=setTimeout(()=>{u(!1,1e-7)},1e3)}U===1&&!rw(h,t.getBoundingClientRect())&&u(),L=!1}try{r=new IntersectionObserver(I,{...R,root:i.ownerDocument})}catch{r=new IntersectionObserver(I,R)}r.observe(t)}return u(!0),c}function Wk(t,n,r,s){s===void 0&&(s={});const{ancestorScroll:i=!0,ancestorResize:c=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:g=!1}=s,h=Ih(t),v=i||c?[...h?tl(h):[],...tl(n)]:[];v.forEach(A=>{i&&A.addEventListener("scroll",r,{passive:!0}),c&&A.addEventListener("resize",r)});const y=h&&f?Qk(h,r):null;let w=-1,N=null;u&&(N=new ResizeObserver(A=>{let[O]=A;O&&O.target===h&&N&&(N.unobserve(n),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var R;(R=N)==null||R.observe(n)})),r()}),h&&!g&&N.observe(h),N.observe(n));let E,S=g?ws(t):null;g&&C();function C(){const A=ws(t);S&&!rw(S,A)&&r(),S=A,E=requestAnimationFrame(C)}return r(),()=>{var A;v.forEach(O=>{i&&O.removeEventListener("scroll",r),c&&O.removeEventListener("resize",r)}),y==null||y(),(A=N)==null||A.disconnect(),N=null,g&&cancelAnimationFrame(E)}}const Jk=Ek,eM=_k,tM=xk,nM=Nk,aM=wk,x0=bk,rM=Ck,sM=(t,n,r)=>{const s=new Map,i={platform:Kk,...r},c={...i.platform,_c:s};return vk(t,n,{...i,platform:c})};var oM=typeof document<"u",iM=function(){},Qc=oM?b.useLayoutEffect:iM;function ou(t,n){if(t===n)return!0;if(typeof t!=typeof n)return!1;if(typeof t=="function"&&t.toString()===n.toString())return!0;let r,s,i;if(t&&n&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==n.length)return!1;for(s=r;s--!==0;)if(!ou(t[s],n[s]))return!1;return!0}if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(n,i[s]))return!1;for(s=r;s--!==0;){const c=i[s];if(!(c==="_owner"&&t.$$typeof)&&!ou(t[c],n[c]))return!1}return!0}return t!==t&&n!==n}function sw(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function w0(t,n){const r=sw(t);return Math.round(n*r)/r}function Rm(t){const n=b.useRef(t);return Qc(()=>{n.current=t}),n}function lM(t){t===void 0&&(t={});const{placement:n="bottom",strategy:r="absolute",middleware:s=[],platform:i,elements:{reference:c,floating:u}={},transform:f=!0,whileElementsMounted:g,open:h}=t,[v,y]=b.useState({x:0,y:0,strategy:r,placement:n,middlewareData:{},isPositioned:!1}),[w,N]=b.useState(s);ou(w,s)||N(s);const[E,S]=b.useState(null),[C,A]=b.useState(null),O=b.useCallback(P=>{P!==ee.current&&(ee.current=P,S(P))},[]),R=b.useCallback(P=>{P!==U.current&&(U.current=P,A(P))},[]),L=c||E,I=u||C,ee=b.useRef(null),U=b.useRef(null),Q=b.useRef(v),le=g!=null,ue=Rm(g),me=Rm(i),re=Rm(h),X=b.useCallback(()=>{if(!ee.current||!U.current)return;const P={placement:n,strategy:r,middleware:w};me.current&&(P.platform=me.current),sM(ee.current,U.current,P).then(se=>{const we={...se,isPositioned:re.current!==!1};he.current&&!ou(Q.current,we)&&(Q.current=we,wh.flushSync(()=>{y(we)}))})},[w,n,r,me,re]);Qc(()=>{h===!1&&Q.current.isPositioned&&(Q.current.isPositioned=!1,y(P=>({...P,isPositioned:!1})))},[h]);const he=b.useRef(!1);Qc(()=>(he.current=!0,()=>{he.current=!1}),[]),Qc(()=>{if(L&&(ee.current=L),I&&(U.current=I),L&&I){if(ue.current)return ue.current(L,I,X);X()}},[L,I,X,ue,le]);const be=b.useMemo(()=>({reference:ee,floating:U,setReference:O,setFloating:R}),[O,R]),j=b.useMemo(()=>({reference:L,floating:I}),[L,I]),Z=b.useMemo(()=>{const P={position:r,left:0,top:0};if(!j.floating)return P;const se=w0(j.floating,v.x),we=w0(j.floating,v.y);return f?{...P,transform:"translate("+se+"px, "+we+"px)",...sw(j.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:se,top:we}},[r,f,j.floating,v.x,v.y]);return b.useMemo(()=>({...v,update:X,refs:be,elements:j,floatingStyles:Z}),[v,X,be,j,Z])}const cM=t=>{function n(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:s,padding:i}=typeof t=="function"?t(r):t;return s&&n(s)?s.current!=null?x0({element:s.current,padding:i}).fn(r):{}:s?x0({element:s,padding:i}).fn(r):{}}}},uM=(t,n)=>({...Jk(t),options:[t,n]}),dM=(t,n)=>({...eM(t),options:[t,n]}),fM=(t,n)=>({...rM(t),options:[t,n]}),mM=(t,n)=>({...tM(t),options:[t,n]}),hM=(t,n)=>({...nM(t),options:[t,n]}),pM=(t,n)=>({...aM(t),options:[t,n]}),gM=(t,n)=>({...cM(t),options:[t,n]});var yM="Arrow",ow=b.forwardRef((t,n)=>{const{children:r,width:s=10,height:i=5,...c}=t;return p.jsx(jt.svg,{...c,ref:n,width:s,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:p.jsx("polygon",{points:"0,0 30,0 15,10"})})});ow.displayName=yM;var vM=ow,qh="Popper",[iw,Iu]=_s(qh),[bM,lw]=iw(qh),cw=t=>{const{__scopePopper:n,children:r}=t,[s,i]=b.useState(null);return p.jsx(bM,{scope:n,anchor:s,onAnchorChange:i,children:r})};cw.displayName=qh;var uw="PopperAnchor",dw=b.forwardRef((t,n)=>{const{__scopePopper:r,virtualRef:s,...i}=t,c=lw(uw,r),u=b.useRef(null),f=Zt(n,u),g=b.useRef(null);return b.useEffect(()=>{const h=g.current;g.current=(s==null?void 0:s.current)||u.current,h!==g.current&&c.onAnchorChange(g.current)}),s?null:p.jsx(jt.div,{...i,ref:f})});dw.displayName=uw;var Fh="PopperContent",[xM,wM]=iw(Fh),fw=b.forwardRef((t,n)=>{var oe,K,de,_e,rt,De;const{__scopePopper:r,side:s="bottom",sideOffset:i=0,align:c="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:g=!0,collisionBoundary:h=[],collisionPadding:v=0,sticky:y="partial",hideWhenDetached:w=!1,updatePositionStrategy:N="optimized",onPlaced:E,...S}=t,C=lw(Fh,r),[A,O]=b.useState(null),R=Zt(n,Le=>O(Le)),[L,I]=b.useState(null),ee=ok(L),U=(ee==null?void 0:ee.width)??0,Q=(ee==null?void 0:ee.height)??0,le=s+(c!=="center"?"-"+c:""),ue=typeof v=="number"?v:{top:0,right:0,bottom:0,left:0,...v},me=Array.isArray(h)?h:[h],re=me.length>0,X={padding:ue,boundary:me.filter(EM),altBoundary:re},{refs:he,floatingStyles:be,placement:j,isPositioned:Z,middlewareData:P}=lM({strategy:"fixed",placement:le,whileElementsMounted:(...Le)=>Wk(...Le,{animationFrame:N==="always"}),elements:{reference:C.anchor},middleware:[uM({mainAxis:i+Q,alignmentAxis:u}),g&&dM({mainAxis:!0,crossAxis:!1,limiter:y==="partial"?fM():void 0,...X}),g&&mM({...X}),hM({...X,apply:({elements:Le,rects:xe,availableWidth:je,availableHeight:at})=>{const{width:pt,height:Je}=xe.reference,Ue=Le.floating.style;Ue.setProperty("--radix-popper-available-width",`${je}px`),Ue.setProperty("--radix-popper-available-height",`${at}px`),Ue.setProperty("--radix-popper-anchor-width",`${pt}px`),Ue.setProperty("--radix-popper-anchor-height",`${Je}px`)}}),L&&gM({element:L,padding:f}),_M({arrowWidth:U,arrowHeight:Q}),w&&pM({strategy:"referenceHidden",...X})]}),[se,we]=pw(j),T=rr(E);Ir(()=>{Z&&(T==null||T())},[Z,T]);const Y=(oe=P.arrow)==null?void 0:oe.x,D=(K=P.arrow)==null?void 0:K.y,V=((de=P.arrow)==null?void 0:de.centerOffset)!==0,[te,fe]=b.useState();return Ir(()=>{A&&fe(window.getComputedStyle(A).zIndex)},[A]),p.jsx("div",{ref:he.setFloating,"data-radix-popper-content-wrapper":"",style:{...be,transform:Z?be.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:te,"--radix-popper-transform-origin":[(_e=P.transformOrigin)==null?void 0:_e.x,(rt=P.transformOrigin)==null?void 0:rt.y].join(" "),...((De=P.hide)==null?void 0:De.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:p.jsx(xM,{scope:r,placedSide:se,onArrowChange:I,arrowX:Y,arrowY:D,shouldHideArrow:V,children:p.jsx(jt.div,{"data-side":se,"data-align":we,...S,ref:R,style:{...S.style,animation:Z?void 0:"none"}})})})});fw.displayName=Fh;var mw="PopperArrow",SM={top:"bottom",right:"left",bottom:"top",left:"right"},hw=b.forwardRef(function(n,r){const{__scopePopper:s,...i}=n,c=wM(mw,s),u=SM[c.placedSide];return p.jsx("span",{ref:c.onArrowChange,style:{position:"absolute",left:c.arrowX,top:c.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[c.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[c.placedSide],visibility:c.shouldHideArrow?"hidden":void 0},children:p.jsx(vM,{...i,ref:r,style:{...i.style,display:"block"}})})});hw.displayName=mw;function EM(t){return t!==null}var _M=t=>({name:"transformOrigin",options:t,fn(n){var C,A,O;const{placement:r,rects:s,middlewareData:i}=n,u=((C=i.arrow)==null?void 0:C.centerOffset)!==0,f=u?0:t.arrowWidth,g=u?0:t.arrowHeight,[h,v]=pw(r),y={start:"0%",center:"50%",end:"100%"}[v],w=(((A=i.arrow)==null?void 0:A.x)??0)+f/2,N=(((O=i.arrow)==null?void 0:O.y)??0)+g/2;let E="",S="";return h==="bottom"?(E=u?y:`${w}px`,S=`${-g}px`):h==="top"?(E=u?y:`${w}px`,S=`${s.floating.height+g}px`):h==="right"?(E=`${-g}px`,S=u?y:`${N}px`):h==="left"&&(E=`${s.floating.width+g}px`,S=u?y:`${N}px`),{data:{x:E,y:S}}}});function pw(t){const[n,r="center"]=t.split("-");return[n,r]}var CM=cw,$h=dw,gw=fw,yw=hw,Tm="rovingFocusGroup.onEntryFocus",NM={bubbles:!1,cancelable:!0},hl="RovingFocusGroup",[eh,vw,AM]=h1(hl),[RM,bw]=_s(hl,[AM]),[TM,jM]=RM(hl),xw=b.forwardRef((t,n)=>p.jsx(eh.Provider,{scope:t.__scopeRovingFocusGroup,children:p.jsx(eh.Slot,{scope:t.__scopeRovingFocusGroup,children:p.jsx(OM,{...t,ref:n})})}));xw.displayName=hl;var OM=b.forwardRef((t,n)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:i=!1,dir:c,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:g,onEntryFocus:h,preventScrollOnEntryFocus:v=!1,...y}=t,w=b.useRef(null),N=Zt(n,w),E=g1(c),[S,C]=jh({prop:u,defaultProp:f??null,onChange:g,caller:hl}),[A,O]=b.useState(!1),R=rr(h),L=vw(r),I=b.useRef(!1),[ee,U]=b.useState(0);return b.useEffect(()=>{const Q=w.current;if(Q)return Q.addEventListener(Tm,R),()=>Q.removeEventListener(Tm,R)},[R]),p.jsx(TM,{scope:r,orientation:s,dir:E,loop:i,currentTabStopId:S,onItemFocus:b.useCallback(Q=>C(Q),[C]),onItemShiftTab:b.useCallback(()=>O(!0),[]),onFocusableItemAdd:b.useCallback(()=>U(Q=>Q+1),[]),onFocusableItemRemove:b.useCallback(()=>U(Q=>Q-1),[]),children:p.jsx(jt.div,{tabIndex:A||ee===0?-1:0,"data-orientation":s,...y,ref:N,style:{outline:"none",...t.style},onMouseDown:Ve(t.onMouseDown,()=>{I.current=!0}),onFocus:Ve(t.onFocus,Q=>{const le=!I.current;if(Q.target===Q.currentTarget&&le&&!A){const ue=new CustomEvent(Tm,NM);if(Q.currentTarget.dispatchEvent(ue),!ue.defaultPrevented){const me=L().filter(j=>j.focusable),re=me.find(j=>j.active),X=me.find(j=>j.id===S),be=[re,X,...me].filter(Boolean).map(j=>j.ref.current);Ew(be,v)}}I.current=!1}),onBlur:Ve(t.onBlur,()=>O(!1))})})}),ww="RovingFocusGroupItem",Sw=b.forwardRef((t,n)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:i=!1,tabStopId:c,children:u,...f}=t,g=Co(),h=c||g,v=jM(ww,r),y=v.currentTabStopId===h,w=vw(r),{onFocusableItemAdd:N,onFocusableItemRemove:E,currentTabStopId:S}=v;return b.useEffect(()=>{if(s)return N(),()=>E()},[s,N,E]),p.jsx(eh.ItemSlot,{scope:r,id:h,focusable:s,active:i,children:p.jsx(jt.span,{tabIndex:y?0:-1,"data-orientation":v.orientation,...f,ref:n,onMouseDown:Ve(t.onMouseDown,C=>{s?v.onItemFocus(h):C.preventDefault()}),onFocus:Ve(t.onFocus,()=>v.onItemFocus(h)),onKeyDown:Ve(t.onKeyDown,C=>{if(C.key==="Tab"&&C.shiftKey){v.onItemShiftTab();return}if(C.target!==C.currentTarget)return;const A=DM(C,v.orientation,v.dir);if(A!==void 0){if(C.metaKey||C.ctrlKey||C.altKey||C.shiftKey)return;C.preventDefault();let R=w().filter(L=>L.focusable).map(L=>L.ref.current);if(A==="last")R.reverse();else if(A==="prev"||A==="next"){A==="prev"&&R.reverse();const L=R.indexOf(C.currentTarget);R=v.loop?zM(R,L+1):R.slice(L+1)}setTimeout(()=>Ew(R))}}),children:typeof u=="function"?u({isCurrentTabStop:y,hasTabStop:S!=null}):u})})});Sw.displayName=ww;var kM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function MM(t,n){return n!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function DM(t,n,r){const s=MM(t.key,r);if(!(n==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(n==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return kM[s]}function Ew(t,n=!1){const r=document.activeElement;for(const s of t)if(s===r||(s.focus({preventScroll:n}),document.activeElement!==r))return}function zM(t,n){return t.map((r,s)=>t[(n+s)%t.length])}var LM=xw,UM=Sw;function BM(t){const n=PM(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(VM);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function PM(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=qM(i),f=IM(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var HM=Symbol("radix.slottable");function VM(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===HM}function IM(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function qM(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var th=["Enter"," "],FM=["ArrowDown","PageUp","Home"],_w=["ArrowUp","PageDown","End"],$M=[...FM,..._w],GM={ltr:[...th,"ArrowRight"],rtl:[...th,"ArrowLeft"]},YM={ltr:["ArrowLeft"],rtl:["ArrowRight"]},pl="Menu",[nl,ZM,XM]=h1(pl),[Cs,Cw]=_s(pl,[XM,Iu,bw]),qu=Iu(),Nw=bw(),[KM,Ns]=Cs(pl),[QM,gl]=Cs(pl),Aw=t=>{const{__scopeMenu:n,open:r=!1,children:s,dir:i,onOpenChange:c,modal:u=!0}=t,f=qu(n),[g,h]=b.useState(null),v=b.useRef(!1),y=rr(c),w=g1(i);return b.useEffect(()=>{const N=()=>{v.current=!0,document.addEventListener("pointerdown",E,{capture:!0,once:!0}),document.addEventListener("pointermove",E,{capture:!0,once:!0})},E=()=>v.current=!1;return document.addEventListener("keydown",N,{capture:!0}),()=>{document.removeEventListener("keydown",N,{capture:!0}),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointermove",E,{capture:!0})}},[]),p.jsx(CM,{...f,children:p.jsx(KM,{scope:n,open:r,onOpenChange:y,content:g,onContentChange:h,children:p.jsx(QM,{scope:n,onClose:b.useCallback(()=>y(!1),[y]),isUsingKeyboardRef:v,dir:w,modal:u,children:s})})})};Aw.displayName=pl;var WM="MenuAnchor",Gh=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t,i=qu(r);return p.jsx($h,{...i,...s,ref:n})});Gh.displayName=WM;var Yh="MenuPortal",[JM,Rw]=Cs(Yh,{forceMount:void 0}),Tw=t=>{const{__scopeMenu:n,forceMount:r,children:s,container:i}=t,c=Ns(Yh,n);return p.jsx(JM,{scope:n,forceMount:r,children:p.jsx(Ma,{present:r||c.open,children:p.jsx(Du,{asChild:!0,container:i,children:s})})})};Tw.displayName=Yh;var na="MenuContent",[eD,Zh]=Cs(na),jw=b.forwardRef((t,n)=>{const r=Rw(na,t.__scopeMenu),{forceMount:s=r.forceMount,...i}=t,c=Ns(na,t.__scopeMenu),u=gl(na,t.__scopeMenu);return p.jsx(nl.Provider,{scope:t.__scopeMenu,children:p.jsx(Ma,{present:s||c.open,children:p.jsx(nl.Slot,{scope:t.__scopeMenu,children:u.modal?p.jsx(tD,{...i,ref:n}):p.jsx(nD,{...i,ref:n})})})})}),tD=b.forwardRef((t,n)=>{const r=Ns(na,t.__scopeMenu),s=b.useRef(null),i=Zt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return Mh(c)},[]),p.jsx(Xh,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Ve(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),nD=b.forwardRef((t,n)=>{const r=Ns(na,t.__scopeMenu);return p.jsx(Xh,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),aD=BM("MenuContent.ScrollLock"),Xh=b.forwardRef((t,n)=>{const{__scopeMenu:r,loop:s=!1,trapFocus:i,onOpenAutoFocus:c,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:g,onEscapeKeyDown:h,onPointerDownOutside:v,onFocusOutside:y,onInteractOutside:w,onDismiss:N,disableOutsideScroll:E,...S}=t,C=Ns(na,r),A=gl(na,r),O=qu(r),R=Nw(r),L=ZM(r),[I,ee]=b.useState(null),U=b.useRef(null),Q=Zt(n,U,C.onContentChange),le=b.useRef(0),ue=b.useRef(""),me=b.useRef(0),re=b.useRef(null),X=b.useRef("right"),he=b.useRef(0),be=E?Lu:b.Fragment,j=E?{as:aD,allowPinchZoom:!0}:void 0,Z=se=>{var oe,K;const we=ue.current+se,T=L().filter(de=>!de.disabled),Y=document.activeElement,D=(oe=T.find(de=>de.ref.current===Y))==null?void 0:oe.textValue,V=T.map(de=>de.textValue),te=pD(V,we,D),fe=(K=T.find(de=>de.textValue===te))==null?void 0:K.ref.current;(function de(_e){ue.current=_e,window.clearTimeout(le.current),_e!==""&&(le.current=window.setTimeout(()=>de(""),1e3))})(we),fe&&setTimeout(()=>fe.focus())};b.useEffect(()=>()=>window.clearTimeout(le.current),[]),kh();const P=b.useCallback(se=>{var T,Y;return X.current===((T=re.current)==null?void 0:T.side)&&yD(se,(Y=re.current)==null?void 0:Y.area)},[]);return p.jsx(eD,{scope:r,searchRef:ue,onItemEnter:b.useCallback(se=>{P(se)&&se.preventDefault()},[P]),onItemLeave:b.useCallback(se=>{var we;P(se)||((we=U.current)==null||we.focus(),ee(null))},[P]),onTriggerLeave:b.useCallback(se=>{P(se)&&se.preventDefault()},[P]),pointerGraceTimerRef:me,onPointerGraceIntentChange:b.useCallback(se=>{re.current=se},[]),children:p.jsx(be,{...j,children:p.jsx(Mu,{asChild:!0,trapped:i,onMountAutoFocus:Ve(c,se=>{var we;se.preventDefault(),(we=U.current)==null||we.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:p.jsx(ku,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:h,onPointerDownOutside:v,onFocusOutside:y,onInteractOutside:w,onDismiss:N,children:p.jsx(LM,{asChild:!0,...R,dir:A.dir,orientation:"vertical",loop:s,currentTabStopId:I,onCurrentTabStopIdChange:ee,onEntryFocus:Ve(g,se=>{A.isUsingKeyboardRef.current||se.preventDefault()}),preventScrollOnEntryFocus:!0,children:p.jsx(gw,{role:"menu","aria-orientation":"vertical","data-state":Gw(C.open),"data-radix-menu-content":"",dir:A.dir,...O,...S,ref:Q,style:{outline:"none",...S.style},onKeyDown:Ve(S.onKeyDown,se=>{const T=se.target.closest("[data-radix-menu-content]")===se.currentTarget,Y=se.ctrlKey||se.altKey||se.metaKey,D=se.key.length===1;T&&(se.key==="Tab"&&se.preventDefault(),!Y&&D&&Z(se.key));const V=U.current;if(se.target!==V||!$M.includes(se.key))return;se.preventDefault();const fe=L().filter(oe=>!oe.disabled).map(oe=>oe.ref.current);_w.includes(se.key)&&fe.reverse(),mD(fe)}),onBlur:Ve(t.onBlur,se=>{se.currentTarget.contains(se.target)||(window.clearTimeout(le.current),ue.current="")}),onPointerMove:Ve(t.onPointerMove,al(se=>{const we=se.target,T=he.current!==se.clientX;if(se.currentTarget.contains(we)&&T){const Y=se.clientX>he.current?"right":"left";X.current=Y,he.current=se.clientX}}))})})})})})})});jw.displayName=na;var rD="MenuGroup",Kh=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return p.jsx(jt.div,{role:"group",...s,ref:n})});Kh.displayName=rD;var sD="MenuLabel",Ow=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return p.jsx(jt.div,{...s,ref:n})});Ow.displayName=sD;var iu="MenuItem",S0="menu.itemSelect",Fu=b.forwardRef((t,n)=>{const{disabled:r=!1,onSelect:s,...i}=t,c=b.useRef(null),u=gl(iu,t.__scopeMenu),f=Zh(iu,t.__scopeMenu),g=Zt(n,c),h=b.useRef(!1),v=()=>{const y=c.current;if(!r&&y){const w=new CustomEvent(S0,{bubbles:!0,cancelable:!0});y.addEventListener(S0,N=>s==null?void 0:s(N),{once:!0}),p1(y,w),w.defaultPrevented?h.current=!1:u.onClose()}};return p.jsx(kw,{...i,ref:g,disabled:r,onClick:Ve(t.onClick,v),onPointerDown:y=>{var w;(w=t.onPointerDown)==null||w.call(t,y),h.current=!0},onPointerUp:Ve(t.onPointerUp,y=>{var w;h.current||(w=y.currentTarget)==null||w.click()}),onKeyDown:Ve(t.onKeyDown,y=>{const w=f.searchRef.current!=="";r||w&&y.key===" "||th.includes(y.key)&&(y.currentTarget.click(),y.preventDefault())})})});Fu.displayName=iu;var kw=b.forwardRef((t,n)=>{const{__scopeMenu:r,disabled:s=!1,textValue:i,...c}=t,u=Zh(iu,r),f=Nw(r),g=b.useRef(null),h=Zt(n,g),[v,y]=b.useState(!1),[w,N]=b.useState("");return b.useEffect(()=>{const E=g.current;E&&N((E.textContent??"").trim())},[c.children]),p.jsx(nl.ItemSlot,{scope:r,disabled:s,textValue:i??w,children:p.jsx(UM,{asChild:!0,...f,focusable:!s,children:p.jsx(jt.div,{role:"menuitem","data-highlighted":v?"":void 0,"aria-disabled":s||void 0,"data-disabled":s?"":void 0,...c,ref:h,onPointerMove:Ve(t.onPointerMove,al(E=>{s?u.onItemLeave(E):(u.onItemEnter(E),E.defaultPrevented||E.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ve(t.onPointerLeave,al(E=>u.onItemLeave(E))),onFocus:Ve(t.onFocus,()=>y(!0)),onBlur:Ve(t.onBlur,()=>y(!1))})})})}),oD="MenuCheckboxItem",Mw=b.forwardRef((t,n)=>{const{checked:r=!1,onCheckedChange:s,...i}=t;return p.jsx(Bw,{scope:t.__scopeMenu,checked:r,children:p.jsx(Fu,{role:"menuitemcheckbox","aria-checked":lu(r)?"mixed":r,...i,ref:n,"data-state":Wh(r),onSelect:Ve(i.onSelect,()=>s==null?void 0:s(lu(r)?!0:!r),{checkForDefaultPrevented:!1})})})});Mw.displayName=oD;var Dw="MenuRadioGroup",[iD,lD]=Cs(Dw,{value:void 0,onValueChange:()=>{}}),zw=b.forwardRef((t,n)=>{const{value:r,onValueChange:s,...i}=t,c=rr(s);return p.jsx(iD,{scope:t.__scopeMenu,value:r,onValueChange:c,children:p.jsx(Kh,{...i,ref:n})})});zw.displayName=Dw;var Lw="MenuRadioItem",Uw=b.forwardRef((t,n)=>{const{value:r,...s}=t,i=lD(Lw,t.__scopeMenu),c=r===i.value;return p.jsx(Bw,{scope:t.__scopeMenu,checked:c,children:p.jsx(Fu,{role:"menuitemradio","aria-checked":c,...s,ref:n,"data-state":Wh(c),onSelect:Ve(s.onSelect,()=>{var u;return(u=i.onValueChange)==null?void 0:u.call(i,r)},{checkForDefaultPrevented:!1})})})});Uw.displayName=Lw;var Qh="MenuItemIndicator",[Bw,cD]=Cs(Qh,{checked:!1}),Pw=b.forwardRef((t,n)=>{const{__scopeMenu:r,forceMount:s,...i}=t,c=cD(Qh,r);return p.jsx(Ma,{present:s||lu(c.checked)||c.checked===!0,children:p.jsx(jt.span,{...i,ref:n,"data-state":Wh(c.checked)})})});Pw.displayName=Qh;var uD="MenuSeparator",Hw=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return p.jsx(jt.div,{role:"separator","aria-orientation":"horizontal",...s,ref:n})});Hw.displayName=uD;var dD="MenuArrow",Vw=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t,i=qu(r);return p.jsx(yw,{...i,...s,ref:n})});Vw.displayName=dD;var fD="MenuSub",[eL,Iw]=Cs(fD),Gi="MenuSubTrigger",qw=b.forwardRef((t,n)=>{const r=Ns(Gi,t.__scopeMenu),s=gl(Gi,t.__scopeMenu),i=Iw(Gi,t.__scopeMenu),c=Zh(Gi,t.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:g}=c,h={__scopeMenu:t.__scopeMenu},v=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);return b.useEffect(()=>v,[v]),b.useEffect(()=>{const y=f.current;return()=>{window.clearTimeout(y),g(null)}},[f,g]),p.jsx(Gh,{asChild:!0,...h,children:p.jsx(kw,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":Gw(r.open),...t,ref:lr(n,i.onTriggerChange),onClick:y=>{var w;(w=t.onClick)==null||w.call(t,y),!(t.disabled||y.defaultPrevented)&&(y.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Ve(t.onPointerMove,al(y=>{c.onItemEnter(y),!y.defaultPrevented&&!t.disabled&&!r.open&&!u.current&&(c.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{r.onOpenChange(!0),v()},100))})),onPointerLeave:Ve(t.onPointerLeave,al(y=>{var N,E;v();const w=(N=r.content)==null?void 0:N.getBoundingClientRect();if(w){const S=(E=r.content)==null?void 0:E.dataset.side,C=S==="right",A=C?-5:5,O=w[C?"left":"right"],R=w[C?"right":"left"];c.onPointerGraceIntentChange({area:[{x:y.clientX+A,y:y.clientY},{x:O,y:w.top},{x:R,y:w.top},{x:R,y:w.bottom},{x:O,y:w.bottom}],side:S}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.onPointerGraceIntentChange(null),300)}else{if(c.onTriggerLeave(y),y.defaultPrevented)return;c.onPointerGraceIntentChange(null)}})),onKeyDown:Ve(t.onKeyDown,y=>{var N;const w=c.searchRef.current!=="";t.disabled||w&&y.key===" "||GM[s.dir].includes(y.key)&&(r.onOpenChange(!0),(N=r.content)==null||N.focus(),y.preventDefault())})})})});qw.displayName=Gi;var Fw="MenuSubContent",$w=b.forwardRef((t,n)=>{const r=Rw(na,t.__scopeMenu),{forceMount:s=r.forceMount,...i}=t,c=Ns(na,t.__scopeMenu),u=gl(na,t.__scopeMenu),f=Iw(Fw,t.__scopeMenu),g=b.useRef(null),h=Zt(n,g);return p.jsx(nl.Provider,{scope:t.__scopeMenu,children:p.jsx(Ma,{present:s||c.open,children:p.jsx(nl.Slot,{scope:t.__scopeMenu,children:p.jsx(Xh,{id:f.contentId,"aria-labelledby":f.triggerId,...i,ref:h,align:"start",side:u.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:v=>{var y;u.isUsingKeyboardRef.current&&((y=g.current)==null||y.focus()),v.preventDefault()},onCloseAutoFocus:v=>v.preventDefault(),onFocusOutside:Ve(t.onFocusOutside,v=>{v.target!==f.trigger&&c.onOpenChange(!1)}),onEscapeKeyDown:Ve(t.onEscapeKeyDown,v=>{u.onClose(),v.preventDefault()}),onKeyDown:Ve(t.onKeyDown,v=>{var N;const y=v.currentTarget.contains(v.target),w=YM[u.dir].includes(v.key);y&&w&&(c.onOpenChange(!1),(N=f.trigger)==null||N.focus(),v.preventDefault())})})})})})});$w.displayName=Fw;function Gw(t){return t?"open":"closed"}function lu(t){return t==="indeterminate"}function Wh(t){return lu(t)?"indeterminate":t?"checked":"unchecked"}function mD(t){const n=document.activeElement;for(const r of t)if(r===n||(r.focus(),document.activeElement!==n))return}function hD(t,n){return t.map((r,s)=>t[(n+s)%t.length])}function pD(t,n,r){const i=n.length>1&&Array.from(n).every(h=>h===n[0])?n[0]:n,c=r?t.indexOf(r):-1;let u=hD(t,Math.max(c,0));i.length===1&&(u=u.filter(h=>h!==r));const g=u.find(h=>h.toLowerCase().startsWith(i.toLowerCase()));return g!==r?g:void 0}function gD(t,n){const{x:r,y:s}=t;let i=!1;for(let c=0,u=n.length-1;c<n.length;u=c++){const f=n[c],g=n[u],h=f.x,v=f.y,y=g.x,w=g.y;v>s!=w>s&&r<(y-h)*(s-v)/(w-v)+h&&(i=!i)}return i}function yD(t,n){if(!n)return!1;const r={x:t.clientX,y:t.clientY};return gD(r,n)}function al(t){return n=>n.pointerType==="mouse"?t(n):void 0}var vD=Aw,bD=Gh,xD=Tw,wD=jw,SD=Kh,ED=Ow,_D=Fu,CD=Mw,ND=zw,AD=Uw,RD=Pw,TD=Hw,jD=Vw,OD=qw,kD=$w;function MD(t){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}const DD=ae.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),$u=()=>{const t=ae.useContext(DD);if(!t)throw new Error("useDrawerContext must be used within a Drawer.Root");return t};MD(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(+[data-state=closed]+){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function zD(t,n){typeof t=="function"?t(n):t!=null&&(t.current=n)}function LD(...t){return n=>t.forEach(r=>zD(r,n))}function Yw(...t){return b.useCallback(LD(...t),t)}const E0=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function jm(t,n){if(!t)return()=>{};const r=t.style.cssText;return Object.assign(t.style,n),()=>{t.style.cssText=r}}function UD(...t){return(...n)=>{for(const r of t)typeof r=="function"&&r(...n)}}const Om={DURATION:.5,EASE:[.32,.72,0,1]},BD=8,PD=26,HD=()=>()=>{};function VD(){const{direction:t,isOpen:n,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:i}=$u(),c=ae.useRef(null),u=b.useMemo(()=>document.body.style.backgroundColor,[]);function f(){return(window.innerWidth-PD)/window.innerWidth}ae.useEffect(()=>{if(n&&r){c.current&&clearTimeout(c.current);const g=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!g)return;UD(s&&!i?jm(document.body,{background:"black"}):HD,jm(g,{transformOrigin:E0(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Om.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Om.EASE.join(",")})`}));const h=jm(g,{borderRadius:`${BD}px`,overflow:"hidden",...E0(t)?{transform:`scale(${f()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${f()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{h(),c.current=window.setTimeout(()=>{u?document.body.style.background=u:document.body.style.removeProperty("background")},Om.DURATION*1e3)}}},[n,r,u])}const ID=ae.forwardRef(function({...t},n){const{overlayRef:r,snapPoints:s,onRelease:i,shouldFade:c,isOpen:u,modal:f,shouldAnimate:g}=$u(),h=Yw(n,r),v=s&&s.length>0;if(!f)return null;const y=ae.useCallback(w=>i(w),[i]);return ae.createElement(F1,{onMouseUp:y,ref:h,"data-vaul-overlay":"","data-vaul-snap-points":u&&v?"true":"false","data-vaul-snap-points-overlay":u&&c?"true":"false","data-vaul-animate":g!=null&&g.current?"true":"false",...t})});ID.displayName="Drawer.Overlay";const qD=ae.forwardRef(function({onPointerDownOutside:t,style:n,onOpenAutoFocus:r,...s},i){const{drawerRef:c,onPress:u,onRelease:f,onDrag:g,keyboardIsOpen:h,snapPointsOffset:v,activeSnapPointIndex:y,modal:w,isOpen:N,direction:E,snapPoints:S,container:C,handleOnly:A,shouldAnimate:O,autoFocus:R}=$u(),[L,I]=ae.useState(!1),ee=Yw(i,c),U=ae.useRef(null),Q=ae.useRef(null),le=ae.useRef(!1),ue=S&&S.length>0;VD();const me=(X,he,be=0)=>{if(le.current)return!0;const j=Math.abs(X.y),Z=Math.abs(X.x),P=Z>j,se=["bottom","right"].includes(he)?1:-1;if(he==="left"||he==="right"){if(!(X.x*se<0)&&Z>=0&&Z<=be)return P}else if(!(X.y*se<0)&&j>=0&&j<=be)return!P;return le.current=!0,!0};ae.useEffect(()=>{ue&&window.requestAnimationFrame(()=>{I(!0)})},[]);function re(X){U.current=null,le.current=!1,f(X)}return ae.createElement($1,{"data-vaul-drawer-direction":E,"data-vaul-drawer":"","data-vaul-delayed-snap-points":L?"true":"false","data-vaul-snap-points":N&&ue?"true":"false","data-vaul-custom-container":C?"true":"false","data-vaul-animate":O!=null&&O.current?"true":"false",...s,ref:ee,style:v&&v.length>0?{"--snap-point-height":`${v[y??0]}px`,...n}:n,onPointerDown:X=>{A||(s.onPointerDown==null||s.onPointerDown.call(s,X),U.current={x:X.pageX,y:X.pageY},u(X))},onOpenAutoFocus:X=>{r==null||r(X),R||X.preventDefault()},onPointerDownOutside:X=>{if(t==null||t(X),!w||X.defaultPrevented){X.preventDefault();return}h.current&&(h.current=!1)},onFocusOutside:X=>{if(!w){X.preventDefault();return}},onPointerMove:X=>{if(Q.current=X,A||(s.onPointerMove==null||s.onPointerMove.call(s,X),!U.current))return;const he=X.pageY-U.current.y,be=X.pageX-U.current.x,j=X.pointerType==="touch"?10:2;me({x:be,y:he},E,j)?g(X):(Math.abs(be)>j||Math.abs(he)>j)&&(U.current=null)},onPointerUp:X=>{s.onPointerUp==null||s.onPointerUp.call(s,X),U.current=null,le.current=!1,f(X)},onPointerOut:X=>{s.onPointerOut==null||s.onPointerOut.call(s,X),re(Q.current)},onContextMenu:X=>{s.onContextMenu==null||s.onContextMenu.call(s,X),Q.current&&re(Q.current)}})});qD.displayName="Drawer.Content";const FD=250,$D=120,GD=ae.forwardRef(function({preventCycle:t=!1,children:n,...r},s){const{closeDrawer:i,isDragging:c,snapPoints:u,activeSnapPoint:f,setActiveSnapPoint:g,dismissible:h,handleOnly:v,isOpen:y,onPress:w,onDrag:N}=$u(),E=ae.useRef(null),S=ae.useRef(!1);function C(){if(S.current){R();return}window.setTimeout(()=>{A()},$D)}function A(){if(c||t||S.current){R();return}if(R(),!u||u.length===0){h||i();return}if(f===u[u.length-1]&&h){i();return}const I=u.findIndex(U=>U===f);if(I===-1)return;const ee=u[I+1];g(ee)}function O(){E.current=window.setTimeout(()=>{S.current=!0},FD)}function R(){E.current&&window.clearTimeout(E.current),S.current=!1}return ae.createElement("div",{onClick:C,onPointerCancel:R,onPointerDown:L=>{v&&w(L),O()},onPointerMove:L=>{v&&N(L)},ref:s,"data-vaul-drawer-visible":y?"true":"false","data-vaul-handle":"","aria-hidden":"true",...r},ae.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},n))});GD.displayName="Drawer.Handle";var Gu="DropdownMenu",[YD]=_s(Gu,[Cw]),pn=Cw(),[ZD,Zw]=YD(Gu),Xw=t=>{const{__scopeDropdownMenu:n,children:r,dir:s,open:i,defaultOpen:c,onOpenChange:u,modal:f=!0}=t,g=pn(n),h=b.useRef(null),[v,y]=jh({prop:i,defaultProp:c??!1,onChange:u,caller:Gu});return p.jsx(ZD,{scope:n,triggerId:Co(),triggerRef:h,contentId:Co(),open:v,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(w=>!w),[y]),modal:f,children:p.jsx(vD,{...g,open:v,onOpenChange:y,dir:s,modal:f,children:r})})};Xw.displayName=Gu;var Kw="DropdownMenuTrigger",Qw=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,disabled:s=!1,...i}=t,c=Zw(Kw,r),u=pn(r);return p.jsx(bD,{asChild:!0,...u,children:p.jsx(jt.button,{type:"button",id:c.triggerId,"aria-haspopup":"menu","aria-expanded":c.open,"aria-controls":c.open?c.contentId:void 0,"data-state":c.open?"open":"closed","data-disabled":s?"":void 0,disabled:s,...i,ref:lr(n,c.triggerRef),onPointerDown:Ve(t.onPointerDown,f=>{!s&&f.button===0&&f.ctrlKey===!1&&(c.onOpenToggle(),c.open||f.preventDefault())}),onKeyDown:Ve(t.onKeyDown,f=>{s||(["Enter"," "].includes(f.key)&&c.onOpenToggle(),f.key==="ArrowDown"&&c.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(f.key)&&f.preventDefault())})})})});Qw.displayName=Kw;var XD="DropdownMenuPortal",Ww=t=>{const{__scopeDropdownMenu:n,...r}=t,s=pn(n);return p.jsx(xD,{...s,...r})};Ww.displayName=XD;var Jw="DropdownMenuContent",eS=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=Zw(Jw,r),c=pn(r),u=b.useRef(!1);return p.jsx(wD,{id:i.contentId,"aria-labelledby":i.triggerId,...c,...s,ref:n,onCloseAutoFocus:Ve(t.onCloseAutoFocus,f=>{var g;u.current||(g=i.triggerRef.current)==null||g.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:Ve(t.onInteractOutside,f=>{const g=f.detail.originalEvent,h=g.button===0&&g.ctrlKey===!0,v=g.button===2||h;(!i.modal||v)&&(u.current=!0)}),style:{...t.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)"}})});eS.displayName=Jw;var KD="DropdownMenuGroup",QD=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(SD,{...i,...s,ref:n})});QD.displayName=KD;var WD="DropdownMenuLabel",JD=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(ED,{...i,...s,ref:n})});JD.displayName=WD;var e4="DropdownMenuItem",tS=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(_D,{...i,...s,ref:n})});tS.displayName=e4;var t4="DropdownMenuCheckboxItem",n4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(CD,{...i,...s,ref:n})});n4.displayName=t4;var a4="DropdownMenuRadioGroup",r4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(ND,{...i,...s,ref:n})});r4.displayName=a4;var s4="DropdownMenuRadioItem",o4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(AD,{...i,...s,ref:n})});o4.displayName=s4;var i4="DropdownMenuItemIndicator",l4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(RD,{...i,...s,ref:n})});l4.displayName=i4;var c4="DropdownMenuSeparator",u4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(TD,{...i,...s,ref:n})});u4.displayName=c4;var d4="DropdownMenuArrow",f4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(jD,{...i,...s,ref:n})});f4.displayName=d4;var m4="DropdownMenuSubTrigger",h4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(OD,{...i,...s,ref:n})});h4.displayName=m4;var p4="DropdownMenuSubContent",g4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=pn(r);return p.jsx(kD,{...i,...s,ref:n,style:{...t.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)"}})});g4.displayName=p4;var y4=Xw,v4=Qw,b4=Ww,x4=eS,w4=tS,yl=t=>t.type==="checkbox",ys=t=>t instanceof Date,An=t=>t==null;const nS=t=>typeof t=="object";var qt=t=>!An(t)&&!Array.isArray(t)&&nS(t)&&!ys(t),S4=t=>qt(t)&&t.target?yl(t.target)?t.target.checked:t.target.value:t,E4=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,_4=(t,n)=>t.has(E4(n)),C4=t=>{const n=t.constructor&&t.constructor.prototype;return qt(n)&&n.hasOwnProperty("isPrototypeOf")},Jh=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Jt(t){let n;const r=Array.isArray(t),s=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)n=new Date(t);else if(!(Jh&&(t instanceof Blob||s))&&(r||qt(t)))if(n=r?[]:Object.create(Object.getPrototypeOf(t)),!r&&!C4(t))n=t;else for(const i in t)t.hasOwnProperty(i)&&(n[i]=Jt(t[i]));else return t;return n}var Yu=t=>/^\w*$/.test(t),Dt=t=>t===void 0,ep=t=>Array.isArray(t)?t.filter(Boolean):[],tp=t=>ep(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Re=(t,n,r)=>{if(!n||!qt(t))return r;const s=(Yu(n)?[n]:tp(n)).reduce((i,c)=>An(i)?i:i[c],t);return Dt(s)||s===t?Dt(t[n])?r:t[n]:s},Ca=t=>typeof t=="boolean",xt=(t,n,r)=>{let s=-1;const i=Yu(n)?[n]:tp(n),c=i.length,u=c-1;for(;++s<c;){const f=i[s];let g=r;if(s!==u){const h=t[f];g=qt(h)||Array.isArray(h)?h:isNaN(+i[s+1])?{}:[]}if(f==="__proto__"||f==="constructor"||f==="prototype")return;t[f]=g,t=t[f]}};const _0={BLUR:"blur",FOCUS_OUT:"focusout"},ca={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},er={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},N4=ae.createContext(null);N4.displayName="HookFormContext";var A4=(t,n,r,s=!0)=>{const i={defaultValues:n._defaultValues};for(const c in t)Object.defineProperty(i,c,{get:()=>{const u=c;return n._proxyFormState[u]!==ca.all&&(n._proxyFormState[u]=!s||ca.all),t[u]}});return i};const R4=typeof window<"u"?ae.useLayoutEffect:ae.useEffect;var Pn=t=>typeof t=="string",T4=(t,n,r,s,i)=>Pn(t)?(s&&n.watch.add(t),Re(r,t,i)):Array.isArray(t)?t.map(c=>(s&&n.watch.add(c),Re(r,c))):(s&&(n.watchAll=!0),r),nh=t=>An(t)||!nS(t);function Pr(t,n,r=new WeakSet){if(nh(t)||nh(n))return t===n;if(ys(t)&&ys(n))return t.getTime()===n.getTime();const s=Object.keys(t),i=Object.keys(n);if(s.length!==i.length)return!1;if(r.has(t)||r.has(n))return!0;r.add(t),r.add(n);for(const c of s){const u=t[c];if(!i.includes(c))return!1;if(c!=="ref"){const f=n[c];if(ys(u)&&ys(f)||qt(u)&&qt(f)||Array.isArray(u)&&Array.isArray(f)?!Pr(u,f,r):u!==f)return!1}}return!0}var np=(t,n,r,s,i)=>n?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[s]:i||!0}}:{},Ki=t=>Array.isArray(t)?t:[t],C0=()=>{let t=[];return{get observers(){return t},next:i=>{for(const c of t)c.next&&c.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(c=>c!==i)}}),unsubscribe:()=>{t=[]}}};function aS(t,n){const r={};for(const s in t)if(t.hasOwnProperty(s)){const i=t[s],c=n[s];if(i&&qt(i)&&c){const u=aS(i,c);qt(u)&&(r[s]=u)}else t[s]&&(r[s]=c)}return r}var hn=t=>qt(t)&&!Object.keys(t).length,ap=t=>t.type==="file",ua=t=>typeof t=="function",cu=t=>{if(!Jh)return!1;const n=t?t.ownerDocument:0;return t instanceof(n&&n.defaultView?n.defaultView.HTMLElement:HTMLElement)},rS=t=>t.type==="select-multiple",rp=t=>t.type==="radio",j4=t=>rp(t)||yl(t),km=t=>cu(t)&&t.isConnected;function O4(t,n){const r=n.slice(0,-1).length;let s=0;for(;s<r;)t=Dt(t)?s++:t[n[s++]];return t}function k4(t){for(const n in t)if(t.hasOwnProperty(n)&&!Dt(t[n]))return!1;return!0}function Ht(t,n){const r=Array.isArray(n)?n:Yu(n)?[n]:tp(n),s=r.length===1?t:O4(t,r),i=r.length-1,c=r[i];return s&&delete s[c],i!==0&&(qt(s)&&hn(s)||Array.isArray(s)&&k4(s))&&Ht(t,r.slice(0,-1)),t}var M4=t=>{for(const n in t)if(ua(t[n]))return!0;return!1};function sS(t){return Array.isArray(t)||qt(t)&&!M4(t)}function ah(t,n={}){for(const r in t)sS(t[r])?(n[r]=Array.isArray(t[r])?[]:{},ah(t[r],n[r])):Dt(t[r])||(n[r]=!0);return n}function wo(t,n,r){r||(r=ah(n));for(const s in t)sS(t[s])?Dt(n)||nh(r[s])?r[s]=ah(t[s],Array.isArray(t[s])?[]:{}):wo(t[s],An(n)?{}:n[s],r[s]):r[s]=!Pr(t[s],n[s]);return r}const N0={value:!1,isValid:!1},A0={value:!0,isValid:!0};var oS=t=>{if(Array.isArray(t)){if(t.length>1){const n=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:n,isValid:!!n.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!Dt(t[0].attributes.value)?Dt(t[0].value)||t[0].value===""?A0:{value:t[0].value,isValid:!0}:A0:N0}return N0},iS=(t,{valueAsNumber:n,valueAsDate:r,setValueAs:s})=>Dt(t)?t:n?t===""?NaN:t&&+t:r&&Pn(t)?new Date(t):s?s(t):t;const R0={isValid:!1,value:null};var lS=t=>Array.isArray(t)?t.reduce((n,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:n,R0):R0;function T0(t){const n=t.ref;return ap(n)?n.files:rp(n)?lS(t.refs).value:rS(n)?[...n.selectedOptions].map(({value:r})=>r):yl(n)?oS(t.refs).value:iS(Dt(n.value)?t.ref.value:n.value,t)}var D4=(t,n,r,s)=>{const i={};for(const c of t){const u=Re(n,c);u&&xt(i,c,u._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:s}},uu=t=>t instanceof RegExp,Fi=t=>Dt(t)?t:uu(t)?t.source:qt(t)?uu(t.value)?t.value.source:t.value:t,j0=t=>({isOnSubmit:!t||t===ca.onSubmit,isOnBlur:t===ca.onBlur,isOnChange:t===ca.onChange,isOnAll:t===ca.all,isOnTouch:t===ca.onTouched});const O0="AsyncFunction";var z4=t=>!!t&&!!t.validate&&!!(ua(t.validate)&&t.validate.constructor.name===O0||qt(t.validate)&&Object.values(t.validate).find(n=>n.constructor.name===O0)),L4=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),k0=(t,n,r)=>!r&&(n.watchAll||n.watch.has(t)||[...n.watch].some(s=>t.startsWith(s)&&/^\.\w+/.test(t.slice(s.length))));const Qi=(t,n,r,s)=>{for(const i of r||Object.keys(t)){const c=Re(t,i);if(c){const{_f:u,...f}=c;if(u){if(u.refs&&u.refs[0]&&n(u.refs[0],i)&&!s)return!0;if(u.ref&&n(u.ref,u.name)&&!s)return!0;if(Qi(f,n))break}else if(qt(f)&&Qi(f,n))break}}};function M0(t,n,r){const s=Re(t,r);if(s||Yu(r))return{error:s,name:r};const i=r.split(".");for(;i.length;){const c=i.join("."),u=Re(n,c),f=Re(t,c);if(u&&!Array.isArray(u)&&r!==c)return{name:r};if(f&&f.type)return{name:c,error:f};if(f&&f.root&&f.root.type)return{name:`${c}.root`,error:f.root};i.pop()}return{name:r}}var U4=(t,n,r,s)=>{r(t);const{name:i,...c}=t;return hn(c)||Object.keys(c).length>=Object.keys(n).length||Object.keys(c).find(u=>n[u]===(!s||ca.all))},B4=(t,n,r)=>!t||!n||t===n||Ki(t).some(s=>s&&(r?s===n:s.startsWith(n)||n.startsWith(s))),P4=(t,n,r,s,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(n||t):(r?s.isOnBlur:i.isOnBlur)?!t:(r?s.isOnChange:i.isOnChange)?t:!0,H4=(t,n)=>!ep(Re(t,n)).length&&Ht(t,n),V4=(t,n,r)=>{const s=Ki(Re(t,r));return xt(s,"root",n[r]),xt(t,r,s),t};function D0(t,n,r="validate"){if(Pn(t)||Array.isArray(t)&&t.every(Pn)||Ca(t)&&!t)return{type:r,message:Pn(t)?t:"",ref:n}}var bo=t=>qt(t)&&!uu(t)?t:{value:t,message:""},z0=async(t,n,r,s,i,c)=>{const{ref:u,refs:f,required:g,maxLength:h,minLength:v,min:y,max:w,pattern:N,validate:E,name:S,valueAsNumber:C,mount:A}=t._f,O=Re(r,S);if(!A||n.has(S))return{};const R=f?f[0]:u,L=re=>{i&&R.reportValidity&&(R.setCustomValidity(Ca(re)?"":re||""),R.reportValidity())},I={},ee=rp(u),U=yl(u),Q=ee||U,le=(C||ap(u))&&Dt(u.value)&&Dt(O)||cu(u)&&u.value===""||O===""||Array.isArray(O)&&!O.length,ue=np.bind(null,S,s,I),me=(re,X,he,be=er.maxLength,j=er.minLength)=>{const Z=re?X:he;I[S]={type:re?be:j,message:Z,ref:u,...ue(re?be:j,Z)}};if(c?!Array.isArray(O)||!O.length:g&&(!Q&&(le||An(O))||Ca(O)&&!O||U&&!oS(f).isValid||ee&&!lS(f).isValid)){const{value:re,message:X}=Pn(g)?{value:!!g,message:g}:bo(g);if(re&&(I[S]={type:er.required,message:X,ref:R,...ue(er.required,X)},!s))return L(X),I}if(!le&&(!An(y)||!An(w))){let re,X;const he=bo(w),be=bo(y);if(!An(O)&&!isNaN(O)){const j=u.valueAsNumber||O&&+O;An(he.value)||(re=j>he.value),An(be.value)||(X=j<be.value)}else{const j=u.valueAsDate||new Date(O),Z=we=>new Date(new Date().toDateString()+" "+we),P=u.type=="time",se=u.type=="week";Pn(he.value)&&O&&(re=P?Z(O)>Z(he.value):se?O>he.value:j>new Date(he.value)),Pn(be.value)&&O&&(X=P?Z(O)<Z(be.value):se?O<be.value:j<new Date(be.value))}if((re||X)&&(me(!!re,he.message,be.message,er.max,er.min),!s))return L(I[S].message),I}if((h||v)&&!le&&(Pn(O)||c&&Array.isArray(O))){const re=bo(h),X=bo(v),he=!An(re.value)&&O.length>+re.value,be=!An(X.value)&&O.length<+X.value;if((he||be)&&(me(he,re.message,X.message),!s))return L(I[S].message),I}if(N&&!le&&Pn(O)){const{value:re,message:X}=bo(N);if(uu(re)&&!O.match(re)&&(I[S]={type:er.pattern,message:X,ref:u,...ue(er.pattern,X)},!s))return L(X),I}if(E){if(ua(E)){const re=await E(O,r),X=D0(re,R);if(X&&(I[S]={...X,...ue(er.validate,X.message)},!s))return L(X.message),I}else if(qt(E)){let re={};for(const X in E){if(!hn(re)&&!s)break;const he=D0(await E[X](O,r),R,X);he&&(re={...he,...ue(X,he.message)},L(he.message),s&&(I[S]=re))}if(!hn(re)&&(I[S]={ref:R,...re},!s))return I}}return L(!0),I};const I4={mode:ca.onSubmit,reValidateMode:ca.onChange,shouldFocusError:!0};function q4(t={}){let n={...I4,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:ua(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:n.errors||{},disabled:n.disabled||!1},s={},i=qt(n.defaultValues)||qt(n.values)?Jt(n.defaultValues||n.values)||{}:{},c=n.shouldUnregister?{}:Jt(i),u={action:!1,mount:!1,watch:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},g,h=0;const v={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let y={...v};const w={array:C0(),state:C0()},N=n.criteriaMode===ca.all,E=k=>H=>{clearTimeout(h),h=setTimeout(k,H)},S=async k=>{if(!n.disabled&&(v.isValid||y.isValid||k)){const H=n.resolver?hn((await U()).errors):await le(s,!0);H!==r.isValid&&w.state.next({isValid:H})}},C=(k,H)=>{!n.disabled&&(v.isValidating||v.validatingFields||y.isValidating||y.validatingFields)&&((k||Array.from(f.mount)).forEach($=>{$&&(H?xt(r.validatingFields,$,H):Ht(r.validatingFields,$))}),w.state.next({validatingFields:r.validatingFields,isValidating:!hn(r.validatingFields)}))},A=(k,H=[],$,ye,pe=!0,ge=!0)=>{if(ye&&$&&!n.disabled){if(u.action=!0,ge&&Array.isArray(Re(s,k))){const Se=$(Re(s,k),ye.argA,ye.argB);pe&&xt(s,k,Se)}if(ge&&Array.isArray(Re(r.errors,k))){const Se=$(Re(r.errors,k),ye.argA,ye.argB);pe&&xt(r.errors,k,Se),H4(r.errors,k)}if((v.touchedFields||y.touchedFields)&&ge&&Array.isArray(Re(r.touchedFields,k))){const Se=$(Re(r.touchedFields,k),ye.argA,ye.argB);pe&&xt(r.touchedFields,k,Se)}(v.dirtyFields||y.dirtyFields)&&(r.dirtyFields=wo(i,c)),w.state.next({name:k,isDirty:me(k,H),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else xt(c,k,H)},O=(k,H)=>{xt(r.errors,k,H),w.state.next({errors:r.errors})},R=k=>{r.errors=k,w.state.next({errors:r.errors,isValid:!1})},L=(k,H,$,ye)=>{const pe=Re(s,k);if(pe){const ge=Re(c,k,Dt($)?Re(i,k):$);Dt(ge)||ye&&ye.defaultChecked||H?xt(c,k,H?ge:T0(pe._f)):he(k,ge),u.mount&&S()}},I=(k,H,$,ye,pe)=>{let ge=!1,Se=!1;const qe={name:k};if(!n.disabled){if(!$||ye){(v.isDirty||y.isDirty)&&(Se=r.isDirty,r.isDirty=qe.isDirty=me(),ge=Se!==qe.isDirty);const Xe=Pr(Re(i,k),H);Se=!!Re(r.dirtyFields,k),Xe?Ht(r.dirtyFields,k):xt(r.dirtyFields,k,!0),qe.dirtyFields=r.dirtyFields,ge=ge||(v.dirtyFields||y.dirtyFields)&&Se!==!Xe}if($){const Xe=Re(r.touchedFields,k);Xe||(xt(r.touchedFields,k,$),qe.touchedFields=r.touchedFields,ge=ge||(v.touchedFields||y.touchedFields)&&Xe!==$)}ge&&pe&&w.state.next(qe)}return ge?qe:{}},ee=(k,H,$,ye)=>{const pe=Re(r.errors,k),ge=(v.isValid||y.isValid)&&Ca(H)&&r.isValid!==H;if(n.delayError&&$?(g=E(()=>O(k,$)),g(n.delayError)):(clearTimeout(h),g=null,$?xt(r.errors,k,$):Ht(r.errors,k)),($?!Pr(pe,$):pe)||!hn(ye)||ge){const Se={...ye,...ge&&Ca(H)?{isValid:H}:{},errors:r.errors,name:k};r={...r,...Se},w.state.next(Se)}},U=async k=>{C(k,!0);const H=await n.resolver(c,n.context,D4(k||f.mount,s,n.criteriaMode,n.shouldUseNativeValidation));return C(k),H},Q=async k=>{const{errors:H}=await U(k);if(k)for(const $ of k){const ye=Re(H,$);ye?xt(r.errors,$,ye):Ht(r.errors,$)}else r.errors=H;return H},le=async(k,H,$={valid:!0})=>{for(const ye in k){const pe=k[ye];if(pe){const{_f:ge,...Se}=pe;if(ge){const qe=f.array.has(ge.name),Xe=pe._f&&z4(pe._f);Xe&&v.validatingFields&&C([ge.name],!0);const Ot=await z0(pe,f.disabled,c,N,n.shouldUseNativeValidation&&!H,qe);if(Xe&&v.validatingFields&&C([ge.name]),Ot[ge.name]&&($.valid=!1,H))break;!H&&(Re(Ot,ge.name)?qe?V4(r.errors,Ot,ge.name):xt(r.errors,ge.name,Ot[ge.name]):Ht(r.errors,ge.name))}!hn(Se)&&await le(Se,H,$)}}return $.valid},ue=()=>{for(const k of f.unMount){const H=Re(s,k);H&&(H._f.refs?H._f.refs.every($=>!km($)):!km(H._f.ref))&&oe(k)}f.unMount=new Set},me=(k,H)=>!n.disabled&&(k&&H&&xt(c,k,H),!Pr(we(),i)),re=(k,H,$)=>T4(k,f,{...u.mount?c:Dt(H)?i:Pn(k)?{[k]:H}:H},$,H),X=k=>ep(Re(u.mount?c:i,k,n.shouldUnregister?Re(i,k,[]):[])),he=(k,H,$={})=>{const ye=Re(s,k);let pe=H;if(ye){const ge=ye._f;ge&&(!ge.disabled&&xt(c,k,iS(H,ge)),pe=cu(ge.ref)&&An(H)?"":H,rS(ge.ref)?[...ge.ref.options].forEach(Se=>Se.selected=pe.includes(Se.value)):ge.refs?yl(ge.ref)?ge.refs.forEach(Se=>{(!Se.defaultChecked||!Se.disabled)&&(Array.isArray(pe)?Se.checked=!!pe.find(qe=>qe===Se.value):Se.checked=pe===Se.value||!!pe)}):ge.refs.forEach(Se=>Se.checked=Se.value===pe):ap(ge.ref)?ge.ref.value="":(ge.ref.value=pe,ge.ref.type||w.state.next({name:k,values:Jt(c)})))}($.shouldDirty||$.shouldTouch)&&I(k,pe,$.shouldTouch,$.shouldDirty,!0),$.shouldValidate&&se(k)},be=(k,H,$)=>{for(const ye in H){if(!H.hasOwnProperty(ye))return;const pe=H[ye],ge=k+"."+ye,Se=Re(s,ge);(f.array.has(k)||qt(pe)||Se&&!Se._f)&&!ys(pe)?be(ge,pe,$):he(ge,pe,$)}},j=(k,H,$={})=>{const ye=Re(s,k),pe=f.array.has(k),ge=Jt(H);xt(c,k,ge),pe?(w.array.next({name:k,values:Jt(c)}),(v.isDirty||v.dirtyFields||y.isDirty||y.dirtyFields)&&$.shouldDirty&&w.state.next({name:k,dirtyFields:wo(i,c),isDirty:me(k,ge)})):ye&&!ye._f&&!An(ge)?be(k,ge,$):he(k,ge,$),k0(k,f)&&w.state.next({...r,name:k}),w.state.next({name:u.mount?k:void 0,values:Jt(c)})},Z=async k=>{u.mount=!0;const H=k.target;let $=H.name,ye=!0;const pe=Re(s,$),ge=Xe=>{ye=Number.isNaN(Xe)||ys(Xe)&&isNaN(Xe.getTime())||Pr(Xe,Re(c,$,Xe))},Se=j0(n.mode),qe=j0(n.reValidateMode);if(pe){let Xe,Ot;const on=H.type?T0(pe._f):S4(k),dn=k.type===_0.BLUR||k.type===_0.FOCUS_OUT,Fn=!L4(pe._f)&&!n.resolver&&!Re(r.errors,$)&&!pe._f.deps||P4(dn,Re(r.touchedFields,$),r.isSubmitted,qe,Se),Ft=k0($,f,dn);xt(c,$,on),dn?(!H||!H.readOnly)&&(pe._f.onBlur&&pe._f.onBlur(k),g&&g(0)):pe._f.onChange&&pe._f.onChange(k);const Nt=I($,on,dn),fn=!hn(Nt)||Ft;if(!dn&&w.state.next({name:$,type:k.type,values:Jt(c)}),Fn)return(v.isValid||y.isValid)&&(n.mode==="onBlur"?dn&&S():dn||S()),fn&&w.state.next({name:$,...Ft?{}:Nt});if(!dn&&Ft&&w.state.next({...r}),n.resolver){const{errors:$t}=await U([$]);if(ge(on),ye){const Xo=M0(r.errors,s,$),cr=M0($t,s,Xo.name||$);Xe=cr.error,$=cr.name,Ot=hn($t)}}else C([$],!0),Xe=(await z0(pe,f.disabled,c,N,n.shouldUseNativeValidation))[$],C([$]),ge(on),ye&&(Xe?Ot=!1:(v.isValid||y.isValid)&&(Ot=await le(s,!0)));ye&&(pe._f.deps&&(!Array.isArray(pe._f.deps)||pe._f.deps.length>0)&&se(pe._f.deps),ee($,Ot,Xe,Nt))}},P=(k,H)=>{if(Re(r.errors,H)&&k.focus)return k.focus(),1},se=async(k,H={})=>{let $,ye;const pe=Ki(k);if(n.resolver){const ge=await Q(Dt(k)?k:pe);$=hn(ge),ye=k?!pe.some(Se=>Re(ge,Se)):$}else k?(ye=(await Promise.all(pe.map(async ge=>{const Se=Re(s,ge);return await le(Se&&Se._f?{[ge]:Se}:Se)}))).every(Boolean),!(!ye&&!r.isValid)&&S()):ye=$=await le(s);return w.state.next({...!Pn(k)||(v.isValid||y.isValid)&&$!==r.isValid?{}:{name:k},...n.resolver||!k?{isValid:$}:{},errors:r.errors}),H.shouldFocus&&!ye&&Qi(s,P,k?pe:f.mount),ye},we=(k,H)=>{let $={...u.mount?c:i};return H&&($=aS(H.dirtyFields?r.dirtyFields:r.touchedFields,$)),Dt(k)?$:Pn(k)?Re($,k):k.map(ye=>Re($,ye))},T=(k,H)=>({invalid:!!Re((H||r).errors,k),isDirty:!!Re((H||r).dirtyFields,k),error:Re((H||r).errors,k),isValidating:!!Re(r.validatingFields,k),isTouched:!!Re((H||r).touchedFields,k)}),Y=k=>{k&&Ki(k).forEach(H=>Ht(r.errors,H)),w.state.next({errors:k?r.errors:{}})},D=(k,H,$)=>{const ye=(Re(s,k,{_f:{}})._f||{}).ref,pe=Re(r.errors,k)||{},{ref:ge,message:Se,type:qe,...Xe}=pe;xt(r.errors,k,{...Xe,...H,ref:ye}),w.state.next({name:k,errors:r.errors,isValid:!1}),$&&$.shouldFocus&&ye&&ye.focus&&ye.focus()},V=(k,H)=>ua(k)?w.state.subscribe({next:$=>"values"in $&&k(re(void 0,H),$)}):re(k,H,!0),te=k=>w.state.subscribe({next:H=>{B4(k.name,H.name,k.exact)&&U4(H,k.formState||v,pt,k.reRenderRoot)&&k.callback({values:{...c},...r,...H,defaultValues:i})}}).unsubscribe,fe=k=>(u.mount=!0,y={...y,...k.formState},te({...k,formState:y})),oe=(k,H={})=>{for(const $ of k?Ki(k):f.mount)f.mount.delete($),f.array.delete($),H.keepValue||(Ht(s,$),Ht(c,$)),!H.keepError&&Ht(r.errors,$),!H.keepDirty&&Ht(r.dirtyFields,$),!H.keepTouched&&Ht(r.touchedFields,$),!H.keepIsValidating&&Ht(r.validatingFields,$),!n.shouldUnregister&&!H.keepDefaultValue&&Ht(i,$);w.state.next({values:Jt(c)}),w.state.next({...r,...H.keepDirty?{isDirty:me()}:{}}),!H.keepIsValid&&S()},K=({disabled:k,name:H})=>{(Ca(k)&&u.mount||k||f.disabled.has(H))&&(k?f.disabled.add(H):f.disabled.delete(H))},de=(k,H={})=>{let $=Re(s,k);const ye=Ca(H.disabled)||Ca(n.disabled);return xt(s,k,{...$||{},_f:{...$&&$._f?$._f:{ref:{name:k}},name:k,mount:!0,...H}}),f.mount.add(k),$?K({disabled:Ca(H.disabled)?H.disabled:n.disabled,name:k}):L(k,!0,H.value),{...ye?{disabled:H.disabled||n.disabled}:{},...n.progressive?{required:!!H.required,min:Fi(H.min),max:Fi(H.max),minLength:Fi(H.minLength),maxLength:Fi(H.maxLength),pattern:Fi(H.pattern)}:{},name:k,onChange:Z,onBlur:Z,ref:pe=>{if(pe){de(k,H),$=Re(s,k);const ge=Dt(pe.value)&&pe.querySelectorAll&&pe.querySelectorAll("input,select,textarea")[0]||pe,Se=j4(ge),qe=$._f.refs||[];if(Se?qe.find(Xe=>Xe===ge):ge===$._f.ref)return;xt(s,k,{_f:{...$._f,...Se?{refs:[...qe.filter(km),ge,...Array.isArray(Re(i,k))?[{}]:[]],ref:{type:ge.type,name:k}}:{ref:ge}}}),L(k,!1,void 0,ge)}else $=Re(s,k,{}),$._f&&($._f.mount=!1),(n.shouldUnregister||H.shouldUnregister)&&!(_4(f.array,k)&&u.action)&&f.unMount.add(k)}}},_e=()=>n.shouldFocusError&&Qi(s,P,f.mount),rt=k=>{Ca(k)&&(w.state.next({disabled:k}),Qi(s,(H,$)=>{const ye=Re(s,$);ye&&(H.disabled=ye._f.disabled||k,Array.isArray(ye._f.refs)&&ye._f.refs.forEach(pe=>{pe.disabled=ye._f.disabled||k}))},0,!1))},De=(k,H)=>async $=>{let ye;$&&($.preventDefault&&$.preventDefault(),$.persist&&$.persist());let pe=Jt(c);if(w.state.next({isSubmitting:!0}),n.resolver){const{errors:ge,values:Se}=await U();r.errors=ge,pe=Jt(Se)}else await le(s);if(f.disabled.size)for(const ge of f.disabled)Ht(pe,ge);if(Ht(r.errors,"root"),hn(r.errors)){w.state.next({errors:{}});try{await k(pe,$)}catch(ge){ye=ge}}else H&&await H({...r.errors},$),_e(),setTimeout(_e);if(w.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:hn(r.errors)&&!ye,submitCount:r.submitCount+1,errors:r.errors}),ye)throw ye},Le=(k,H={})=>{Re(s,k)&&(Dt(H.defaultValue)?j(k,Jt(Re(i,k))):(j(k,H.defaultValue),xt(i,k,Jt(H.defaultValue))),H.keepTouched||Ht(r.touchedFields,k),H.keepDirty||(Ht(r.dirtyFields,k),r.isDirty=H.defaultValue?me(k,Jt(Re(i,k))):me()),H.keepError||(Ht(r.errors,k),v.isValid&&S()),w.state.next({...r}))},xe=(k,H={})=>{const $=k?Jt(k):i,ye=Jt($),pe=hn(k),ge=pe?i:ye;if(H.keepDefaultValues||(i=$),!H.keepValues){if(H.keepDirtyValues){const Se=new Set([...f.mount,...Object.keys(wo(i,c))]);for(const qe of Array.from(Se))Re(r.dirtyFields,qe)?xt(ge,qe,Re(c,qe)):j(qe,Re(ge,qe))}else{if(Jh&&Dt(k))for(const Se of f.mount){const qe=Re(s,Se);if(qe&&qe._f){const Xe=Array.isArray(qe._f.refs)?qe._f.refs[0]:qe._f.ref;if(cu(Xe)){const Ot=Xe.closest("form");if(Ot){Ot.reset();break}}}}if(H.keepFieldsRef)for(const Se of f.mount)j(Se,Re(ge,Se));else s={}}c=n.shouldUnregister?H.keepDefaultValues?Jt(i):{}:Jt(ge),w.array.next({values:{...ge}}),w.state.next({values:{...ge}})}f={mount:H.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!v.isValid||!!H.keepIsValid||!!H.keepDirtyValues||!n.shouldUnregister&&!hn(ge),u.watch=!!n.shouldUnregister,w.state.next({submitCount:H.keepSubmitCount?r.submitCount:0,isDirty:pe?!1:H.keepDirty?r.isDirty:!!(H.keepDefaultValues&&!Pr(k,i)),isSubmitted:H.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:pe?{}:H.keepDirtyValues?H.keepDefaultValues&&c?wo(i,c):r.dirtyFields:H.keepDefaultValues&&k?wo(i,k):H.keepDirty?r.dirtyFields:{},touchedFields:H.keepTouched?r.touchedFields:{},errors:H.keepErrors?r.errors:{},isSubmitSuccessful:H.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},je=(k,H)=>xe(ua(k)?k(c):k,H),at=(k,H={})=>{const $=Re(s,k),ye=$&&$._f;if(ye){const pe=ye.refs?ye.refs[0]:ye.ref;pe.focus&&(pe.focus(),H.shouldSelect&&ua(pe.select)&&pe.select())}},pt=k=>{r={...r,...k}},Ue={control:{register:de,unregister:oe,getFieldState:T,handleSubmit:De,setError:D,_subscribe:te,_runSchema:U,_focusError:_e,_getWatch:re,_getDirty:me,_setValid:S,_setFieldArray:A,_setDisabledField:K,_setErrors:R,_getFieldArray:X,_reset:xe,_resetDefaultValues:()=>ua(n.defaultValues)&&n.defaultValues().then(k=>{je(k,n.resetOptions),w.state.next({isLoading:!1})}),_removeUnmounted:ue,_disableForm:rt,_subjects:w,_proxyFormState:v,get _fields(){return s},get _formValues(){return c},get _state(){return u},set _state(k){u=k},get _defaultValues(){return i},get _names(){return f},set _names(k){f=k},get _formState(){return r},get _options(){return n},set _options(k){n={...n,...k}}},subscribe:fe,trigger:se,register:de,handleSubmit:De,watch:V,setValue:j,getValues:we,reset:je,resetField:Le,clearErrors:Y,unregister:oe,setError:D,setFocus:at,getFieldState:T};return{...Ue,formControl:Ue}}function Oo(t={}){const n=ae.useRef(void 0),r=ae.useRef(void 0),[s,i]=ae.useState({isDirty:!1,isValidating:!1,isLoading:ua(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:ua(t.defaultValues)?void 0:t.defaultValues});if(!n.current)if(t.formControl)n.current={...t.formControl,formState:s},t.defaultValues&&!ua(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:u,...f}=q4(t);n.current={...f,formState:s}}const c=n.current.control;return c._options=t,R4(()=>{const u=c._subscribe({formState:c._proxyFormState,callback:()=>i({...c._formState}),reRenderRoot:!0});return i(f=>({...f,isReady:!0})),c._formState.isReady=!0,u},[c]),ae.useEffect(()=>c._disableForm(t.disabled),[c,t.disabled]),ae.useEffect(()=>{t.mode&&(c._options.mode=t.mode),t.reValidateMode&&(c._options.reValidateMode=t.reValidateMode)},[c,t.mode,t.reValidateMode]),ae.useEffect(()=>{t.errors&&(c._setErrors(t.errors),c._focusError())},[c,t.errors]),ae.useEffect(()=>{t.shouldUnregister&&c._subjects.state.next({values:c._getWatch()})},[c,t.shouldUnregister]),ae.useEffect(()=>{if(c._proxyFormState.isDirty){const u=c._getDirty();u!==s.isDirty&&c._subjects.state.next({isDirty:u})}},[c,s.isDirty]),ae.useEffect(()=>{t.values&&!Pr(t.values,r.current)?(c._reset(t.values,{keepFieldsRef:!0,...c._options.resetOptions}),r.current=t.values,i(u=>({...u}))):c._resetDefaultValues()},[c,t.values]),ae.useEffect(()=>{c._state.mount||(c._setValid(),c._state.mount=!0),c._state.watch&&(c._state.watch=!1,c._subjects.state.next({...c._formState})),c._removeUnmounted()}),n.current.formState=A4(s,c),n.current}var F4=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],$4=F4.reduce((t,n)=>{const r=Y1(`Primitive.${n}`),s=b.forwardRef((i,c)=>{const{asChild:u,...f}=i,g=u?r:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{}),G4="Label",cS=b.forwardRef((t,n)=>p.jsx($4.label,{...t,ref:n,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));cS.displayName=G4;var Y4=cS,Z4=Object.defineProperty,X4=Object.defineProperties,K4=Object.getOwnPropertyDescriptors,du=Object.getOwnPropertySymbols,uS=Object.prototype.hasOwnProperty,dS=Object.prototype.propertyIsEnumerable,L0=(t,n,r)=>n in t?Z4(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,Q4=(t,n)=>{for(var r in n||(n={}))uS.call(n,r)&&L0(t,r,n[r]);if(du)for(var r of du(n))dS.call(n,r)&&L0(t,r,n[r]);return t},W4=(t,n)=>X4(t,K4(n)),J4=(t,n)=>{var r={};for(var s in t)uS.call(t,s)&&n.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&du)for(var s of du(t))n.indexOf(s)<0&&dS.call(t,s)&&(r[s]=t[s]);return r};function ez(t){let n=setTimeout(t,0),r=setTimeout(t,10),s=setTimeout(t,50);return[n,r,s]}function tz(t){let n=b.useRef();return b.useEffect(()=>{n.current=t}),n.current}var nz=18,fS=40,az=`${fS}px`,rz=["[data-lastpass-icon-root]","com-1password-button","[data-dashlanecreated]",'[style$="2147483647 !important;"]'].join(",");function sz({containerRef:t,inputRef:n,pushPasswordManagerStrategy:r,isFocused:s}){let[i,c]=b.useState(!1),[u,f]=b.useState(!1),[g,h]=b.useState(!1),v=b.useMemo(()=>r==="none"?!1:(r==="increase-width"||r==="experimental-no-flickering")&&i&&u,[i,u,r]),y=b.useCallback(()=>{let w=t.current,N=n.current;if(!w||!N||g||r==="none")return;let E=w,S=E.getBoundingClientRect().left+E.offsetWidth,C=E.getBoundingClientRect().top+E.offsetHeight/2,A=S-nz,O=C;document.querySelectorAll(rz).length===0&&document.elementFromPoint(A,O)===w||(c(!0),h(!0))},[t,n,g,r]);return b.useEffect(()=>{let w=t.current;if(!w||r==="none")return;function N(){let S=window.innerWidth-w.getBoundingClientRect().right;f(S>=fS)}N();let E=setInterval(N,1e3);return()=>{clearInterval(E)}},[t,r]),b.useEffect(()=>{let w=s||document.activeElement===n.current;if(r==="none"||!w)return;let N=setTimeout(y,0),E=setTimeout(y,2e3),S=setTimeout(y,5e3),C=setTimeout(()=>{h(!0)},6e3);return()=>{clearTimeout(N),clearTimeout(E),clearTimeout(S),clearTimeout(C)}},[n,s,r,y]),{hasPWMBadge:i,willPushPWMBadge:v,PWM_BADGE_SPACE_WIDTH:az}}var oz=b.createContext({}),iz=b.forwardRef((t,n)=>{var r=t,{value:s,onChange:i,maxLength:c,textAlign:u="left",pattern:f,placeholder:g,inputMode:h="numeric",onComplete:v,pushPasswordManagerStrategy:y="increase-width",pasteTransformer:w,containerClassName:N,noScriptCSSFallback:E=lz,render:S,children:C}=r,A=J4(r,["value","onChange","maxLength","textAlign","pattern","placeholder","inputMode","onComplete","pushPasswordManagerStrategy","pasteTransformer","containerClassName","noScriptCSSFallback","render","children"]),O,R,L,I,ee;let[U,Q]=b.useState(typeof A.defaultValue=="string"?A.defaultValue:""),le=s??U,ue=tz(le),me=b.useCallback(xe=>{i==null||i(xe),Q(xe)},[i]),re=b.useMemo(()=>f?typeof f=="string"?new RegExp(f):f:null,[f]),X=b.useRef(null),he=b.useRef(null),be=b.useRef({value:le,onChange:me,isIOS:typeof window<"u"&&((R=(O=window==null?void 0:window.CSS)==null?void 0:O.supports)==null?void 0:R.call(O,"-webkit-touch-callout","none"))}),j=b.useRef({prev:[(L=X.current)==null?void 0:L.selectionStart,(I=X.current)==null?void 0:I.selectionEnd,(ee=X.current)==null?void 0:ee.selectionDirection]});b.useImperativeHandle(n,()=>X.current,[]),b.useEffect(()=>{let xe=X.current,je=he.current;if(!xe||!je)return;be.current.value!==xe.value&&be.current.onChange(xe.value),j.current.prev=[xe.selectionStart,xe.selectionEnd,xe.selectionDirection];function at(){if(document.activeElement!==xe){Y(null),V(null);return}let Ue=xe.selectionStart,k=xe.selectionEnd,H=xe.selectionDirection,$=xe.maxLength,ye=xe.value,pe=j.current.prev,ge=-1,Se=-1,qe;if(ye.length!==0&&Ue!==null&&k!==null){let dn=Ue===k,Fn=Ue===ye.length&&ye.length<$;if(dn&&!Fn){let Ft=Ue;if(Ft===0)ge=0,Se=1,qe="forward";else if(Ft===$)ge=Ft-1,Se=Ft,qe="backward";else if($>1&&ye.length>1){let Nt=0;if(pe[0]!==null&&pe[1]!==null){qe=Ft<pe[1]?"backward":"forward";let fn=pe[0]===pe[1]&&pe[0]<$;qe==="backward"&&!fn&&(Nt=-1)}ge=Nt+Ft,Se=Nt+Ft+1}}ge!==-1&&Se!==-1&&ge!==Se&&X.current.setSelectionRange(ge,Se,qe)}let Xe=ge!==-1?ge:Ue,Ot=Se!==-1?Se:k,on=qe??H;Y(Xe),V(Ot),j.current.prev=[Xe,Ot,on]}if(document.addEventListener("selectionchange",at,{capture:!0}),at(),document.activeElement===xe&&we(!0),!document.getElementById("input-otp-style")){let Ue=document.createElement("style");if(Ue.id="input-otp-style",document.head.appendChild(Ue),Ue.sheet){let k="background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;";$i(Ue.sheet,"[data-input-otp]::selection { background: transparent !important; color: transparent !important; }"),$i(Ue.sheet,`[data-input-otp]:autofill { ${k} }`),$i(Ue.sheet,`[data-input-otp]:-webkit-autofill { ${k} }`),$i(Ue.sheet,"@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }"),$i(Ue.sheet,"[data-input-otp] + * { pointer-events: all !important; }")}}let pt=()=>{je&&je.style.setProperty("--root-height",`${xe.clientHeight}px`)};pt();let Je=new ResizeObserver(pt);return Je.observe(xe),()=>{document.removeEventListener("selectionchange",at,{capture:!0}),Je.disconnect()}},[]);let[Z,P]=b.useState(!1),[se,we]=b.useState(!1),[T,Y]=b.useState(null),[D,V]=b.useState(null);b.useEffect(()=>{ez(()=>{var xe,je,at,pt;(xe=X.current)==null||xe.dispatchEvent(new Event("input"));let Je=(je=X.current)==null?void 0:je.selectionStart,Ue=(at=X.current)==null?void 0:at.selectionEnd,k=(pt=X.current)==null?void 0:pt.selectionDirection;Je!==null&&Ue!==null&&(Y(Je),V(Ue),j.current.prev=[Je,Ue,k])})},[le,se]),b.useEffect(()=>{ue!==void 0&&le!==ue&&ue.length<c&&le.length===c&&(v==null||v(le))},[c,v,ue,le]);let te=sz({containerRef:he,inputRef:X,pushPasswordManagerStrategy:y,isFocused:se}),fe=b.useCallback(xe=>{let je=xe.currentTarget.value.slice(0,c);if(je.length>0&&re&&!re.test(je)){xe.preventDefault();return}typeof ue=="string"&&je.length<ue.length&&document.dispatchEvent(new Event("selectionchange")),me(je)},[c,me,ue,re]),oe=b.useCallback(()=>{var xe;if(X.current){let je=Math.min(X.current.value.length,c-1),at=X.current.value.length;(xe=X.current)==null||xe.setSelectionRange(je,at),Y(je),V(at)}we(!0)},[c]),K=b.useCallback(xe=>{var je,at;let pt=X.current;if(!w&&(!be.current.isIOS||!xe.clipboardData||!pt))return;let Je=xe.clipboardData.getData("text/plain"),Ue=w?w(Je):Je;xe.preventDefault();let k=(je=X.current)==null?void 0:je.selectionStart,H=(at=X.current)==null?void 0:at.selectionEnd,$=(k!==H?le.slice(0,k)+Ue+le.slice(H):le.slice(0,k)+Ue+le.slice(k)).slice(0,c);if($.length>0&&re&&!re.test($))return;pt.value=$,me($);let ye=Math.min($.length,c-1),pe=$.length;pt.setSelectionRange(ye,pe),Y(ye),V(pe)},[c,me,re,le]),de=b.useMemo(()=>({position:"relative",cursor:A.disabled?"default":"text",userSelect:"none",WebkitUserSelect:"none",pointerEvents:"none"}),[A.disabled]),_e=b.useMemo(()=>({position:"absolute",inset:0,width:te.willPushPWMBadge?`calc(100% + ${te.PWM_BADGE_SPACE_WIDTH})`:"100%",clipPath:te.willPushPWMBadge?`inset(0 ${te.PWM_BADGE_SPACE_WIDTH} 0 0)`:void 0,height:"100%",display:"flex",textAlign:u,opacity:"1",color:"transparent",pointerEvents:"all",background:"transparent",caretColor:"transparent",border:"0 solid transparent",outline:"0 solid transparent",boxShadow:"none",lineHeight:"1",letterSpacing:"-.5em",fontSize:"var(--root-height)",fontFamily:"monospace",fontVariantNumeric:"tabular-nums"}),[te.PWM_BADGE_SPACE_WIDTH,te.willPushPWMBadge,u]),rt=b.useMemo(()=>b.createElement("input",W4(Q4({autoComplete:A.autoComplete||"one-time-code"},A),{"data-input-otp":!0,"data-input-otp-placeholder-shown":le.length===0||void 0,"data-input-otp-mss":T,"data-input-otp-mse":D,inputMode:h,pattern:re==null?void 0:re.source,"aria-placeholder":g,style:_e,maxLength:c,value:le,ref:X,onPaste:xe=>{var je;K(xe),(je=A.onPaste)==null||je.call(A,xe)},onChange:fe,onMouseOver:xe=>{var je;P(!0),(je=A.onMouseOver)==null||je.call(A,xe)},onMouseLeave:xe=>{var je;P(!1),(je=A.onMouseLeave)==null||je.call(A,xe)},onFocus:xe=>{var je;oe(),(je=A.onFocus)==null||je.call(A,xe)},onBlur:xe=>{var je;we(!1),(je=A.onBlur)==null||je.call(A,xe)}})),[fe,oe,K,h,_e,c,D,T,A,re==null?void 0:re.source,le]),De=b.useMemo(()=>({slots:Array.from({length:c}).map((xe,je)=>{var at;let pt=se&&T!==null&&D!==null&&(T===D&&je===T||je>=T&&je<D),Je=le[je]!==void 0?le[je]:null,Ue=le[0]!==void 0?null:(at=g==null?void 0:g[je])!=null?at:null;return{char:Je,placeholderChar:Ue,isActive:pt,hasFakeCaret:pt&&Je===null}}),isFocused:se,isHovering:!A.disabled&&Z}),[se,Z,c,D,T,A.disabled,le]),Le=b.useMemo(()=>S?S(De):b.createElement(oz.Provider,{value:De},C),[C,De,S]);return b.createElement(b.Fragment,null,E!==null&&b.createElement("noscript",null,b.createElement("style",null,E)),b.createElement("div",{ref:he,"data-input-otp-container":!0,style:de,className:N},Le,b.createElement("div",{style:{position:"absolute",inset:0,pointerEvents:"none"}},rt)))});iz.displayName="Input";function $i(t,n){try{t.insertRule(n)}catch{console.error("input-otp could not insert CSS rule:",n)}}var lz=`+[data-input-otp] {+ --nojs-bg: white !important;+ --nojs-fg: black !important;++ background-color: var(--nojs-bg) !important;+ color: var(--nojs-fg) !important;+ caret-color: var(--nojs-fg) !important;+ letter-spacing: .25em !important;+ text-align: center !important;+ border: 1px solid var(--nojs-fg) !important;+ border-radius: 4px !important;+ width: 100% !important;+}+@media (prefers-color-scheme: dark) {+ [data-input-otp] {+ --nojs-bg: black !important;+ --nojs-fg: white !important;+ }+}`;function cz(t){const n=uz(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(fz);if(g){const h=g.props.children,v=f.map(y=>y===g?b.Children.count(h)>1?b.Children.only(null):b.isValidElement(h)?h.props.children:null:y);return p.jsx(n,{...u,ref:i,children:b.isValidElement(h)?b.cloneElement(h,void 0,v):null})}return p.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function uz(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=hz(i),f=mz(c,i.props);return i.type!==b.Fragment&&(f.ref=s?lr(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var dz=Symbol("radix.slottable");function fz(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===dz}function mz(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function hz(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var mS="Popover",[hS]=_s(mS,[Iu]),Zu=Iu(),[tL,Zr]=hS(mS),pS="PopoverAnchor",pz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zr(pS,r),c=Zu(r),{onCustomAnchorAdd:u,onCustomAnchorRemove:f}=i;return b.useEffect(()=>(u(),()=>f()),[u,f]),p.jsx($h,{...c,...s,ref:n})});pz.displayName=pS;var gS="PopoverTrigger",gz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zr(gS,r),c=Zu(r),u=Zt(n,i.triggerRef),f=p.jsx(jt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":wS(i.open),...s,ref:u,onClick:Ve(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?f:p.jsx($h,{asChild:!0,...c,children:f})});gz.displayName=gS;var sp="PopoverPortal",[yz,vz]=hS(sp,{forceMount:void 0}),yS=t=>{const{__scopePopover:n,forceMount:r,children:s,container:i}=t,c=Zr(sp,n);return p.jsx(yz,{scope:n,forceMount:r,children:p.jsx(Ma,{present:r||c.open,children:p.jsx(Du,{asChild:!0,container:i,children:s})})})};yS.displayName=sp;var ko="PopoverContent",vS=b.forwardRef((t,n)=>{const r=vz(ko,t.__scopePopover),{forceMount:s=r.forceMount,...i}=t,c=Zr(ko,t.__scopePopover);return p.jsx(Ma,{present:s||c.open,children:c.modal?p.jsx(xz,{...i,ref:n}):p.jsx(wz,{...i,ref:n})})});vS.displayName=ko;var bz=cz("PopoverContent.RemoveScroll"),xz=b.forwardRef((t,n)=>{const r=Zr(ko,t.__scopePopover),s=b.useRef(null),i=Zt(n,s),c=b.useRef(!1);return b.useEffect(()=>{const u=s.current;if(u)return Mh(u)},[]),p.jsx(Lu,{as:bz,allowPinchZoom:!0,children:p.jsx(bS,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ve(t.onCloseAutoFocus,u=>{var f;u.preventDefault(),c.current||(f=r.triggerRef.current)==null||f.focus()}),onPointerDownOutside:Ve(t.onPointerDownOutside,u=>{const f=u.detail.originalEvent,g=f.button===0&&f.ctrlKey===!0,h=f.button===2||g;c.current=h},{checkForDefaultPrevented:!1}),onFocusOutside:Ve(t.onFocusOutside,u=>u.preventDefault(),{checkForDefaultPrevented:!1})})})}),wz=b.forwardRef((t,n)=>{const r=Zr(ko,t.__scopePopover),s=b.useRef(!1),i=b.useRef(!1);return p.jsx(bS,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var u,f;(u=t.onCloseAutoFocus)==null||u.call(t,c),c.defaultPrevented||(s.current||(f=r.triggerRef.current)==null||f.focus(),c.preventDefault()),s.current=!1,i.current=!1},onInteractOutside:c=>{var g,h;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(s.current=!0,c.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=c.target;((h=r.triggerRef.current)==null?void 0:h.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),bS=b.forwardRef((t,n)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:h,onInteractOutside:v,...y}=t,w=Zr(ko,r),N=Zu(r);return kh(),p.jsx(Mu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:p.jsx(ku,{asChild:!0,disableOutsidePointerEvents:u,onInteractOutside:v,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:h,onDismiss:()=>w.onOpenChange(!1),children:p.jsx(gw,{"data-state":wS(w.open),role:"dialog",id:w.contentId,...N,...y,ref:n,style:{...y.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),xS="PopoverClose",Sz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zr(xS,r);return p.jsx(jt.button,{type:"button",...s,ref:n,onClick:Ve(t.onClick,()=>i.onOpenChange(!1))})});Sz.displayName=xS;var Ez="PopoverArrow",_z=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Zu(r);return p.jsx(yw,{...i,...s,ref:n})});_z.displayName=Ez;function wS(t){return t?"open":"closed"}var Cz=yS,SS=vS;const op=b.createContext(null);op.displayName="PanelGroupContext";const Hn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandleId:"data-panel-resize-handle-id"},ip=10,Ro=b.useLayoutEffect,U0=_u.useId,Nz=typeof U0=="function"?U0:()=>null;let Az=0;function ES(t=null){const n=Nz(),r=b.useRef(t||n||null);return r.current===null&&(r.current=""+Az++),t??r.current}function _S({children:t,className:n="",collapsedSize:r,collapsible:s,defaultSize:i,forwardedRef:c,id:u,maxSize:f,minSize:g,onCollapse:h,onExpand:v,onResize:y,order:w,style:N,tagName:E="div",...S}){const C=b.useContext(op);if(C===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:A,expandPanel:O,getPanelSize:R,getPanelStyle:L,groupId:I,isPanelCollapsed:ee,reevaluatePanelConstraints:U,registerPanel:Q,resizePanel:le,unregisterPanel:ue}=C,me=ES(u),re=b.useRef({callbacks:{onCollapse:h,onExpand:v,onResize:y},constraints:{collapsedSize:r,collapsible:s,defaultSize:i,maxSize:f,minSize:g},id:me,idIsFromProps:u!==void 0,order:w});b.useRef({didLogMissingDefaultSizeWarning:!1}),Ro(()=>{const{callbacks:he,constraints:be}=re.current,j={...be};re.current.id=me,re.current.idIsFromProps=u!==void 0,re.current.order=w,he.onCollapse=h,he.onExpand=v,he.onResize=y,be.collapsedSize=r,be.collapsible=s,be.defaultSize=i,be.maxSize=f,be.minSize=g,(j.collapsedSize!==be.collapsedSize||j.collapsible!==be.collapsible||j.maxSize!==be.maxSize||j.minSize!==be.minSize)&&U(re.current,j)}),Ro(()=>{const he=re.current;return Q(he),()=>{ue(he)}},[w,me,Q,ue]),b.useImperativeHandle(c,()=>({collapse:()=>{A(re.current)},expand:he=>{O(re.current,he)},getId(){return me},getSize(){return R(re.current)},isCollapsed(){return ee(re.current)},isExpanded(){return!ee(re.current)},resize:he=>{le(re.current,he)}}),[A,O,R,ee,me,le]);const X=L(re.current,i);return b.createElement(E,{...S,children:t,className:n,id:me,style:{...X,...N},[Hn.groupId]:I,[Hn.panel]:"",[Hn.panelCollapsible]:s||void 0,[Hn.panelId]:me,[Hn.panelSize]:parseFloat(""+X.flexGrow).toFixed(1)})}const Rz=b.forwardRef((t,n)=>b.createElement(_S,{...t,forwardedRef:n}));_S.displayName="Panel";Rz.displayName="forwardRef(Panel)";function CS(t){return t.type==="keydown"}function NS(t){return t.type.startsWith("pointer")}function AS(t){return t.type.startsWith("mouse")}function Tz(t){if(NS(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(AS(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function jz(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}const Oz=1,kz=2,Mz=4,Dz=8;jz();let zz=new Map;function Mm(t,n){zz.set(t,n)}function Lz(){const[t,n]=b.useState(0);return b.useCallback(()=>n(r=>r+1),[])}function st(t,n){if(!t)throw console.error(n),Error(n)}function Ss(t,n,r=ip){return t.toFixed(r)===n.toFixed(r)?0:t>n?1:-1}function tr(t,n,r=ip){return Ss(t,n,r)===0}function Un(t,n,r){return Ss(t,n,r)===0}function Uz(t,n,r){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++){const i=t[s],c=n[s];if(!Un(i,c,r))return!1}return!0}function _o({panelConstraints:t,panelIndex:n,size:r}){const s=t[n];st(s!=null,`Panel constraints not found for index ${n}`);let{collapsedSize:i=0,collapsible:c,maxSize:u=100,minSize:f=0}=s;if(Ss(r,f)<0)if(c){const g=(i+f)/2;Ss(r,g)<0?r=i:r=f}else r=f;return r=Math.min(u,r),r=parseFloat(r.toFixed(ip)),r}function Yi({delta:t,initialLayout:n,panelConstraints:r,pivotIndices:s,prevLayout:i,trigger:c}){if(Un(t,0))return n;const u=[...n],[f,g]=s;st(f!=null,"Invalid first pivot index"),st(g!=null,"Invalid second pivot index");let h=0;if(c==="keyboard"){{const y=t<0?g:f,w=r[y];st(w,`Panel constraints not found for index ${y}`);const{collapsedSize:N=0,collapsible:E,minSize:S=0}=w;if(E){const C=n[y];if(st(C!=null,`Previous layout not found for panel index ${y}`),Un(C,N)){const A=S-C;Ss(A,Math.abs(t))>0&&(t=t<0?0-A:A)}}}{const y=t<0?f:g,w=r[y];st(w,`No panel constraints found for index ${y}`);const{collapsedSize:N=0,collapsible:E,minSize:S=0}=w;if(E){const C=n[y];if(st(C!=null,`Previous layout not found for panel index ${y}`),Un(C,S)){const A=C-N;Ss(A,Math.abs(t))>0&&(t=t<0?0-A:A)}}}}{const y=t<0?1:-1;let w=t<0?g:f,N=0;for(;;){const S=n[w];st(S!=null,`Previous layout not found for panel index ${w}`);const A=_o({panelConstraints:r,panelIndex:w,size:100})-S;if(N+=A,w+=y,w<0||w>=r.length)break}const E=Math.min(Math.abs(t),Math.abs(N));t=t<0?0-E:E}{let w=t<0?f:g;for(;w>=0&&w<r.length;){const N=Math.abs(t)-Math.abs(h),E=n[w];st(E!=null,`Previous layout not found for panel index ${w}`);const S=E-N,C=_o({panelConstraints:r,panelIndex:w,size:S});if(!Un(E,C)&&(h+=E-C,u[w]=C,h.toFixed(3).localeCompare(Math.abs(t).toFixed(3),void 0,{numeric:!0})>=0))break;t<0?w--:w++}}if(Uz(i,u))return i;{const y=t<0?g:f,w=n[y];st(w!=null,`Previous layout not found for panel index ${y}`);const N=w+h,E=_o({panelConstraints:r,panelIndex:y,size:N});if(u[y]=E,!Un(E,N)){let S=N-E,A=t<0?g:f;for(;A>=0&&A<r.length;){const O=u[A];st(O!=null,`Previous layout not found for panel index ${A}`);const R=O+S,L=_o({panelConstraints:r,panelIndex:A,size:R});if(Un(O,L)||(S-=L-O,u[A]=L),Un(S,0))break;t>0?A--:A++}}}const v=u.reduce((y,w)=>w+y,0);return Un(v,100)?u:i}function Bz({layout:t,panelsArray:n,pivotIndices:r}){let s=0,i=100,c=0,u=0;const f=r[0];st(f!=null,"No pivot index found"),n.forEach((y,w)=>{const{constraints:N}=y,{maxSize:E=100,minSize:S=0}=N;w===f?(s=S,i=E):(c+=S,u+=E)});const g=Math.min(i,100-c),h=Math.max(s,100-u),v=t[f];return{valueMax:g,valueMin:h,valueNow:v}}function fu(t,n=document){return Array.from(n.querySelectorAll(`[${Hn.resizeHandleId}][data-panel-group-id="${t}"]`))}function Pz(t,n,r=document){const i=fu(t,r).findIndex(c=>c.getAttribute(Hn.resizeHandleId)===n);return i??null}function RS(t,n,r){const s=Pz(t,n,r);return s!=null?[s,s+1]:[-1,-1]}function Hz(t){return t instanceof HTMLElement?!0:typeof t=="object"&&t!==null&&"tagName"in t&&"getAttribute"in t}function TS(t,n=document){if(Hz(n)&&n.dataset.panelGroupId==t)return n;const r=n.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return r||null}function lp(t,n=document){const r=n.querySelector(`[${Hn.resizeHandleId}="${t}"]`);return r||null}function Vz(t,n,r,s=document){var i,c,u,f;const g=lp(n,s),h=fu(t,s),v=g?h.indexOf(g):-1,y=(i=(c=r[v])===null||c===void 0?void 0:c.id)!==null&&i!==void 0?i:null,w=(u=(f=r[v+1])===null||f===void 0?void 0:f.id)!==null&&u!==void 0?u:null;return[y,w]}function Iz({committedValuesRef:t,eagerValuesRef:n,groupId:r,layout:s,panelDataArray:i,panelGroupElement:c,setLayout:u}){b.useRef({didWarnAboutMissingResizeHandle:!1}),Ro(()=>{if(!c)return;const f=fu(r,c);for(let g=0;g<i.length-1;g++){const{valueMax:h,valueMin:v,valueNow:y}=Bz({layout:s,panelsArray:i,pivotIndices:[g,g+1]}),w=f[g];if(w!=null){const N=i[g];st(N,`No panel data found for index "${g}"`),w.setAttribute("aria-controls",N.id),w.setAttribute("aria-valuemax",""+Math.round(h)),w.setAttribute("aria-valuemin",""+Math.round(v)),w.setAttribute("aria-valuenow",y!=null?""+Math.round(y):"")}}return()=>{f.forEach((g,h)=>{g.removeAttribute("aria-controls"),g.removeAttribute("aria-valuemax"),g.removeAttribute("aria-valuemin"),g.removeAttribute("aria-valuenow")})}},[r,s,i,c]),b.useEffect(()=>{if(!c)return;const f=n.current;st(f,"Eager values not found");const{panelDataArray:g}=f,h=TS(r,c);st(h!=null,`No group found for id "${r}"`);const v=fu(r,c);st(v,`No resize handles found for group id "${r}"`);const y=v.map(w=>{const N=w.getAttribute(Hn.resizeHandleId);st(N,"Resize handle element has no handle id attribute");const[E,S]=Vz(r,N,g,c);if(E==null||S==null)return()=>{};const C=A=>{if(!A.defaultPrevented)switch(A.key){case"Enter":{A.preventDefault();const O=g.findIndex(R=>R.id===E);if(O>=0){const R=g[O];st(R,`No panel data found for index ${O}`);const L=s[O],{collapsedSize:I=0,collapsible:ee,minSize:U=0}=R.constraints;if(L!=null&&ee){const Q=Yi({delta:Un(L,I)?U-I:I-L,initialLayout:s,panelConstraints:g.map(le=>le.constraints),pivotIndices:RS(r,N,c),prevLayout:s,trigger:"keyboard"});s!==Q&&u(Q)}}break}}};return w.addEventListener("keydown",C),()=>{w.removeEventListener("keydown",C)}});return()=>{y.forEach(w=>w())}},[c,t,n,r,s,i,u])}function B0(t,n){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==n[r])return!1;return!0}function jS(t,n){const r=t==="horizontal",{x:s,y:i}=Tz(n);return r?s:i}function qz(t,n,r,s,i){const c=r==="horizontal",u=lp(n,i);st(u,`No resize handle element found for id "${n}"`);const f=u.getAttribute(Hn.groupId);st(f,"Resize handle element has no group id attribute");let{initialCursorPosition:g}=s;const h=jS(r,t),v=TS(f,i);st(v,`No group element found for id "${f}"`);const y=v.getBoundingClientRect(),w=c?y.width:y.height;return(h-g)/w*100}function Fz(t,n,r,s,i,c){if(CS(t)){const u=r==="horizontal";let f=0;t.shiftKey?f=100:i!=null?f=i:f=10;let g=0;switch(t.key){case"ArrowDown":g=u?0:f;break;case"ArrowLeft":g=u?-f:0;break;case"ArrowRight":g=u?f:0;break;case"ArrowUp":g=u?0:-f;break;case"End":g=100;break;case"Home":g=-100;break}return g}else return s==null?0:qz(t,n,r,s,c)}function $z({panelDataArray:t}){const n=Array(t.length),r=t.map(c=>c.constraints);let s=0,i=100;for(let c=0;c<t.length;c++){const u=r[c];st(u,`Panel constraints not found for index ${c}`);const{defaultSize:f}=u;f!=null&&(s++,n[c]=f,i-=f)}for(let c=0;c<t.length;c++){const u=r[c];st(u,`Panel constraints not found for index ${c}`);const{defaultSize:f}=u;if(f!=null)continue;const g=t.length-s,h=i/g;s++,n[c]=h,i-=h}return n}function xo(t,n,r){n.forEach((s,i)=>{const c=t[i];st(c,`Panel data not found for index ${i}`);const{callbacks:u,constraints:f,id:g}=c,{collapsedSize:h=0,collapsible:v}=f,y=r[g];if(y==null||s!==y){r[g]=s;const{onCollapse:w,onExpand:N,onResize:E}=u;E&&E(s,y),v&&(w||N)&&(N&&(y==null||tr(y,h))&&!tr(s,h)&&N(),w&&(y==null||!tr(y,h))&&tr(s,h)&&w())}})}function Vc(t,n){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!=n[r])return!1;return!0}function Gz({defaultSize:t,dragState:n,layout:r,panelData:s,panelIndex:i,precision:c=3}){const u=r[i];let f;return u==null?f=t!=null?t.toFixed(c):"1":s.length===1?f="1":f=u.toFixed(c),{flexBasis:0,flexGrow:f,flexShrink:1,overflow:"hidden",pointerEvents:n!==null?"none":void 0}}function Yz(t,n=10){let r=null;return(...i)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{t(...i)},n)}}function P0(t){try{if(typeof localStorage<"u")t.getItem=n=>localStorage.getItem(n),t.setItem=(n,r)=>{localStorage.setItem(n,r)};else throw new Error("localStorage not supported in this environment")}catch(n){console.error(n),t.getItem=()=>null,t.setItem=()=>{}}}function OS(t){return`react-resizable-panels:${t}`}function kS(t){return t.map(n=>{const{constraints:r,id:s,idIsFromProps:i,order:c}=n;return i?s:c?`${c}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((n,r)=>n.localeCompare(r)).join(",")}function MS(t,n){try{const r=OS(t),s=n.getItem(r);if(s){const i=JSON.parse(s);if(typeof i=="object"&&i!=null)return i}}catch{}return null}function Zz(t,n,r){var s,i;const c=(s=MS(t,r))!==null&&s!==void 0?s:{},u=kS(n);return(i=c[u])!==null&&i!==void 0?i:null}function Xz(t,n,r,s,i){var c;const u=OS(t),f=kS(n),g=(c=MS(t,i))!==null&&c!==void 0?c:{};g[f]={expandToSizes:Object.fromEntries(r.entries()),layout:s};try{i.setItem(u,JSON.stringify(g))}catch(h){console.error(h)}}function H0({layout:t,panelConstraints:n}){const r=[...t],s=r.reduce((c,u)=>c+u,0);if(r.length!==n.length)throw Error(`Invalid ${n.length} panel layout: ${r.map(c=>`${c}%`).join(", ")}`);if(!Un(s,100)&&r.length>0)for(let c=0;c<n.length;c++){const u=r[c];st(u!=null,`No layout data found for index ${c}`);const f=100/s*u;r[c]=f}let i=0;for(let c=0;c<n.length;c++){const u=r[c];st(u!=null,`No layout data found for index ${c}`);const f=_o({panelConstraints:n,panelIndex:c,size:u});u!=f&&(i+=u-f,r[c]=f)}if(!Un(i,0))for(let c=0;c<n.length;c++){const u=r[c];st(u!=null,`No layout data found for index ${c}`);const f=u+i,g=_o({panelConstraints:n,panelIndex:c,size:f});if(u!==g&&(i-=g-u,r[c]=g,Un(i,0)))break}return r}const Kz=100,Zi={getItem:t=>(P0(Zi),Zi.getItem(t)),setItem:(t,n)=>{P0(Zi),Zi.setItem(t,n)}},V0={};function DS({autoSaveId:t=null,children:n,className:r="",direction:s,forwardedRef:i,id:c=null,onLayout:u=null,keyboardResizeBy:f=null,storage:g=Zi,style:h,tagName:v="div",...y}){const w=ES(c),N=b.useRef(null),[E,S]=b.useState(null),[C,A]=b.useState([]),O=Lz(),R=b.useRef({}),L=b.useRef(new Map),I=b.useRef(0),ee=b.useRef({autoSaveId:t,direction:s,dragState:E,id:w,keyboardResizeBy:f,onLayout:u,storage:g}),U=b.useRef({layout:C,panelDataArray:[],panelDataArrayChanged:!1});b.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),b.useImperativeHandle(i,()=>({getId:()=>ee.current.id,getLayout:()=>{const{layout:D}=U.current;return D},setLayout:D=>{const{onLayout:V}=ee.current,{layout:te,panelDataArray:fe}=U.current,oe=H0({layout:D,panelConstraints:fe.map(K=>K.constraints)});B0(te,oe)||(A(oe),U.current.layout=oe,V&&V(oe),xo(fe,oe,R.current))}}),[]),Ro(()=>{ee.current.autoSaveId=t,ee.current.direction=s,ee.current.dragState=E,ee.current.id=w,ee.current.onLayout=u,ee.current.storage=g}),Iz({committedValuesRef:ee,eagerValuesRef:U,groupId:w,layout:C,panelDataArray:U.current.panelDataArray,setLayout:A,panelGroupElement:N.current}),b.useEffect(()=>{const{panelDataArray:D}=U.current;if(t){if(C.length===0||C.length!==D.length)return;let V=V0[t];V==null&&(V=Yz(Xz,Kz),V0[t]=V);const te=[...D],fe=new Map(L.current);V(t,te,fe,C,g)}},[t,C,g]),b.useEffect(()=>{});const Q=b.useCallback(D=>{const{onLayout:V}=ee.current,{layout:te,panelDataArray:fe}=U.current;if(D.constraints.collapsible){const oe=fe.map(rt=>rt.constraints),{collapsedSize:K=0,panelSize:de,pivotIndices:_e}=ps(fe,D,te);if(st(de!=null,`Panel size not found for panel "${D.id}"`),!tr(de,K)){L.current.set(D.id,de);const De=So(fe,D)===fe.length-1?de-K:K-de,Le=Yi({delta:De,initialLayout:te,panelConstraints:oe,pivotIndices:_e,prevLayout:te,trigger:"imperative-api"});Vc(te,Le)||(A(Le),U.current.layout=Le,V&&V(Le),xo(fe,Le,R.current))}}},[]),le=b.useCallback((D,V)=>{const{onLayout:te}=ee.current,{layout:fe,panelDataArray:oe}=U.current;if(D.constraints.collapsible){const K=oe.map(xe=>xe.constraints),{collapsedSize:de=0,panelSize:_e=0,minSize:rt=0,pivotIndices:De}=ps(oe,D,fe),Le=V??rt;if(tr(_e,de)){const xe=L.current.get(D.id),je=xe!=null&&xe>=Le?xe:Le,pt=So(oe,D)===oe.length-1?_e-je:je-_e,Je=Yi({delta:pt,initialLayout:fe,panelConstraints:K,pivotIndices:De,prevLayout:fe,trigger:"imperative-api"});Vc(fe,Je)||(A(Je),U.current.layout=Je,te&&te(Je),xo(oe,Je,R.current))}}},[]),ue=b.useCallback(D=>{const{layout:V,panelDataArray:te}=U.current,{panelSize:fe}=ps(te,D,V);return st(fe!=null,`Panel size not found for panel "${D.id}"`),fe},[]),me=b.useCallback((D,V)=>{const{panelDataArray:te}=U.current,fe=So(te,D);return Gz({defaultSize:V,dragState:E,layout:C,panelData:te,panelIndex:fe})},[E,C]),re=b.useCallback(D=>{const{layout:V,panelDataArray:te}=U.current,{collapsedSize:fe=0,collapsible:oe,panelSize:K}=ps(te,D,V);return st(K!=null,`Panel size not found for panel "${D.id}"`),oe===!0&&tr(K,fe)},[]),X=b.useCallback(D=>{const{layout:V,panelDataArray:te}=U.current,{collapsedSize:fe=0,collapsible:oe,panelSize:K}=ps(te,D,V);return st(K!=null,`Panel size not found for panel "${D.id}"`),!oe||Ss(K,fe)>0},[]),he=b.useCallback(D=>{const{panelDataArray:V}=U.current;V.push(D),V.sort((te,fe)=>{const oe=te.order,K=fe.order;return oe==null&&K==null?0:oe==null?-1:K==null?1:oe-K}),U.current.panelDataArrayChanged=!0,O()},[O]);Ro(()=>{if(U.current.panelDataArrayChanged){U.current.panelDataArrayChanged=!1;const{autoSaveId:D,onLayout:V,storage:te}=ee.current,{layout:fe,panelDataArray:oe}=U.current;let K=null;if(D){const _e=Zz(D,oe,te);_e&&(L.current=new Map(Object.entries(_e.expandToSizes)),K=_e.layout)}K==null&&(K=$z({panelDataArray:oe}));const de=H0({layout:K,panelConstraints:oe.map(_e=>_e.constraints)});B0(fe,de)||(A(de),U.current.layout=de,V&&V(de),xo(oe,de,R.current))}}),Ro(()=>{const D=U.current;return()=>{D.layout=[]}},[]);const be=b.useCallback(D=>{let V=!1;const te=N.current;return te&&window.getComputedStyle(te,null).getPropertyValue("direction")==="rtl"&&(V=!0),function(oe){oe.preventDefault();const K=N.current;if(!K)return()=>null;const{direction:de,dragState:_e,id:rt,keyboardResizeBy:De,onLayout:Le}=ee.current,{layout:xe,panelDataArray:je}=U.current,{initialLayout:at}=_e??{},pt=RS(rt,D,K);let Je=Fz(oe,D,de,_e,De,K);const Ue=de==="horizontal";Ue&&V&&(Je=-Je);const k=je.map(ye=>ye.constraints),H=Yi({delta:Je,initialLayout:at??xe,panelConstraints:k,pivotIndices:pt,prevLayout:xe,trigger:CS(oe)?"keyboard":"mouse-or-touch"}),$=!Vc(xe,H);(NS(oe)||AS(oe))&&I.current!=Je&&(I.current=Je,!$&&Je!==0?Ue?Mm(D,Je<0?Oz:kz):Mm(D,Je<0?Mz:Dz):Mm(D,0)),$&&(A(H),U.current.layout=H,Le&&Le(H),xo(je,H,R.current))}},[]),j=b.useCallback((D,V)=>{const{onLayout:te}=ee.current,{layout:fe,panelDataArray:oe}=U.current,K=oe.map(xe=>xe.constraints),{panelSize:de,pivotIndices:_e}=ps(oe,D,fe);st(de!=null,`Panel size not found for panel "${D.id}"`);const De=So(oe,D)===oe.length-1?de-V:V-de,Le=Yi({delta:De,initialLayout:fe,panelConstraints:K,pivotIndices:_e,prevLayout:fe,trigger:"imperative-api"});Vc(fe,Le)||(A(Le),U.current.layout=Le,te&&te(Le),xo(oe,Le,R.current))},[]),Z=b.useCallback((D,V)=>{const{layout:te,panelDataArray:fe}=U.current,{collapsedSize:oe=0,collapsible:K}=V,{collapsedSize:de=0,collapsible:_e,maxSize:rt=100,minSize:De=0}=D.constraints,{panelSize:Le}=ps(fe,D,te);Le!=null&&(K&&_e&&tr(Le,oe)?tr(oe,de)||j(D,de):Le<De?j(D,De):Le>rt&&j(D,rt))},[j]),P=b.useCallback((D,V)=>{const{direction:te}=ee.current,{layout:fe}=U.current;if(!N.current)return;const oe=lp(D,N.current);st(oe,`Drag handle element not found for id "${D}"`);const K=jS(te,V);S({dragHandleId:D,dragHandleRect:oe.getBoundingClientRect(),initialCursorPosition:K,initialLayout:fe})},[]),se=b.useCallback(()=>{S(null)},[]),we=b.useCallback(D=>{const{panelDataArray:V}=U.current,te=So(V,D);te>=0&&(V.splice(te,1),delete R.current[D.id],U.current.panelDataArrayChanged=!0,O())},[O]),T=b.useMemo(()=>({collapsePanel:Q,direction:s,dragState:E,expandPanel:le,getPanelSize:ue,getPanelStyle:me,groupId:w,isPanelCollapsed:re,isPanelExpanded:X,reevaluatePanelConstraints:Z,registerPanel:he,registerResizeHandle:be,resizePanel:j,startDragging:P,stopDragging:se,unregisterPanel:we,panelGroupElement:N.current}),[Q,E,s,le,ue,me,w,re,X,Z,he,be,j,P,se,we]),Y={display:"flex",flexDirection:s==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return b.createElement(op.Provider,{value:T},b.createElement(v,{...y,children:n,className:r,id:c,ref:N,style:{...Y,...h},[Hn.group]:"",[Hn.groupDirection]:s,[Hn.groupId]:w}))}const Qz=b.forwardRef((t,n)=>b.createElement(DS,{...t,forwardedRef:n}));DS.displayName="PanelGroup";Qz.displayName="forwardRef(PanelGroup)";function So(t,n){return t.findIndex(r=>r===n||r.id===n.id)}function ps(t,n,r){const s=So(t,n),c=s===t.length-1?[s-1,s]:[s,s+1],u=r[s];return{...n.constraints,panelSize:u,pivotIndices:c}}var Wz=(t,n,r,s,i,c,u,f)=>{let g=document.documentElement,h=["light","dark"];function v(N){(Array.isArray(t)?t:[t]).forEach(E=>{let S=E==="class",C=S&&c?i.map(A=>c[A]||A):i;S?(g.classList.remove(...C),g.classList.add(c&&c[N]?c[N]:N)):g.setAttribute(E,N)}),y(N)}function y(N){f&&h.includes(N)&&(g.style.colorScheme=N)}function w(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(s)v(s);else try{let N=localStorage.getItem(n)||r,E=u&&N==="system"?w():N;v(E)}catch{}};b.createContext(void 0);b.memo(({forcedTheme:t,storageKey:n,attribute:r,enableSystem:s,enableColorScheme:i,defaultTheme:c,value:u,themes:f,nonce:g,scriptProps:h})=>{let v=JSON.stringify([r,n,c,t,f,u,s,i]).slice(1,-1);return b.createElement("script",{...h,suppressHydrationWarning:!0,nonce:typeof window>"u"?g:"",dangerouslySetInnerHTML:{__html:`(${Wz.toString()})(${v})`}})});function Xt(...t){return Vx(Eh(t))}var Jz=Oh("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function e3({className:t,variant:n,...r}){return p.jsx("div",{"data-slot":"alert",role:"alert",className:Xt(Jz({variant:n}),t),...r})}function t3({className:t,...n}){return p.jsx("div",{"data-slot":"alert-title",className:Xt("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...n})}function n3({className:t,...n}){return p.jsx("div",{"data-slot":"alert-description",className:Xt("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...n})}var a3=Oh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}}),ft=b.forwardRef(({className:t,variant:n,size:r,asChild:s=!1,...i},c)=>{const u=s?Z1:"button";return p.jsx(u,{className:Xt(a3({variant:n,size:r,className:t})),ref:c,...i})});ft.displayName="Button";var r3=Oh("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function mu({className:t,variant:n,asChild:r=!1,...s}){const i=r?Z1:"span";return p.jsx(i,{"data-slot":"badge",className:Xt(r3({variant:n}),t),...s})}function s3({className:t,...n}){return p.jsx("div",{"data-slot":"card",className:Xt("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",t),...n})}function o3({className:t,...n}){return p.jsx("div",{"data-slot":"card-content",className:Xt("px-6",t),...n})}b.createContext(null);b.createContext(null);function hu({...t}){return p.jsx(ZO,{"data-slot":"dialog",...t})}function i3({...t}){return p.jsx(XO,{"data-slot":"dialog-portal",...t})}function l3({className:t,...n}){return p.jsx(F1,{"data-slot":"dialog-overlay",className:Xt("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...n})}function pu({className:t,children:n,showCloseButton:r=!0,...s}){return p.jsxs(i3,{"data-slot":"dialog-portal",children:[p.jsx(l3,{}),p.jsxs($1,{"data-slot":"dialog-content",className:Xt("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s,children:[n,r&&p.jsxs(WO,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[p.jsx(jj,{}),p.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gu({className:t,...n}){return p.jsx("div",{"data-slot":"dialog-header",className:Xt("flex flex-col gap-2 text-center sm:text-left",t),...n})}function zS({className:t,...n}){return p.jsx("div",{"data-slot":"dialog-footer",className:Xt("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...n})}function yu({className:t,...n}){return p.jsx(KO,{"data-slot":"dialog-title",className:Xt("text-lg leading-none font-semibold",t),...n})}function vu({className:t,...n}){return p.jsx(QO,{"data-slot":"dialog-description",className:Xt("text-muted-foreground text-sm",t),...n})}function c3({...t}){return p.jsx(y4,{"data-slot":"dropdown-menu",...t})}function u3({...t}){return p.jsx(v4,{"data-slot":"dropdown-menu-trigger",...t})}function d3({className:t,sideOffset:n=4,...r}){return p.jsx(b4,{children:p.jsx(x4,{"data-slot":"dropdown-menu-content",sideOffset:n,className:Xt("bg-popover text-popover-foreground 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 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...r})})}function f3({className:t,inset:n,variant:r="default",...s}){return p.jsx(w4,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:Xt("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function Ur({className:t,...n}){return p.jsx(Y4,{"data-slot":"label",className:Xt("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...n})}b.createContext({});b.createContext({});function Na({className:t,type:n,...r}){return p.jsx("input",{type:n,"data-slot":"input",className:Xt("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),...r})}var m3=b.forwardRef(({className:t,align:n="center",sideOffset:r=4,...s},i)=>p.jsx(Cz,{children:p.jsx(SS,{ref:i,align:n,sideOffset:r,className:Xt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none",t),...s})}));m3.displayName=SS.displayName;function h3({className:t,...n}){return p.jsx("div",{"data-slot":"skeleton",className:Xt("bg-accent animate-pulse rounded-md",t),...n})}b.createContext(null);b.createContext({size:"default",variant:"default"});const p3=()=>{const t=Vo();return p.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary/10 via-background to-background",children:p.jsx("div",{className:"container mx-auto px-4 py-16",children:p.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[p.jsxs("div",{className:"space-y-4",children:[p.jsx("h1",{className:"text-6xl font-bold text-primary animate-fadeIn",children:"Evolution GO"}),p.jsx("p",{className:"text-xl text-muted-foreground",children:"Interface moderna para gerenciamento de instâncias WhatsApp"})]}),p.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mt-12",children:[p.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[p.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:p.jsx(SA,{className:"w-6 h-6 text-primary"})}),p.jsx("h3",{className:"text-lg font-semibold",children:"Rápido e Eficiente"}),p.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie múltiplas instâncias WhatsApp com alta performance"})]}),p.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[p.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:p.jsx(fA,{className:"w-6 h-6 text-primary"})}),p.jsx("h3",{className:"text-lg font-semibold",children:"Seguro"}),p.jsx("p",{className:"text-sm text-muted-foreground",children:"Autenticação robusta e controle total sobre suas instâncias"})]}),p.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[p.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:p.jsx(VN,{className:"w-6 h-6 text-primary"})}),p.jsx("h3",{className:"text-lg font-semibold",children:"API Completa"}),p.jsx("p",{className:"text-sm text-muted-foreground",children:"Integração via API REST com Evolution GO"})]})]}),p.jsx("div",{className:"mt-12",children:p.jsxs(ft,{size:"lg",onClick:()=>t("/manager/login"),className:"text-lg px-8 py-6 group",children:["Acessar Manager",p.jsx(_N,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})}),p.jsxs("div",{className:"mt-16 pt-8 border-t",children:[p.jsx("p",{className:"text-sm text-muted-foreground",children:"Evolution GO Manager - Gerencie suas instâncias WhatsApp de forma simples e eficiente"}),p.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["© ",new Date().getFullYear()," Evolution GO. Todos os direitos reservados."]})]})]})})})};var ut;(function(t){t.assertEqual=i=>{};function n(i){}t.assertIs=n;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const c={};for(const u of i)c[u]=u;return c},t.getValidEnumValues=i=>{const c=t.objectKeys(i).filter(f=>typeof i[i[f]]!="number"),u={};for(const f of c)u[f]=i[f];return t.objectValues(u)},t.objectValues=i=>t.objectKeys(i).map(function(c){return i[c]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const c=[];for(const u in i)Object.prototype.hasOwnProperty.call(i,u)&&c.push(u);return c},t.find=(i,c)=>{for(const u of i)if(c(u))return u},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,c=" | "){return i.map(u=>typeof u=="string"?`'${u}'`:u).join(c)}t.joinValues=s,t.jsonStringifyReplacer=(i,c)=>typeof c=="bigint"?c.toString():c})(ut||(ut={}));var I0;(function(t){t.mergeShapes=(n,r)=>({...n,...r})})(I0||(I0={}));const Te=ut.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Br=t=>{switch(typeof t){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(t)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(t)?Te.array:t===null?Te.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Te.promise:typeof Map<"u"&&t instanceof Map?Te.map:typeof Set<"u"&&t instanceof Set?Te.set:typeof Date<"u"&&t instanceof Date?Te.date:Te.object;default:return Te.unknown}},ve=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"]);class ir extends Error{get errors(){return this.issues}constructor(n){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=n}format(n){const r=n||function(c){return c.message},s={_errors:[]},i=c=>{for(const u of c.issues)if(u.code==="invalid_union")u.unionErrors.map(i);else if(u.code==="invalid_return_type")i(u.returnTypeError);else if(u.code==="invalid_arguments")i(u.argumentsError);else if(u.path.length===0)s._errors.push(r(u));else{let f=s,g=0;for(;g<u.path.length;){const h=u.path[g];g===u.path.length-1?(f[h]=f[h]||{_errors:[]},f[h]._errors.push(r(u))):f[h]=f[h]||{_errors:[]},f=f[h],g++}}};return i(this),s}static assert(n){if(!(n instanceof ir))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ut.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=r=>r.message){const r={},s=[];for(const i of this.issues)if(i.path.length>0){const c=i.path[0];r[c]=r[c]||[],r[c].push(n(i))}else s.push(n(i));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}}ir.create=t=>new ir(t);const rh=(t,n)=>{let r;switch(t.code){case ve.invalid_type:t.received===Te.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ve.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ut.jsonStringifyReplacer)}`;break;case ve.unrecognized_keys:r=`Unrecognized key(s) in object: ${ut.joinValues(t.keys,", ")}`;break;case ve.invalid_union:r="Invalid input";break;case ve.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ut.joinValues(t.options)}`;break;case ve.invalid_enum_value:r=`Invalid enum value. Expected ${ut.joinValues(t.options)}, received '${t.received}'`;break;case ve.invalid_arguments:r="Invalid function arguments";break;case ve.invalid_return_type:r="Invalid function return type";break;case ve.invalid_date:r="Invalid date";break;case ve.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ut.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ve.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ve.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ve.custom:r="Invalid input";break;case ve.invalid_intersection_types:r="Intersection results could not be merged";break;case ve.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ve.not_finite:r="Number must be finite";break;default:r=n.defaultError,ut.assertNever(t)}return{message:r}};let g3=rh;function y3(){return g3}const v3=t=>{const{data:n,path:r,errorMaps:s,issueData:i}=t,c=[...r,...i.path||[]],u={...i,path:c};if(i.message!==void 0)return{...i,path:c,message:i.message};let f="";const g=s.filter(h=>!!h).slice().reverse();for(const h of g)f=h(u,{data:n,defaultError:f}).message;return{...i,path:c,message:f}};function Ee(t,n){const r=y3(),s=v3({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===rh?void 0:rh].filter(i=>!!i)});t.common.issues.push(s)}class In{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(n,r){const s=[];for(const i of r){if(i.status==="aborted")return He;i.status==="dirty"&&n.dirty(),s.push(i.value)}return{status:n.value,value:s}}static async mergeObjectAsync(n,r){const s=[];for(const i of r){const c=await i.key,u=await i.value;s.push({key:c,value:u})}return In.mergeObjectSync(n,s)}static mergeObjectSync(n,r){const s={};for(const i of r){const{key:c,value:u}=i;if(c.status==="aborted"||u.status==="aborted")return He;c.status==="dirty"&&n.dirty(),u.status==="dirty"&&n.dirty(),c.value!=="__proto__"&&(typeof u.value<"u"||i.alwaysSet)&&(s[c.value]=u.value)}return{status:n.value,value:s}}}const He=Object.freeze({status:"aborted"}),Xi=t=>({status:"dirty",value:t}),ra=t=>({status:"valid",value:t}),q0=t=>t.status==="aborted",F0=t=>t.status==="dirty",Mo=t=>t.status==="valid",bu=t=>typeof Promise<"u"&&t instanceof Promise;var ke;(function(t){t.errToObj=n=>typeof n=="string"?{message:n}:n||{},t.toString=n=>typeof n=="string"?n:n==null?void 0:n.message})(ke||(ke={}));class $r{constructor(n,r,s,i){this._cachedPath=[],this.parent=n,this.data=r,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $0=(t,n)=>{if(Mo(n))return{success:!0,data:n.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ir(t.common.issues);return this._error=r,this._error}}};function Ze(t){if(!t)return{};const{errorMap:n,invalid_type_error:r,required_error:s,description:i}=t;if(n&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return n?{errorMap:n,description:i}:{errorMap:(u,f)=>{const{message:g}=t;return u.code==="invalid_enum_value"?{message:g??f.defaultError}:typeof f.data>"u"?{message:g??s??f.defaultError}:u.code!=="invalid_type"?{message:f.defaultError}:{message:g??r??f.defaultError}},description:i}}class it{get description(){return this._def.description}_getType(n){return Br(n.data)}_getOrReturnCtx(n,r){return r||{common:n.parent.common,data:n.data,parsedType:Br(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new In,ctx:{common:n.parent.common,data:n.data,parsedType:Br(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const r=this._parse(n);if(bu(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(n){const r=this._parse(n);return Promise.resolve(r)}parse(n,r){const s=this.safeParse(n,r);if(s.success)return s.data;throw s.error}safeParse(n,r){const s={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Br(n)},i=this._parseSync({data:n,path:s.path,parent:s});return $0(s,i)}"~validate"(n){var s,i;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Br(n)};if(!this["~standard"].async)try{const c=this._parseSync({data:n,path:[],parent:r});return Mo(c)?{value:c.value}:{issues:r.common.issues}}catch(c){(i=(s=c==null?void 0:c.message)==null?void 0:s.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:r}).then(c=>Mo(c)?{value:c.value}:{issues:r.common.issues})}async parseAsync(n,r){const s=await this.safeParseAsync(n,r);if(s.success)return s.data;throw s.error}async safeParseAsync(n,r){const s={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Br(n)},i=this._parse({data:n,path:s.path,parent:s}),c=await(bu(i)?i:Promise.resolve(i));return $0(s,c)}refine(n,r){const s=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,c)=>{const u=n(i),f=()=>c.addIssue({code:ve.custom,...s(i)});return typeof Promise<"u"&&u instanceof Promise?u.then(g=>g?!0:(f(),!1)):u?!0:(f(),!1)})}refinement(n,r){return this._refinement((s,i)=>n(s)?!0:(i.addIssue(typeof r=="function"?r(s,i):r),!1))}_refinement(n){return new zo({schema:this,typeName:Ie.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,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),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Vr.create(this,this._def)}nullable(){return Lo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Oa.create(this)}promise(){return Eu.create(this,this._def)}or(n){return wu.create([this,n],this._def)}and(n){return Su.create(this,n,this._def)}transform(n){return new zo({...Ze(this._def),schema:this,typeName:Ie.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const r=typeof n=="function"?n:()=>n;return new lh({...Ze(this._def),innerType:this,defaultValue:r,typeName:Ie.ZodDefault})}brand(){return new V3({typeName:Ie.ZodBranded,type:this,...Ze(this._def)})}catch(n){const r=typeof n=="function"?n:()=>n;return new ch({...Ze(this._def),innerType:this,catchValue:r,typeName:Ie.ZodCatch})}describe(n){const r=this.constructor;return new r({...this._def,description:n})}pipe(n){return cp.create(this,n)}readonly(){return uh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const b3=/^c[^\s-]{8,}$/i,x3=/^[0-9a-z]+$/,w3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,S3=/^[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,E3=/^[a-z0-9_-]{21}$/i,_3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,C3=/^[-+]?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)?)??$/,N3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,A3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Dm;const R3=/^(?:(?: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])$/,T3=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,j3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,O3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,k3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,M3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,LS="((\\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])))",D3=new RegExp(`^${LS}$`);function US(t){let n="[0-5]\\d";t.precision?n=`${n}\\.\\d{${t.precision}}`:t.precision==null&&(n=`${n}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${r}`}function z3(t){return new RegExp(`^${US(t)}$`)}function L3(t){let n=`${LS}T${US(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),n=`${n}(${r.join("|")})`,new RegExp(`^${n}$`)}function U3(t,n){return!!((n==="v4"||!n)&&R3.test(t)||(n==="v6"||!n)&&j3.test(t))}function B3(t,n){if(!_3.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||n&&i.alg!==n)}catch{return!1}}function P3(t,n){return!!((n==="v4"||!n)&&T3.test(t)||(n==="v6"||!n)&&O3.test(t))}class Hr extends it{_parse(n){if(this._def.coerce&&(n.data=String(n.data)),this._getType(n)!==Te.string){const c=this._getOrReturnCtx(n);return Ee(c,{code:ve.invalid_type,expected:Te.string,received:c.parsedType}),He}const s=new In;let i;for(const c of this._def.checks)if(c.kind==="min")n.data.length<c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),s.dirty());else if(c.kind==="max")n.data.length>c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),s.dirty());else if(c.kind==="length"){const u=n.data.length>c.value,f=n.data.length<c.value;(u||f)&&(i=this._getOrReturnCtx(n,i),u?Ee(i,{code:ve.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}):f&&Ee(i,{code:ve.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}),s.dirty())}else if(c.kind==="email")N3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"email",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="emoji")Dm||(Dm=new RegExp(A3,"u")),Dm.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"emoji",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="uuid")S3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"uuid",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="nanoid")E3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"nanoid",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="cuid")b3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cuid",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="cuid2")x3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cuid2",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="ulid")w3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"ulid",code:ve.invalid_string,message:c.message}),s.dirty());else if(c.kind==="url")try{new URL(n.data)}catch{i=this._getOrReturnCtx(n,i),Ee(i,{validation:"url",code:ve.invalid_string,message:c.message}),s.dirty()}else c.kind==="regex"?(c.regex.lastIndex=0,c.regex.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"regex",code:ve.invalid_string,message:c.message}),s.dirty())):c.kind==="trim"?n.data=n.data.trim():c.kind==="includes"?n.data.includes(c.value,c.position)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:{includes:c.value,position:c.position},message:c.message}),s.dirty()):c.kind==="toLowerCase"?n.data=n.data.toLowerCase():c.kind==="toUpperCase"?n.data=n.data.toUpperCase():c.kind==="startsWith"?n.data.startsWith(c.value)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:{startsWith:c.value},message:c.message}),s.dirty()):c.kind==="endsWith"?n.data.endsWith(c.value)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:{endsWith:c.value},message:c.message}),s.dirty()):c.kind==="datetime"?L3(c).test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:"datetime",message:c.message}),s.dirty()):c.kind==="date"?D3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:"date",message:c.message}),s.dirty()):c.kind==="time"?z3(c).test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.invalid_string,validation:"time",message:c.message}),s.dirty()):c.kind==="duration"?C3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"duration",code:ve.invalid_string,message:c.message}),s.dirty()):c.kind==="ip"?U3(n.data,c.version)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"ip",code:ve.invalid_string,message:c.message}),s.dirty()):c.kind==="jwt"?B3(n.data,c.alg)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"jwt",code:ve.invalid_string,message:c.message}),s.dirty()):c.kind==="cidr"?P3(n.data,c.version)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cidr",code:ve.invalid_string,message:c.message}),s.dirty()):c.kind==="base64"?k3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"base64",code:ve.invalid_string,message:c.message}),s.dirty()):c.kind==="base64url"?M3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"base64url",code:ve.invalid_string,message:c.message}),s.dirty()):ut.assertNever(c);return{status:s.value,value:n.data}}_regex(n,r,s){return this.refinement(i=>n.test(i),{validation:r,code:ve.invalid_string,...ke.errToObj(s)})}_addCheck(n){return new Hr({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...ke.errToObj(n)})}url(n){return this._addCheck({kind:"url",...ke.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...ke.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...ke.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...ke.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...ke.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...ke.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...ke.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...ke.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...ke.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...ke.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...ke.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...ke.errToObj(n)})}datetime(n){return typeof n=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n}):this._addCheck({kind:"datetime",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,offset:(n==null?void 0:n.offset)??!1,local:(n==null?void 0:n.local)??!1,...ke.errToObj(n==null?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){return typeof n=="string"?this._addCheck({kind:"time",precision:null,message:n}):this._addCheck({kind:"time",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,...ke.errToObj(n==null?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...ke.errToObj(n)})}regex(n,r){return this._addCheck({kind:"regex",regex:n,...ke.errToObj(r)})}includes(n,r){return this._addCheck({kind:"includes",value:n,position:r==null?void 0:r.position,...ke.errToObj(r==null?void 0:r.message)})}startsWith(n,r){return this._addCheck({kind:"startsWith",value:n,...ke.errToObj(r)})}endsWith(n,r){return this._addCheck({kind:"endsWith",value:n,...ke.errToObj(r)})}min(n,r){return this._addCheck({kind:"min",value:n,...ke.errToObj(r)})}max(n,r){return this._addCheck({kind:"max",value:n,...ke.errToObj(r)})}length(n,r){return this._addCheck({kind:"length",value:n,...ke.errToObj(r)})}nonempty(n){return this.min(1,ke.errToObj(n))}trim(){return new Hr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Hr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Hr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(n=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find(n=>n.kind==="date")}get isTime(){return!!this._def.checks.find(n=>n.kind==="time")}get isDuration(){return!!this._def.checks.find(n=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find(n=>n.kind==="email")}get isURL(){return!!this._def.checks.find(n=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find(n=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find(n=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(n=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(n=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(n=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find(n=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find(n=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find(n=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find(n=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find(n=>n.kind==="base64url")}get minLength(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxLength(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}}Hr.create=t=>new Hr({checks:[],typeName:Ie.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ze(t)});function H3(t,n){const r=(t.toString().split(".")[1]||"").length,s=(n.toString().split(".")[1]||"").length,i=r>s?r:s,c=Number.parseInt(t.toFixed(i).replace(".","")),u=Number.parseInt(n.toFixed(i).replace(".",""));return c%u/10**i}class rl extends it{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce&&(n.data=Number(n.data)),this._getType(n)!==Te.number){const c=this._getOrReturnCtx(n);return Ee(c,{code:ve.invalid_type,expected:Te.number,received:c.parsedType}),He}let s;const i=new In;for(const c of this._def.checks)c.kind==="int"?ut.isInteger(n.data)||(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.invalid_type,expected:"integer",received:"float",message:c.message}),i.dirty()):c.kind==="min"?(c.inclusive?n.data<c.value:n.data<=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.too_small,minimum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),i.dirty()):c.kind==="max"?(c.inclusive?n.data>c.value:n.data>=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.too_big,maximum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),i.dirty()):c.kind==="multipleOf"?H3(n.data,c.value)!==0&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.not_multiple_of,multipleOf:c.value,message:c.message}),i.dirty()):c.kind==="finite"?Number.isFinite(n.data)||(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.not_finite,message:c.message}),i.dirty()):ut.assertNever(c);return{status:i.value,value:n.data}}gte(n,r){return this.setLimit("min",n,!0,ke.toString(r))}gt(n,r){return this.setLimit("min",n,!1,ke.toString(r))}lte(n,r){return this.setLimit("max",n,!0,ke.toString(r))}lt(n,r){return this.setLimit("max",n,!1,ke.toString(r))}setLimit(n,r,s,i){return new rl({...this._def,checks:[...this._def.checks,{kind:n,value:r,inclusive:s,message:ke.toString(i)}]})}_addCheck(n){return new rl({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:ke.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ke.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ke.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ke.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ke.toString(n)})}multipleOf(n,r){return this._addCheck({kind:"multipleOf",value:n,message:ke.toString(r)})}finite(n){return this._addCheck({kind:"finite",message:ke.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ke.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ke.toString(n)})}get minValue(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxValue(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}get isInt(){return!!this._def.checks.find(n=>n.kind==="int"||n.kind==="multipleOf"&&ut.isInteger(n.value))}get isFinite(){let n=null,r=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(n===null||s.value<n)&&(n=s.value)}return Number.isFinite(r)&&Number.isFinite(n)}}rl.create=t=>new rl({checks:[],typeName:Ie.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ze(t)});class sl extends it{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==Te.bigint)return this._getInvalidInput(n);let s;const i=new In;for(const c of this._def.checks)c.kind==="min"?(c.inclusive?n.data<c.value:n.data<=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.too_small,type:"bigint",minimum:c.value,inclusive:c.inclusive,message:c.message}),i.dirty()):c.kind==="max"?(c.inclusive?n.data>c.value:n.data>=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.too_big,type:"bigint",maximum:c.value,inclusive:c.inclusive,message:c.message}),i.dirty()):c.kind==="multipleOf"?n.data%c.value!==BigInt(0)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:ve.not_multiple_of,multipleOf:c.value,message:c.message}),i.dirty()):ut.assertNever(c);return{status:i.value,value:n.data}}_getInvalidInput(n){const r=this._getOrReturnCtx(n);return Ee(r,{code:ve.invalid_type,expected:Te.bigint,received:r.parsedType}),He}gte(n,r){return this.setLimit("min",n,!0,ke.toString(r))}gt(n,r){return this.setLimit("min",n,!1,ke.toString(r))}lte(n,r){return this.setLimit("max",n,!0,ke.toString(r))}lt(n,r){return this.setLimit("max",n,!1,ke.toString(r))}setLimit(n,r,s,i){return new sl({...this._def,checks:[...this._def.checks,{kind:n,value:r,inclusive:s,message:ke.toString(i)}]})}_addCheck(n){return new sl({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ke.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ke.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ke.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ke.toString(n)})}multipleOf(n,r){return this._addCheck({kind:"multipleOf",value:n,message:ke.toString(r)})}get minValue(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxValue(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}}sl.create=t=>new sl({checks:[],typeName:Ie.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ze(t)});class sh extends it{_parse(n){if(this._def.coerce&&(n.data=!!n.data),this._getType(n)!==Te.boolean){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.boolean,received:s.parsedType}),He}return ra(n.data)}}sh.create=t=>new sh({typeName:Ie.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ze(t)});class xu extends it{_parse(n){if(this._def.coerce&&(n.data=new Date(n.data)),this._getType(n)!==Te.date){const c=this._getOrReturnCtx(n);return Ee(c,{code:ve.invalid_type,expected:Te.date,received:c.parsedType}),He}if(Number.isNaN(n.data.getTime())){const c=this._getOrReturnCtx(n);return Ee(c,{code:ve.invalid_date}),He}const s=new In;let i;for(const c of this._def.checks)c.kind==="min"?n.data.getTime()<c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.too_small,message:c.message,inclusive:!0,exact:!1,minimum:c.value,type:"date"}),s.dirty()):c.kind==="max"?n.data.getTime()>c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:ve.too_big,message:c.message,inclusive:!0,exact:!1,maximum:c.value,type:"date"}),s.dirty()):ut.assertNever(c);return{status:s.value,value:new Date(n.data.getTime())}}_addCheck(n){return new xu({...this._def,checks:[...this._def.checks,n]})}min(n,r){return this._addCheck({kind:"min",value:n.getTime(),message:ke.toString(r)})}max(n,r){return this._addCheck({kind:"max",value:n.getTime(),message:ke.toString(r)})}get minDate(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n!=null?new Date(n):null}get maxDate(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n!=null?new Date(n):null}}xu.create=t=>new xu({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Ie.ZodDate,...Ze(t)});class G0 extends it{_parse(n){if(this._getType(n)!==Te.symbol){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.symbol,received:s.parsedType}),He}return ra(n.data)}}G0.create=t=>new G0({typeName:Ie.ZodSymbol,...Ze(t)});class Y0 extends it{_parse(n){if(this._getType(n)!==Te.undefined){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.undefined,received:s.parsedType}),He}return ra(n.data)}}Y0.create=t=>new Y0({typeName:Ie.ZodUndefined,...Ze(t)});class Z0 extends it{_parse(n){if(this._getType(n)!==Te.null){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.null,received:s.parsedType}),He}return ra(n.data)}}Z0.create=t=>new Z0({typeName:Ie.ZodNull,...Ze(t)});class X0 extends it{constructor(){super(...arguments),this._any=!0}_parse(n){return ra(n.data)}}X0.create=t=>new X0({typeName:Ie.ZodAny,...Ze(t)});class K0 extends it{constructor(){super(...arguments),this._unknown=!0}_parse(n){return ra(n.data)}}K0.create=t=>new K0({typeName:Ie.ZodUnknown,...Ze(t)});class Gr extends it{_parse(n){const r=this._getOrReturnCtx(n);return Ee(r,{code:ve.invalid_type,expected:Te.never,received:r.parsedType}),He}}Gr.create=t=>new Gr({typeName:Ie.ZodNever,...Ze(t)});class Q0 extends it{_parse(n){if(this._getType(n)!==Te.undefined){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.void,received:s.parsedType}),He}return ra(n.data)}}Q0.create=t=>new Q0({typeName:Ie.ZodVoid,...Ze(t)});class Oa extends it{_parse(n){const{ctx:r,status:s}=this._processInputParams(n),i=this._def;if(r.parsedType!==Te.array)return Ee(r,{code:ve.invalid_type,expected:Te.array,received:r.parsedType}),He;if(i.exactLength!==null){const u=r.data.length>i.exactLength.value,f=r.data.length<i.exactLength.value;(u||f)&&(Ee(r,{code:u?ve.too_big:ve.too_small,minimum:f?i.exactLength.value:void 0,maximum:u?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Ee(r,{code:ve.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Ee(r,{code:ve.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((u,f)=>i.type._parseAsync(new $r(r,u,r.path,f)))).then(u=>In.mergeArray(s,u));const c=[...r.data].map((u,f)=>i.type._parseSync(new $r(r,u,r.path,f)));return In.mergeArray(s,c)}get element(){return this._def.type}min(n,r){return new Oa({...this._def,minLength:{value:n,message:ke.toString(r)}})}max(n,r){return new Oa({...this._def,maxLength:{value:n,message:ke.toString(r)}})}length(n,r){return new Oa({...this._def,exactLength:{value:n,message:ke.toString(r)}})}nonempty(n){return this.min(1,n)}}Oa.create=(t,n)=>new Oa({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Ie.ZodArray,...Ze(n)});function Eo(t){if(t instanceof Vt){const n={};for(const r in t.shape){const s=t.shape[r];n[r]=Vr.create(Eo(s))}return new Vt({...t._def,shape:()=>n})}else return t instanceof Oa?new Oa({...t._def,type:Eo(t.element)}):t instanceof Vr?Vr.create(Eo(t.unwrap())):t instanceof Lo?Lo.create(Eo(t.unwrap())):t instanceof Es?Es.create(t.items.map(n=>Eo(n))):t}class Vt extends it{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const n=this._def.shape(),r=ut.objectKeys(n);return this._cached={shape:n,keys:r},this._cached}_parse(n){if(this._getType(n)!==Te.object){const h=this._getOrReturnCtx(n);return Ee(h,{code:ve.invalid_type,expected:Te.object,received:h.parsedType}),He}const{status:s,ctx:i}=this._processInputParams(n),{shape:c,keys:u}=this._getCached(),f=[];if(!(this._def.catchall instanceof Gr&&this._def.unknownKeys==="strip"))for(const h in i.data)u.includes(h)||f.push(h);const g=[];for(const h of u){const v=c[h],y=i.data[h];g.push({key:{status:"valid",value:h},value:v._parse(new $r(i,y,i.path,h)),alwaysSet:h in i.data})}if(this._def.catchall instanceof Gr){const h=this._def.unknownKeys;if(h==="passthrough")for(const v of f)g.push({key:{status:"valid",value:v},value:{status:"valid",value:i.data[v]}});else if(h==="strict")f.length>0&&(Ee(i,{code:ve.unrecognized_keys,keys:f}),s.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const h=this._def.catchall;for(const v of f){const y=i.data[v];g.push({key:{status:"valid",value:v},value:h._parse(new $r(i,y,i.path,v)),alwaysSet:v in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const h=[];for(const v of g){const y=await v.key,w=await v.value;h.push({key:y,value:w,alwaysSet:v.alwaysSet})}return h}).then(h=>In.mergeObjectSync(s,h)):In.mergeObjectSync(s,g)}get shape(){return this._def.shape()}strict(n){return ke.errToObj,new Vt({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(r,s)=>{var c,u;const i=((u=(c=this._def).errorMap)==null?void 0:u.call(c,r,s).message)??s.defaultError;return r.code==="unrecognized_keys"?{message:ke.errToObj(n).message??i}:{message:i}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(n){return new Vt({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new Vt({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:Ie.ZodObject})}setKey(n,r){return this.augment({[n]:r})}catchall(n){return new Vt({...this._def,catchall:n})}pick(n){const r={};for(const s of ut.objectKeys(n))n[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new Vt({...this._def,shape:()=>r})}omit(n){const r={};for(const s of ut.objectKeys(this.shape))n[s]||(r[s]=this.shape[s]);return new Vt({...this._def,shape:()=>r})}deepPartial(){return Eo(this)}partial(n){const r={};for(const s of ut.objectKeys(this.shape)){const i=this.shape[s];n&&!n[s]?r[s]=i:r[s]=i.optional()}return new Vt({...this._def,shape:()=>r})}required(n){const r={};for(const s of ut.objectKeys(this.shape))if(n&&!n[s])r[s]=this.shape[s];else{let c=this.shape[s];for(;c instanceof Vr;)c=c._def.innerType;r[s]=c}return new Vt({...this._def,shape:()=>r})}keyof(){return BS(ut.objectKeys(this.shape))}}Vt.create=(t,n)=>new Vt({shape:()=>t,unknownKeys:"strip",catchall:Gr.create(),typeName:Ie.ZodObject,...Ze(n)});Vt.strictCreate=(t,n)=>new Vt({shape:()=>t,unknownKeys:"strict",catchall:Gr.create(),typeName:Ie.ZodObject,...Ze(n)});Vt.lazycreate=(t,n)=>new Vt({shape:t,unknownKeys:"strip",catchall:Gr.create(),typeName:Ie.ZodObject,...Ze(n)});class wu extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s=this._def.options;function i(c){for(const f of c)if(f.result.status==="valid")return f.result;for(const f of c)if(f.result.status==="dirty")return r.common.issues.push(...f.ctx.common.issues),f.result;const u=c.map(f=>new ir(f.ctx.common.issues));return Ee(r,{code:ve.invalid_union,unionErrors:u}),He}if(r.common.async)return Promise.all(s.map(async c=>{const u={...r,common:{...r.common,issues:[]},parent:null};return{result:await c._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(i);{let c;const u=[];for(const g of s){const h={...r,common:{...r.common,issues:[]},parent:null},v=g._parseSync({data:r.data,path:r.path,parent:h});if(v.status==="valid")return v;v.status==="dirty"&&!c&&(c={result:v,ctx:h}),h.common.issues.length&&u.push(h.common.issues)}if(c)return r.common.issues.push(...c.ctx.common.issues),c.result;const f=u.map(g=>new ir(g));return Ee(r,{code:ve.invalid_union,unionErrors:f}),He}}get options(){return this._def.options}}wu.create=(t,n)=>new wu({options:t,typeName:Ie.ZodUnion,...Ze(n)});function oh(t,n){const r=Br(t),s=Br(n);if(t===n)return{valid:!0,data:t};if(r===Te.object&&s===Te.object){const i=ut.objectKeys(n),c=ut.objectKeys(t).filter(f=>i.indexOf(f)!==-1),u={...t,...n};for(const f of c){const g=oh(t[f],n[f]);if(!g.valid)return{valid:!1};u[f]=g.data}return{valid:!0,data:u}}else if(r===Te.array&&s===Te.array){if(t.length!==n.length)return{valid:!1};const i=[];for(let c=0;c<t.length;c++){const u=t[c],f=n[c],g=oh(u,f);if(!g.valid)return{valid:!1};i.push(g.data)}return{valid:!0,data:i}}else return r===Te.date&&s===Te.date&&+t==+n?{valid:!0,data:t}:{valid:!1}}class Su extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n),i=(c,u)=>{if(q0(c)||q0(u))return He;const f=oh(c.value,u.value);return f.valid?((F0(c)||F0(u))&&r.dirty(),{status:r.value,value:f.data}):(Ee(s,{code:ve.invalid_intersection_types}),He)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([c,u])=>i(c,u)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Su.create=(t,n,r)=>new Su({left:t,right:n,typeName:Ie.ZodIntersection,...Ze(r)});class Es extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.array)return Ee(s,{code:ve.invalid_type,expected:Te.array,received:s.parsedType}),He;if(s.data.length<this._def.items.length)return Ee(s,{code:ve.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),He;!this._def.rest&&s.data.length>this._def.items.length&&(Ee(s,{code:ve.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const c=[...s.data].map((u,f)=>{const g=this._def.items[f]||this._def.rest;return g?g._parse(new $r(s,u,s.path,f)):null}).filter(u=>!!u);return s.common.async?Promise.all(c).then(u=>In.mergeArray(r,u)):In.mergeArray(r,c)}get items(){return this._def.items}rest(n){return new Es({...this._def,rest:n})}}Es.create=(t,n)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Es({items:t,typeName:Ie.ZodTuple,rest:null,...Ze(n)})};class W0 extends it{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.map)return Ee(s,{code:ve.invalid_type,expected:Te.map,received:s.parsedType}),He;const i=this._def.keyType,c=this._def.valueType,u=[...s.data.entries()].map(([f,g],h)=>({key:i._parse(new $r(s,f,s.path,[h,"key"])),value:c._parse(new $r(s,g,s.path,[h,"value"]))}));if(s.common.async){const f=new Map;return Promise.resolve().then(async()=>{for(const g of u){const h=await g.key,v=await g.value;if(h.status==="aborted"||v.status==="aborted")return He;(h.status==="dirty"||v.status==="dirty")&&r.dirty(),f.set(h.value,v.value)}return{status:r.value,value:f}})}else{const f=new Map;for(const g of u){const h=g.key,v=g.value;if(h.status==="aborted"||v.status==="aborted")return He;(h.status==="dirty"||v.status==="dirty")&&r.dirty(),f.set(h.value,v.value)}return{status:r.value,value:f}}}}W0.create=(t,n,r)=>new W0({valueType:n,keyType:t,typeName:Ie.ZodMap,...Ze(r)});class ol extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.set)return Ee(s,{code:ve.invalid_type,expected:Te.set,received:s.parsedType}),He;const i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(Ee(s,{code:ve.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(Ee(s,{code:ve.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const c=this._def.valueType;function u(g){const h=new Set;for(const v of g){if(v.status==="aborted")return He;v.status==="dirty"&&r.dirty(),h.add(v.value)}return{status:r.value,value:h}}const f=[...s.data.values()].map((g,h)=>c._parse(new $r(s,g,s.path,h)));return s.common.async?Promise.all(f).then(g=>u(g)):u(f)}min(n,r){return new ol({...this._def,minSize:{value:n,message:ke.toString(r)}})}max(n,r){return new ol({...this._def,maxSize:{value:n,message:ke.toString(r)}})}size(n,r){return this.min(n,r).max(n,r)}nonempty(n){return this.min(1,n)}}ol.create=(t,n)=>new ol({valueType:t,minSize:null,maxSize:null,typeName:Ie.ZodSet,...Ze(n)});class J0 extends it{get schema(){return this._def.getter()}_parse(n){const{ctx:r}=this._processInputParams(n);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}J0.create=(t,n)=>new J0({getter:t,typeName:Ie.ZodLazy,...Ze(n)});class ih extends it{_parse(n){if(n.data!==this._def.value){const r=this._getOrReturnCtx(n);return Ee(r,{received:r.data,code:ve.invalid_literal,expected:this._def.value}),He}return{status:"valid",value:n.data}}get value(){return this._def.value}}ih.create=(t,n)=>new ih({value:t,typeName:Ie.ZodLiteral,...Ze(n)});function BS(t,n){return new Do({values:t,typeName:Ie.ZodEnum,...Ze(n)})}class Do extends it{_parse(n){if(typeof n.data!="string"){const r=this._getOrReturnCtx(n),s=this._def.values;return Ee(r,{expected:ut.joinValues(s),received:r.parsedType,code:ve.invalid_type}),He}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(n.data)){const r=this._getOrReturnCtx(n),s=this._def.values;return Ee(r,{received:r.data,code:ve.invalid_enum_value,options:s}),He}return ra(n.data)}get options(){return this._def.values}get enum(){const n={};for(const r of this._def.values)n[r]=r;return n}get Values(){const n={};for(const r of this._def.values)n[r]=r;return n}get Enum(){const n={};for(const r of this._def.values)n[r]=r;return n}extract(n,r=this._def){return Do.create(n,{...this._def,...r})}exclude(n,r=this._def){return Do.create(this.options.filter(s=>!n.includes(s)),{...this._def,...r})}}Do.create=BS;class ex extends it{_parse(n){const r=ut.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(n);if(s.parsedType!==Te.string&&s.parsedType!==Te.number){const i=ut.objectValues(r);return Ee(s,{expected:ut.joinValues(i),received:s.parsedType,code:ve.invalid_type}),He}if(this._cache||(this._cache=new Set(ut.getValidEnumValues(this._def.values))),!this._cache.has(n.data)){const i=ut.objectValues(r);return Ee(s,{received:s.data,code:ve.invalid_enum_value,options:i}),He}return ra(n.data)}get enum(){return this._def.values}}ex.create=(t,n)=>new ex({values:t,typeName:Ie.ZodNativeEnum,...Ze(n)});class Eu extends it{unwrap(){return this._def.type}_parse(n){const{ctx:r}=this._processInputParams(n);if(r.parsedType!==Te.promise&&r.common.async===!1)return Ee(r,{code:ve.invalid_type,expected:Te.promise,received:r.parsedType}),He;const s=r.parsedType===Te.promise?r.data:Promise.resolve(r.data);return ra(s.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Eu.create=(t,n)=>new Eu({type:t,typeName:Ie.ZodPromise,...Ze(n)});class zo extends it{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:r,ctx:s}=this._processInputParams(n),i=this._def.effect||null,c={addIssue:u=>{Ee(s,u),u.fatal?r.abort():r.dirty()},get path(){return s.path}};if(c.addIssue=c.addIssue.bind(c),i.type==="preprocess"){const u=i.transform(s.data,c);if(s.common.async)return Promise.resolve(u).then(async f=>{if(r.value==="aborted")return He;const g=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});return g.status==="aborted"?He:g.status==="dirty"||r.value==="dirty"?Xi(g.value):g});{if(r.value==="aborted")return He;const f=this._def.schema._parseSync({data:u,path:s.path,parent:s});return f.status==="aborted"?He:f.status==="dirty"||r.value==="dirty"?Xi(f.value):f}}if(i.type==="refinement"){const u=f=>{const g=i.refinement(f,c);if(s.common.async)return Promise.resolve(g);if(g instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){const f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return f.status==="aborted"?He:(f.status==="dirty"&&r.dirty(),u(f.value),{status:r.value,value:f.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(f=>f.status==="aborted"?He:(f.status==="dirty"&&r.dirty(),u(f.value).then(()=>({status:r.value,value:f.value}))))}if(i.type==="transform")if(s.common.async===!1){const u=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Mo(u))return He;const f=i.transform(u.value,c);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(u=>Mo(u)?Promise.resolve(i.transform(u.value,c)).then(f=>({status:r.value,value:f})):He);ut.assertNever(i)}}zo.create=(t,n,r)=>new zo({schema:t,typeName:Ie.ZodEffects,effect:n,...Ze(r)});zo.createWithPreprocess=(t,n,r)=>new zo({schema:n,effect:{type:"preprocess",transform:t},typeName:Ie.ZodEffects,...Ze(r)});class Vr extends it{_parse(n){return this._getType(n)===Te.undefined?ra(void 0):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Vr.create=(t,n)=>new Vr({innerType:t,typeName:Ie.ZodOptional,...Ze(n)});class Lo extends it{_parse(n){return this._getType(n)===Te.null?ra(null):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Lo.create=(t,n)=>new Lo({innerType:t,typeName:Ie.ZodNullable,...Ze(n)});class lh extends it{_parse(n){const{ctx:r}=this._processInputParams(n);let s=r.data;return r.parsedType===Te.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}lh.create=(t,n)=>new lh({innerType:t,typeName:Ie.ZodDefault,defaultValue:typeof n.default=="function"?n.default:()=>n.default,...Ze(n)});class ch extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return bu(i)?i.then(c=>({status:"valid",value:c.status==="valid"?c.value:this._def.catchValue({get error(){return new ir(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ir(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ch.create=(t,n)=>new ch({innerType:t,typeName:Ie.ZodCatch,catchValue:typeof n.catch=="function"?n.catch:()=>n.catch,...Ze(n)});class tx extends it{_parse(n){if(this._getType(n)!==Te.nan){const s=this._getOrReturnCtx(n);return Ee(s,{code:ve.invalid_type,expected:Te.nan,received:s.parsedType}),He}return{status:"valid",value:n.data}}}tx.create=t=>new tx({typeName:Ie.ZodNaN,...Ze(t)});class V3 extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}}class cp extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.common.async)return(async()=>{const c=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?He:c.status==="dirty"?(r.dirty(),Xi(c.value)):this._def.out._parseAsync({data:c.value,path:s.path,parent:s})})();{const i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?He:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(n,r){return new cp({in:n,out:r,typeName:Ie.ZodPipeline})}}class uh extends it{_parse(n){const r=this._def.innerType._parse(n),s=i=>(Mo(i)&&(i.value=Object.freeze(i.value)),i);return bu(r)?r.then(i=>s(i)):s(r)}unwrap(){return this._def.innerType}}uh.create=(t,n)=>new uh({innerType:t,typeName:Ie.ZodReadonly,...Ze(n)});var Ie;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Ie||(Ie={}));const It=Hr.create,Ra=sh.create;Gr.create;const I3=Oa.create,Zo=Vt.create;wu.create;Su.create;Es.create;const q3=ih.create;Do.create;Eu.create;Vr.create;Lo.create;const nx=(t,n,r)=>{if(t&&"reportValidity"in t){const s=Re(r,n);t.setCustomValidity(s&&s.message||""),t.reportValidity()}},dh=(t,n)=>{for(const r in n.fields){const s=n.fields[r];s&&s.ref&&"reportValidity"in s.ref?nx(s.ref,r,t):s&&s.refs&&s.refs.forEach(i=>nx(i,r,t))}},ax=(t,n)=>{n.shouldUseNativeValidation&&dh(t,n);const r={};for(const s in t){const i=Re(n.fields,s),c=Object.assign(t[s]||{},{ref:i&&i.ref});if(F3(n.names||Object.keys(t),s)){const u=Object.assign({},Re(r,s));xt(u,"root",c),xt(r,s,u)}else xt(r,s,c)}return r},F3=(t,n)=>{const r=rx(n);return t.some(s=>rx(s).match(`^${r}\\.\\d+`))};function rx(t){return t.replace(/\]|\[/g,"")}function PS(t,n,r){function s(f,g){var h;Object.defineProperty(f,"_zod",{value:f._zod??{},enumerable:!1}),(h=f._zod).traits??(h.traits=new Set),f._zod.traits.add(t),n(f,g);for(const v in u.prototype)v in f||Object.defineProperty(f,v,{value:u.prototype[v].bind(f)});f._zod.constr=u,f._zod.def=g}const i=(r==null?void 0:r.Parent)??Object;class c extends i{}Object.defineProperty(c,"name",{value:t});function u(f){var g;const h=r!=null&&r.Parent?new c:this;s(h,f),(g=h._zod).deferred??(g.deferred=[]);for(const v of h._zod.deferred)v();return h}return Object.defineProperty(u,"init",{value:s}),Object.defineProperty(u,Symbol.hasInstance,{value:f=>{var g,h;return r!=null&&r.Parent&&f instanceof r.Parent?!0:(h=(g=f==null?void 0:f._zod)==null?void 0:g.traits)==null?void 0:h.has(t)}}),Object.defineProperty(u,"name",{value:t}),u}class $3 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const G3={};function HS(t){return G3}function Y3(t,n){return typeof n=="bigint"?n.toString():n}const VS=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ic(t){return typeof t=="string"?t:t==null?void 0:t.message}function IS(t,n,r){var i,c,u,f,g,h;const s={...t,path:t.path??[]};if(!t.message){const v=Ic((u=(c=(i=t.inst)==null?void 0:i._zod.def)==null?void 0:c.error)==null?void 0:u.call(c,t))??Ic((f=n==null?void 0:n.error)==null?void 0:f.call(n,t))??Ic((g=r.customError)==null?void 0:g.call(r,t))??Ic((h=r.localeError)==null?void 0:h.call(r,t))??"Invalid input";s.message=v}return delete s.inst,delete s.continue,n!=null&&n.reportInput||delete s.input,s}const qS=(t,n)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:n,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(n,Y3,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Z3=PS("$ZodError",qS),FS=PS("$ZodError",qS,{Parent:Error}),X3=t=>(n,r,s,i)=>{const c=s?Object.assign(s,{async:!1}):{async:!1},u=n._zod.run({value:r,issues:[]},c);if(u instanceof Promise)throw new $3;if(u.issues.length){const f=new((i==null?void 0:i.Err)??t)(u.issues.map(g=>IS(g,c,HS())));throw VS(f,i==null?void 0:i.callee),f}return u.value},K3=X3(FS),Q3=t=>async(n,r,s,i)=>{const c=s?Object.assign(s,{async:!0}):{async:!0};let u=n._zod.run({value:r,issues:[]},c);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new((i==null?void 0:i.Err)??t)(u.issues.map(g=>IS(g,c,HS())));throw VS(f,i==null?void 0:i.callee),f}return u.value},W3=Q3(FS);function sx(t,n){try{var r=t()}catch(s){return n(s)}return r&&r.then?r.then(void 0,n):r}function J3(t,n){for(var r={};t.length;){var s=t[0],i=s.code,c=s.message,u=s.path.join(".");if(!r[u])if("unionErrors"in s){var f=s.unionErrors[0].errors[0];r[u]={message:f.message,type:f.code}}else r[u]={message:c,type:i};if("unionErrors"in s&&s.unionErrors.forEach(function(v){return v.errors.forEach(function(y){return t.push(y)})}),n){var g=r[u].types,h=g&&g[s.code];r[u]=np(u,n,r,i,h?[].concat(h,s.message):s.message)}t.shift()}return r}function e5(t,n){for(var r={};t.length;){var s=t[0],i=s.code,c=s.message,u=s.path.join(".");if(!r[u])if(s.code==="invalid_union"&&s.errors.length>0){var f=s.errors[0][0];r[u]={message:f.message,type:f.code}}else r[u]={message:c,type:i};if(s.code==="invalid_union"&&s.errors.forEach(function(v){return v.forEach(function(y){return t.push(y)})}),n){var g=r[u].types,h=g&&g[s.code];r[u]=np(u,n,r,i,h?[].concat(h,s.message):s.message)}t.shift()}return r}function Uo(t,n,r){if(r===void 0&&(r={}),(function(s){return"_def"in s&&typeof s._def=="object"&&"typeName"in s._def})(t))return function(s,i,c){try{return Promise.resolve(sx(function(){return Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](s,n)).then(function(u){return c.shouldUseNativeValidation&&dh({},c),{errors:{},values:r.raw?Object.assign({},s):u}})},function(u){if((function(f){return Array.isArray(f==null?void 0:f.issues)})(u))return{values:{},errors:ax(J3(u.errors,!c.shouldUseNativeValidation&&c.criteriaMode==="all"),c)};throw u}))}catch(u){return Promise.reject(u)}};if((function(s){return"_zod"in s&&typeof s._zod=="object"})(t))return function(s,i,c){try{return Promise.resolve(sx(function(){return Promise.resolve((r.mode==="sync"?K3:W3)(t,s,n)).then(function(u){return c.shouldUseNativeValidation&&dh({},c),{errors:{},values:r.raw?Object.assign({},s):u}})},function(u){if((function(f){return f instanceof Z3})(u))return{values:{},errors:ax(e5(u.issues,!c.shouldUseNativeValidation&&c.criteriaMode==="all"),c)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const t5=()=>{const{login:t,apiUrl:n}=Th(),r=Vo(),[s,i]=b.useState(!1),[c,u]=b.useState(""),f=window.location.origin,g=Zo({apiUrl:It().min(1,{message:"URL da API é obrigatória"}).url({message:`URL inválida. Use o formato: ${f}`}).refine(y=>y.startsWith("http://")||y.startsWith("https://"),{message:"URL deve começar com http:// ou https://"}),apiKey:It().min(1,{message:"API Key é obrigatória"}).min(10,{message:"API Key deve ter pelo menos 10 caracteres"})}),h=Oo({resolver:Uo(g),defaultValues:{apiUrl:n,apiKey:""}}),v=async y=>{i(!0),u("");try{await t(y.apiUrl,y.apiKey),We.success("Conectado com sucesso!",{description:"Você foi conectado ao Evolution GO."}),r("/manager",{replace:!0})}catch(w){console.error("Erro ao fazer login:",w);const N=w instanceof Error?w.message:"Erro ao conectar. Verifique a URL e API Key.";We.error("Credenciais inválidas",{description:N}),u(N)}finally{i(!1)}};return p.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-gradient-to-t from-primary/20 via-background/95 to-background relative",children:p.jsxs("div",{className:"w-full max-w-md space-y-6",children:[p.jsx("div",{className:"text-center",children:p.jsx("h1",{className:"text-3xl font-bold text-primary",children:"Evolution GO"})}),p.jsxs("div",{className:"bg-background/80 backdrop-blur-sm border rounded-lg p-6 shadow-lg",children:[p.jsxs("div",{className:"space-y-2 mb-6",children:[p.jsx("h2",{className:"text-2xl font-bold",children:"Entrar na sua conta"}),p.jsx("p",{className:"text-muted-foreground",children:"Digite suas credenciais para acessar o sistema"})]}),c&&p.jsxs(e3,{variant:"destructive",className:"mb-4",children:[p.jsx(jN,{className:"h-4 w-4"}),p.jsx(t3,{children:"Erro"}),p.jsx(n3,{children:c})]}),p.jsxs("form",{onSubmit:h.handleSubmit(v),className:"space-y-4",children:[p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"login-apiUrl",children:"URL da API Evolution GO"}),p.jsx(Na,{id:"login-apiUrl",type:"text",placeholder:f,disabled:s,...h.register("apiUrl")}),h.formState.errors.apiUrl&&p.jsx("p",{className:"text-destructive text-sm",children:h.formState.errors.apiUrl.message})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"login-apiKey",children:"API Key (GLOBAL_API_KEY)"}),p.jsx(Na,{id:"login-apiKey",type:"password",placeholder:"Sua chave de API",disabled:s,...h.register("apiKey")}),h.formState.errors.apiKey&&p.jsx("p",{className:"text-destructive text-sm",children:h.formState.errors.apiKey.message})]}),p.jsx("div",{className:"text-xs text-muted-foreground",children:p.jsxs("p",{children:[p.jsx("strong",{children:"Dica:"})," A API Key é o valor da variável"," ",p.jsx("code",{className:"relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs",children:"GLOBAL_API_KEY"})," ","configurada no arquivo .env do Evolution GO."]})}),p.jsx(ft,{type:"submit",disabled:s,className:"w-full",children:s?"Conectando...":"Entrar"})]})]}),p.jsx("div",{className:"text-center text-xs text-muted-foreground",children:p.jsxs("p",{children:["Ao continuar, você concorda com nossos"," ",p.jsx("a",{href:"#",className:"underline hover:text-primary",children:"Termos de Serviço"})," ","e"," ",p.jsx("a",{href:"#",className:"underline hover:text-primary",children:"Política de Privacidade"}),"."]})})]})})};function n5(){return p.jsxs("div",{className:"p-6",children:[p.jsx("h1",{className:"mb-4 text-2xl font-bold text-foreground",children:"Dashboard"}),p.jsx("p",{className:"text-muted-foreground",children:"Dashboard content will be implemented here..."})]})}const $S=t=>{const n=t.connected?"open":"close";let r;if(t.qrcode){const s=t.qrcode.split("|");r={base64:s[0]||void 0,code:s[1]||void 0}}return{id:t.id,instanceName:t.name,status:n,apikey:t.token,owner:t.jid?t.jid.split("@")[0]:"",profileName:t.name,connected:t.connected,qrcode:r,webhook:t.webhook||void 0,rabbitmqEnable:t.rabbitmqEnable||void 0,websocketEnable:t.websocketEnable||void 0,natsEnable:t.natsEnable||void 0,events:t.events||void 0,disconnectReason:t.disconnect_reason||void 0,createdAt:t.createdAt,alwaysOnline:t.alwaysOnline,rejectCall:t.rejectCall,readMessages:t.readMessages,ignoreGroups:t.ignoreGroups,ignoreStatus:t.ignoreStatus}},a5=async()=>(await qn.get("/instance/all")).data.data.map($S),qc=async t=>{const n=await qn.get(`/instance/info/${t}`);return $S(n.data.data)},r5=async t=>(await qn.post("/instance/create",t)).data,fh=async(t,n)=>{const r={webhookUrl:(n==null?void 0:n.webhookUrl)||"",subscribe:(n==null?void 0:n.subscribe)||[],rabbitmqEnable:(n==null?void 0:n.rabbitmqEnable)||"",websocketEnable:(n==null?void 0:n.websocketEnable)||"",natsEnable:(n==null?void 0:n.natsEnable)||""};return(await qn.post("/instance/connect",r,{headers:{apikey:t}})).data.data},s5=async(t,n)=>({pairingCode:(await qn.post("/instance/pair",{subscribe:n.subscribe,phone:n.phone},{headers:{apikey:t}})).data.data.PairingCode}),GS=async(t,n,r)=>{await qn.put(`/instance/${t}/advanced-settings`,r,{headers:{apikey:n}})},zm=async t=>{const n=await qn.get("/instance/qr",{headers:{apikey:t}});return{qrcode:n.data.data.Qrcode,code:n.data.data.Code}},YS=async t=>{await qn.delete("/instance/logout",{headers:{apikey:t}})},ZS=async t=>{await qn.delete(`/instance/delete/${t}`)},o5=async(t,n)=>(await qn.post("/send/text",n,{headers:{apikey:t}})).data,XS=Ix()(t=>({instances:[],isLoading:!1,error:null,fetchInstances:async()=>{t({isLoading:!0,error:null});try{const n=await a5();t({instances:n,isLoading:!1})}catch(n){console.error("Failed to fetch instances:",n),t({error:n instanceof Error?n.message:"Erro ao buscar instâncias",isLoading:!1})}},addInstance:n=>{t(r=>({instances:[...r.instances,n]}))},updateInstance:(n,r)=>{t(s=>({instances:s.instances.map(i=>i.instanceName===n?{...i,...r}:i)}))},removeInstance:n=>{t(r=>({instances:r.instances.filter(s=>s.instanceName!==n)}))},setLoading:n=>{t({isLoading:n})},setError:n=>{t({error:n})},clearError:()=>{t({error:null})}})),i5=t=>t==="open"?p.jsx(mu,{className:"bg-green-500/10 text-green-500 hover:bg-green-500/20",children:"Conectado"}):p.jsx(mu,{className:"bg-red-500/10 text-red-500 hover:bg-red-500/20",children:"Desconectado"});function l5({instance:t,isDeleting:n,onSettings:r,onDelete:s,onConnect:i,onDisconnect:c,onSendMessage:u}){const f=t.status==="open";return p.jsx(s3,{className:"group relative bg-sidebar border-sidebar-border hover:bg-sidebar-accent/30 transition-all duration-300 hover:shadow-lg hover:shadow-black/10 overflow-hidden",children:p.jsxs(o3,{className:"p-0",children:[p.jsxs("div",{className:"flex items-center gap-3 p-4 border-b border-sidebar-border",children:[t.profilePicUrl&&p.jsx("div",{className:"flex-shrink-0 dark",children:p.jsx("div",{className:"rounded-lg bg-gray-900 flex items-center justify-center w-14 h-14 overflow-hidden",children:p.jsx("img",{src:t.profilePicUrl,alt:t.profileName||t.instanceName,className:"w-12 h-12 object-cover rounded-lg",onError:g=>{const h=g.target;h.style.display="none"}})})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("h3",{className:"font-semibold text-base truncate text-sidebar-foreground",children:t.profileName||t.instanceName}),p.jsx("p",{className:"text-xs text-sidebar-foreground/60 truncate",children:t.instanceName})]}),p.jsx("div",{className:"flex-shrink-0",children:i5(t.status)})]}),p.jsxs("div",{className:"px-4 py-3 text-xs text-sidebar-foreground/70 space-y-1",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("span",{children:"Status"}),p.jsx("span",{className:"font-mono",children:t.status})]}),t.profileStatus&&p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("span",{children:"Recado"}),p.jsx("span",{className:"font-mono truncate ml-2 max-w-[150px]",children:t.profileStatus})]}),t.owner&&p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("span",{children:"Proprietário"}),p.jsx("span",{className:"font-mono truncate ml-2 max-w-[150px]",children:t.owner})]})]}),p.jsxs("div",{className:"flex border-t border-sidebar-border opacity-0 group-hover:opacity-100 transition-opacity duration-200",children:[!f&&p.jsxs(ft,{variant:"ghost",className:"flex-1 rounded-none h-12 text-green-500 hover:text-green-400 hover:bg-green-500/10",onClick:()=>i(t),children:[p.jsx(Ax,{className:"h-4 w-4 mr-2"}),"Conectar"]}),f&&p.jsxs(ft,{variant:"ghost",className:"flex-1 rounded-none h-12 text-yellow-500 hover:text-yellow-400 hover:bg-yellow-500/10",onClick:()=>c(t),children:[p.jsx(nA,{className:"h-4 w-4 mr-2"}),"Desconectar"]}),p.jsx("div",{className:"w-px bg-sidebar-border"}),f&&u&&p.jsxs(p.Fragment,{children:[p.jsx(ft,{variant:"ghost",className:"rounded-none h-12 px-4 text-blue-500 hover:text-blue-400 hover:bg-blue-500/10",onClick:()=>u(t),children:p.jsx(QN,{className:"h-4 w-4"})}),p.jsx("div",{className:"w-px bg-sidebar-border"})]}),p.jsx(ft,{variant:"ghost",className:"rounded-none h-12 px-4 text-gray-500 hover:text-gray-300 hover:bg-gray-500/10",onClick:()=>r(t),children:p.jsx(uA,{className:"h-4 w-4"})}),p.jsx("div",{className:"w-px bg-sidebar-border"}),p.jsx(ft,{variant:"ghost",className:"rounded-none h-12 px-4 text-red-500 hover:text-red-400 hover:bg-red-500/10",disabled:n===t.instanceName,onClick:()=>s(t),children:p.jsx(Sh,{className:"h-4 w-4"})})]})]})})}function c5({title:t,subtitle:n,searchValue:r,onSearchChange:s,searchPlaceholder:i="Buscar...",primaryAction:c,secondaryActions:u=[],moreActions:f=[],filters:g=[],onFilterClick:h,showFilters:v=!1,selectedCount:y=0,onClearSelection:w,bulkActions:N=[],className:E="",children:S}){const C=y>0,A=u.filter(R=>R.show!==!1),O=f.filter(R=>R.show!==!1);return p.jsxs("div",{className:`space-y-6 ${E} mb-4`,children:[p.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[p.jsxs("div",{className:"flex-1",children:[p.jsx("h1",{className:"text-2xl font-bold tracking-tight text-sidebar-foreground mb-2 dark:text-gray-200",children:t}),n&&p.jsx("p",{className:"text-sm text-sidebar-foreground/70 dark:text-gray-400",children:n})]}),c&&c.show!==!1&&p.jsx("div",{className:"flex-shrink-0",children:p.jsxs(ft,{onClick:c.onClick,variant:c.variant||"default",className:c.className,children:[c.icon&&p.jsx("span",{className:"mr-2",children:c.icon}),c.label]})})]}),p.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[p.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[s&&p.jsxs("div",{className:"relative flex-1 max-w-md",children:[p.jsx(lA,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-sidebar-foreground/60 dark:text-gray-200"}),p.jsx(Na,{type:"search",placeholder:i,value:r,onChange:R=>s(R.target.value),className:"pl-9 bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50 focus:border-sidebar-border dark:text-gray-400 dark:placeholder:text-gray-400"})]}),v&&h&&p.jsxs(ft,{variant:"outline",size:"sm",onClick:h,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent whitespace-nowrap dark:text-gray-400 dark:hover:bg-sidebar-accent",children:[p.jsx(PN,{className:"h-4 w-4 mr-2"}),"Filtros",g.length>0&&p.jsx(mu,{variant:"secondary",className:"ml-2 h-5 px-1.5 text-xs bg-sidebar-accent",children:g.length})]})]}),p.jsxs("div",{className:"flex items-center gap-2",children:[A.map((R,L)=>p.jsxs(ft,{variant:R.variant||"outline",size:"sm",onClick:R.onClick,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:[R.icon&&p.jsx("span",{className:"mr-2",children:R.icon}),R.label]},L)),O.length>0&&p.jsxs(c3,{children:[p.jsx(u3,{asChild:!0,children:p.jsx(ft,{variant:"outline",size:"sm",className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:p.jsx(MN,{className:"h-4 w-4"})})}),p.jsx(d3,{align:"end",className:"bg-sidebar border-sidebar-border text-sidebar-foreground dark:text-gray-400",children:O.map((R,L)=>p.jsxs(f3,{onClick:R.onClick,className:`hover:bg-sidebar-accent ${R.variant==="destructive"?"text-red-400":""} dark:text-gray-400`,children:[R.icon&&p.jsx("span",{className:"mr-2",children:R.icon}),R.label]},L))})]})]})]}),C&&p.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-sidebar-accent/50 border border-sidebar-border px-4 py-2",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsxs("span",{className:"text-sm font-medium text-sidebar-foreground dark:text-gray-400",children:[y," selecionado",y>1?"s":""]}),w&&p.jsxs(ft,{variant:"ghost",size:"sm",onClick:w,className:"h-7 px-2 text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:text-gray-400 dark:hover:bg-sidebar-accent",children:[p.jsx(Ji,{className:"h-3 w-3 mr-1"}),"Limpar"]})]}),N.length>0&&p.jsx("div",{className:"flex items-center gap-2",children:N.map((R,L)=>p.jsxs(ft,{variant:R.variant||"outline",size:"sm",onClick:R.onClick,className:"h-7 bg-sidebar-accent border-sidebar-border text-sidebar-foreground hover:bg-sidebar dark:text-gray-400 dark:hover:bg-sidebar",children:[R.icon&&p.jsx("span",{className:"mr-1.5",children:R.icon}),R.label]},L))})]}),g.length>0&&p.jsx("div",{className:"flex flex-wrap gap-2",children:g.map((R,L)=>p.jsxs(mu,{variant:"secondary",className:"pl-2 pr-1 py-1 bg-sidebar-accent text-sidebar-foreground hover:bg-sidebar dark:text-gray-400 dark:hover:bg-sidebar dark:bg-sidebar-accent/50",children:[R.label,": ",R.value,p.jsx(ft,{variant:"ghost",size:"sm",onClick:R.onRemove,className:"ml-1 h-4 w-4 p-0 hover:bg-transparent text-sidebar-foreground/60 hover:text-sidebar-foreground dark:text-gray-400 dark:hover:text-gray-400",children:p.jsx(Ji,{className:"h-3 w-3"})})]},L))}),S]})}function u5({totalCount:t,selectedCount:n,searchValue:r,onSearchChange:s,onNewInstance:i,onClearSelection:c}){const u={label:"Nova Instância",icon:p.jsx(Vm,{className:"h-4 w-4"}),onClick:i};return p.jsx(c5,{title:"Instâncias",subtitle:"Gerencie suas instâncias WhatsApp do Evolution GO",totalCount:t,selectedCount:n,searchValue:r,onSearchChange:s,searchPlaceholder:"Buscar instâncias...",primaryAction:u,onClearSelection:c,showFilters:!1,className:"mb-4"})}const sn=[];for(let t=0;t<256;++t)sn.push((t+256).toString(16).slice(1));function d5(t,n=0){return(sn[t[n+0]]+sn[t[n+1]]+sn[t[n+2]]+sn[t[n+3]]+"-"+sn[t[n+4]]+sn[t[n+5]]+"-"+sn[t[n+6]]+sn[t[n+7]]+"-"+sn[t[n+8]]+sn[t[n+9]]+"-"+sn[t[n+10]]+sn[t[n+11]]+sn[t[n+12]]+sn[t[n+13]]+sn[t[n+14]]+sn[t[n+15]]).toLowerCase()}let Lm;const f5=new Uint8Array(16);function m5(){if(!Lm){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Lm=crypto.getRandomValues.bind(crypto)}return Lm(f5)}const h5=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ox={randomUUID:h5};function p5(t,n,r){var i;if(ox.randomUUID&&!t)return ox.randomUUID();t=t||{};const s=t.random??((i=t.rng)==null?void 0:i.call(t))??m5();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,d5(s)}const g5=Zo({instanceName:It().min(1,"Nome da instância é obrigatório").min(3,"Nome deve ter pelo menos 3 caracteres").max(50,"Nome deve ter no máximo 50 caracteres").regex(/^[a-zA-Z0-9-_]+$/,"Nome deve conter apenas letras, números, hífen e underscore"),token:It().optional(),proxyHost:It().optional(),proxyPort:It().optional(),proxyUsername:It().optional(),proxyPassword:It().optional()});function y5({open:t,onOpenChange:n}){const[r,s]=b.useState(!1),[i,c]=b.useState(!1),{addInstance:u,fetchInstances:f}=XS(),{register:g,handleSubmit:h,reset:v,formState:{errors:y}}=Oo({resolver:Uo(g5),defaultValues:{instanceName:"",token:"",proxyHost:"",proxyPort:"",proxyUsername:"",proxyPassword:""}}),w=async E=>{s(!0);try{const S={name:E.instanceName,token:E.token||p5()};E.proxyHost&&E.proxyPort&&(S.proxy={host:E.proxyHost,port:E.proxyPort,username:E.proxyUsername,password:E.proxyPassword});const C=await r5(S);u(C),We.success("Instância criada com sucesso!",{description:`A instância "${E.instanceName}" foi criada.`}),await f(),n(!1),v()}catch(S){console.error("Erro ao criar instância:",S),We.error(S instanceof Error?S.message:"Erro ao criar instância. Tente novamente.")}finally{s(!1)}},N=()=>{r||(n(!1),v(),c(!1))};return p.jsx(hu,{open:t,onOpenChange:N,children:p.jsxs(pu,{className:"sm:max-w-md",children:[p.jsxs(gu,{children:[p.jsxs(yu,{className:"flex items-center gap-2",children:[p.jsx(Vm,{className:"h-5 w-5 text-primary"}),"Nova Instância"]}),p.jsx(vu,{className:"text-sidebar-foreground/70",children:"Crie uma nova instância WhatsApp para gerenciar suas conversas"})]}),p.jsxs("form",{onSubmit:h(w),className:"space-y-4",children:[p.jsxs("div",{className:"space-y-2",children:[p.jsxs(Ur,{htmlFor:"instanceName",children:["Nome da Instância ",p.jsx("span",{className:"text-red-500",children:"*"})]}),p.jsx(Na,{id:"instanceName",type:"text",placeholder:"ex: minha-instancia",disabled:r,...g("instanceName"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.instanceName&&p.jsx("p",{className:"text-destructive text-sm",children:y.instanceName.message}),p.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Use apenas letras, números, hífen (-) e underscore (_)"})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"token",children:"Token (Opcional)"}),p.jsx(Na,{id:"token",type:"text",placeholder:"Token personalizado (UUID)",disabled:r,...g("token"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.token&&p.jsx("p",{className:"text-destructive text-sm",children:y.token.message}),p.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Se não informado, será gerado um UUID automaticamente"})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsxs(ft,{type:"button",variant:"outline",onClick:()=>c(!i),disabled:r,className:"w-full justify-between bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:[p.jsx("span",{children:"Configuração de Proxy (Opcional)"}),i?p.jsx(RN,{className:"h-4 w-4"}):p.jsx(Hm,{className:"h-4 w-4"})]}),i&&p.jsxs("div",{className:"space-y-4 pt-2 border-t border-sidebar-border",children:[p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"proxyHost",children:"Host do Proxy"}),p.jsx(Na,{id:"proxyHost",type:"text",placeholder:"ex: proxy.example.com",disabled:r,...g("proxyHost"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.proxyHost&&p.jsx("p",{className:"text-destructive text-sm",children:y.proxyHost.message})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"proxyPort",children:"Porta do Proxy"}),p.jsx(Na,{id:"proxyPort",type:"text",placeholder:"ex: 8080",disabled:r,...g("proxyPort"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.proxyPort&&p.jsx("p",{className:"text-destructive text-sm",children:y.proxyPort.message})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"proxyUsername",children:"Usuário (Opcional)"}),p.jsx(Na,{id:"proxyUsername",type:"text",placeholder:"Usuário do proxy",disabled:r,...g("proxyUsername"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.proxyUsername&&p.jsx("p",{className:"text-destructive text-sm",children:y.proxyUsername.message})]}),p.jsxs("div",{className:"space-y-2",children:[p.jsx(Ur,{htmlFor:"proxyPassword",children:"Senha (Opcional)"}),p.jsx(Na,{id:"proxyPassword",type:"password",placeholder:"Senha do proxy",disabled:r,...g("proxyPassword"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),y.proxyPassword&&p.jsx("p",{className:"text-destructive text-sm",children:y.proxyPassword.message})]})]})]}),p.jsxs(zS,{className:"flex gap-2 sm:gap-0",children:[p.jsx(ft,{type:"button",variant:"outline",onClick:N,disabled:r,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:"Cancelar"}),p.jsx(ft,{type:"submit",disabled:r,children:r?p.jsxs(p.Fragment,{children:[p.jsx(YN,{className:"mr-2 h-4 w-4 animate-spin"}),"Criando..."]}):p.jsxs(p.Fragment,{children:[p.jsx(Vm,{className:"mr-2 h-4 w-4"}),"Criar Instância"]})})]})]})]})})}function v5({instance:t,open:n,onOpenChange:r,onRefresh:s}){var f,g;const[i,c]=b.useState(!1);b.useEffect(()=>{if(!n||!t||t.connected)return;const h=setInterval(()=>{s&&(console.log("Auto-refreshing QR Code and checking connection..."),s().catch(v=>{console.error("Auto-refresh failed:",v)}))},1e4);return()=>clearInterval(h)},[n,t,s]);const u=async()=>{if(s){c(!0);try{await s(),We.success("QR Code atualizado!")}catch(h){console.error("Erro ao atualizar QR Code:",h),We.error("Erro ao atualizar QR Code")}finally{c(!1)}}};return t?t.connected?p.jsx(hu,{open:n,onOpenChange:r,children:p.jsxs(pu,{className:"sm:max-w-md",children:[p.jsxs(gu,{children:[p.jsxs(yu,{className:"flex items-center gap-2 text-green-500",children:[p.jsx(Sb,{className:"h-5 w-5"}),"Conectado com Sucesso!"]}),p.jsxs(vu,{className:"text-sidebar-foreground/70",children:["A instância ",t.instanceName," foi conectada ao WhatsApp."]})]}),p.jsxs("div",{className:"flex flex-col items-center gap-4 py-6",children:[p.jsx("div",{className:"rounded-full bg-green-500/10 p-4",children:p.jsx(Sb,{className:"h-12 w-12 text-green-500"})}),t.profileName&&p.jsxs("div",{className:"text-center",children:[p.jsx("p",{className:"text-sm text-sidebar-foreground/60",children:"Conectado como"}),p.jsx("p",{className:"text-lg font-semibold text-sidebar-foreground",children:t.profileName})]})]}),p.jsx("div",{className:"flex justify-end",children:p.jsx(ft,{onClick:()=>r(!1),className:"w-full sm:w-auto",children:"Fechar"})})]})}):p.jsx(hu,{open:n,onOpenChange:r,children:p.jsxs(pu,{className:"sm:max-w-md",children:[p.jsxs(gu,{children:[p.jsxs(yu,{className:"flex items-center gap-2",children:[p.jsx(Eb,{className:"h-5 w-5 text-primary"}),"Conectar WhatsApp"]}),p.jsxs(vu,{className:"text-sidebar-foreground/70",children:["Escaneie o QR Code abaixo com seu WhatsApp para conectar a instância"," ",p.jsx("strong",{children:t.instanceName})]})]}),p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"flex flex-col items-center gap-4",children:[(f=t.qrcode)!=null&&f.base64?p.jsx("div",{className:"rounded-lg border-2 border-sidebar-border bg-white p-4",children:p.jsx("img",{src:t.qrcode.base64,alt:"QR Code",className:"h-64 w-64"})}):p.jsx("div",{className:"flex h-64 w-64 items-center justify-center rounded-lg border-2 border-dashed border-sidebar-border bg-sidebar",children:p.jsxs("div",{className:"text-center",children:[p.jsx(Eb,{className:"mx-auto h-12 w-12 text-sidebar-foreground/40"}),p.jsx("p",{className:"mt-2 text-sm text-sidebar-foreground/60",children:"Aguardando QR Code..."})]})}),((g=t.qrcode)==null?void 0:g.pairingCode)&&p.jsxs("div",{className:"w-full rounded-lg bg-sidebar-accent p-3 text-center",children:[p.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Código de Pareamento"}),p.jsx("p",{className:"mt-1 font-mono text-lg font-semibold text-sidebar-foreground",children:t.qrcode.pairingCode})]})]}),p.jsxs("div",{className:"rounded-lg bg-sidebar-accent p-4",children:[p.jsx("p",{className:"text-sm font-medium text-sidebar-foreground",children:"Como conectar:"}),p.jsxs("ol",{className:"mt-2 space-y-1 text-sm text-sidebar-foreground/70",children:[p.jsx("li",{children:"1. Abra o WhatsApp no seu celular"}),p.jsx("li",{children:"2. Toque em Menu ou Configurações"}),p.jsx("li",{children:"3. Toque em Dispositivos conectados"}),p.jsx("li",{children:"4. Toque em Conectar um dispositivo"}),p.jsx("li",{children:"5. Aponte seu celular para esta tela para capturar o código"})]})]}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx(ft,{variant:"outline",onClick:u,disabled:i,className:"flex-1 bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:i?p.jsxs(p.Fragment,{children:[p.jsx(_b,{className:"mr-2 h-4 w-4 animate-spin"}),"Atualizando..."]}):p.jsxs(p.Fragment,{children:[p.jsx(_b,{className:"mr-2 h-4 w-4"}),"Atualizar QR Code"]})}),p.jsx(ft,{variant:"outline",onClick:()=>r(!1),className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:p.jsx(Ji,{className:"h-4 w-4"})})]})]})]})}):null}const b5=Zo({webhookUrl:It().optional(),phone:It().optional(),rabbitmqEnable:It().optional(),websocketEnable:It().optional(),natsEnable:It().optional(),alwaysOnline:Ra().optional(),rejectCall:Ra().optional(),readMessages:Ra().optional(),ignoreGroups:Ra().optional(),ignoreStatus:Ra().optional()}),x5=["ALL","MESSAGE","READ_RECEIPT","PRESENCE","HISTORY_SYNC","CHAT_PRESENCE","CALL","CONNECTION","QRCODE","LABEL","CONTACT","GROUP","NEWSLETTER"];function w5({open:t,onClose:n,instance:r,onConfirm:s}){const[i,c]=b.useState([]),[u,f]=b.useState(!1),[g,h]=b.useState(!1),{register:v,handleSubmit:y,formState:{errors:w},reset:N}=Oo({resolver:Uo(b5)}),E=async R=>{const L={webhookUrl:R.webhookUrl||"",subscribe:i,phone:R.phone||"",rabbitmqEnable:R.rabbitmqEnable||"",websocketEnable:R.websocketEnable||"",natsEnable:R.natsEnable||"",alwaysOnline:R.alwaysOnline,rejectCall:R.rejectCall,readMessages:R.readMessages,ignoreGroups:R.ignoreGroups,ignoreStatus:R.ignoreStatus};s(L),S()},S=()=>{N(),c([]),f(!1),h(!1),n()},C=R=>{c(L=>R==="ALL"?L.includes("ALL")?[]:["ALL"]:L.includes("ALL")?[R]:L.includes(R)?L.filter(I=>I!==R):[...L,R])},A=()=>{c(["ALL"])},O=()=>{c([])};return!t||!r?null:p.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:p.jsxs("div",{className:"w-full max-w-2xl rounded-lg bg-card p-6 shadow-lg max-h-[90vh] overflow-y-auto",children:[p.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[p.jsxs("h2",{className:"text-xl font-semibold text-foreground",children:["Configurar Conexão - ",r.instanceName]}),p.jsx("button",{onClick:S,className:"rounded-md p-1 hover:bg-accent",children:p.jsx(Ji,{className:"h-5 w-5"})})]}),p.jsxs("form",{onSubmit:y(E),className:"space-y-4",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"webhookUrl",className:"mb-1 block text-sm font-medium text-foreground",children:"Webhook URL (opcional)"}),p.jsx("input",{id:"webhookUrl",type:"url",placeholder:"https://seu-servidor.com/webhook",...v("webhookUrl"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),w.webhookUrl&&p.jsx("p",{className:"mt-1 text-sm text-destructive",children:w.webhookUrl.message})]}),p.jsxs("div",{children:[p.jsxs("button",{type:"button",onClick:()=>h(!g),className:"flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary",children:[g?p.jsx(Hm,{className:"h-4 w-4"}):p.jsx(wb,{className:"h-4 w-4"}),"Eventos para Webhook (",i.length," selecionados)"]}),g&&p.jsxs("div",{className:"mt-2 space-y-2 rounded-md border border-input p-3",children:[p.jsxs("div",{className:"flex gap-2 mb-2",children:[p.jsx("button",{type:"button",onClick:A,className:"text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90",children:"Selecionar ALL"}),p.jsx("button",{type:"button",onClick:O,className:"text-xs px-2 py-1 rounded border border-input hover:bg-accent",children:"Limpar"})]}),p.jsx("div",{className:"mb-3 p-3 rounded-md bg-primary/10 border border-primary/20",children:p.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[p.jsx("input",{type:"checkbox",checked:i.includes("ALL"),onChange:()=>C("ALL"),className:"rounded border-input w-4 h-4"}),p.jsxs("div",{className:"flex-1",children:[p.jsx("span",{className:"text-sm font-semibold text-primary",children:"ALL"}),p.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Seleciona todos os eventos (recomendado)"})]})]})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Eventos Individuais:"}),p.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-48 overflow-y-auto",children:x5.filter(R=>R!=="ALL").map(R=>p.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer hover:bg-accent p-2 rounded",children:[p.jsx("input",{type:"checkbox",checked:i.includes(R)||i.includes("ALL"),onChange:()=>C(R),disabled:i.includes("ALL"),className:"rounded border-input"}),p.jsx("span",{className:i.includes("ALL")?"text-muted-foreground":"text-foreground",children:R})]},R))})]})]})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"phone",className:"mb-1 block text-sm font-medium text-foreground",children:"Telefone para Pairing Code (opcional)"}),p.jsx("input",{id:"phone",type:"tel",placeholder:"5511999999999",...v("phone"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),p.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Se fornecido, será gerado um código de pareamento (pairing code)"})]}),p.jsxs("div",{children:[p.jsxs("button",{type:"button",onClick:()=>f(!u),className:"flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary",children:[u?p.jsx(Hm,{className:"h-4 w-4"}):p.jsx(wb,{className:"h-4 w-4"}),"Configurações Avançadas"]}),u&&p.jsxs("div",{className:"mt-2 space-y-4 rounded-md border border-input p-4",children:[p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Comportamento"}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"alwaysOnline",className:"text-sm font-medium text-foreground cursor-pointer",children:"Always Online"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Manter sempre online no WhatsApp"})]}),p.jsx("input",{id:"alwaysOnline",type:"checkbox",...v("alwaysOnline"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"rejectCall",className:"text-sm font-medium text-foreground cursor-pointer",children:"Reject Call"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Rejeitar chamadas automaticamente"})]}),p.jsx("input",{id:"rejectCall",type:"checkbox",...v("rejectCall"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"readMessages",className:"text-sm font-medium text-foreground cursor-pointer",children:"Read Messages"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Marcar mensagens como lidas"})]}),p.jsx("input",{id:"readMessages",type:"checkbox",...v("readMessages"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"ignoreGroups",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Groups"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar mensagens de grupos"})]}),p.jsx("input",{id:"ignoreGroups",type:"checkbox",...v("ignoreGroups"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"ignoreStatus",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Status"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar atualizações de status"})]}),p.jsx("input",{id:"ignoreStatus",type:"checkbox",...v("ignoreStatus"),className:"rounded border-input w-4 h-4"})]})]}),p.jsxs("div",{className:"space-y-3 pt-3 border-t border-input",children:[p.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Produtores de Eventos"}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"rabbitmqEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"RabbitMQ"}),p.jsxs("select",{id:"rabbitmqEnable",...v("rabbitmqEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"websocketEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"WebSocket"}),p.jsxs("select",{id:"websocketEnable",...v("websocketEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"natsEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"NATS"}),p.jsxs("select",{id:"natsEnable",...v("natsEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]})]})]})]}),p.jsxs("div",{className:"flex gap-2 pt-4",children:[p.jsx("button",{type:"button",onClick:S,className:"flex-1 rounded-md border border-input px-4 py-2 text-sm font-medium text-foreground hover:bg-accent",children:"Cancelar"}),p.jsx("button",{type:"submit",className:"flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",children:"Conectar"})]})]})]})})}const S5=Zo({number:It().min(1,"Número é obrigatório"),message:It().min(1,"Mensagem é obrigatória")});function E5({open:t,onClose:n,instance:r}){const{register:s,handleSubmit:i,formState:{errors:c,isSubmitting:u},reset:f}=Oo({resolver:Uo(S5)}),g=async v=>{if(!(r!=null&&r.apikey)){We.error("Token da instância não encontrado");return}try{await o5(r.apikey,{number:v.number,text:v.message}),We.success("Mensagem enviada com sucesso!"),f(),n()}catch(y){console.error("Send message error:",y),We.error("Erro ao enviar mensagem")}},h=()=>{f(),n()};return!t||!r?null:p.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:p.jsxs("div",{className:"w-full max-w-md rounded-lg bg-card p-6 shadow-lg",children:[p.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[p.jsxs("h2",{className:"text-xl font-semibold text-foreground",children:["Enviar Mensagem - ",r.instanceName]}),p.jsx("button",{onClick:h,className:"rounded-md p-1 hover:bg-accent",children:p.jsx(Ji,{className:"h-5 w-5"})})]}),p.jsxs("form",{onSubmit:i(g),className:"space-y-4",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"number",className:"mb-1 block text-sm font-medium text-foreground",children:"Número (com DDI)"}),p.jsx("input",{id:"number",type:"text",placeholder:"5511999999999",...s("number"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),c.number&&p.jsx("p",{className:"mt-1 text-sm text-destructive",children:c.number.message})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"message",className:"mb-1 block text-sm font-medium text-foreground",children:"Mensagem"}),p.jsx("textarea",{id:"message",rows:4,placeholder:"Digite sua mensagem...",...s("message"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),c.message&&p.jsx("p",{className:"mt-1 text-sm text-destructive",children:c.message.message})]}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button",onClick:h,disabled:u,className:"flex-1 rounded-md border border-input px-4 py-2 text-sm font-medium text-foreground hover:bg-accent disabled:opacity-50",children:"Cancelar"}),p.jsx("button",{type:"submit",disabled:u,className:"flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:u?"Enviando...":"Enviar"})]})]})]})})}function _5({icon:t,title:n,description:r,action:s,className:i}){return p.jsxs("div",{className:qm("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[p.jsx("div",{className:"rounded-full bg-sidebar-accent/50 p-6 mb-4 dark:bg-sidebar-accent/50 dark:text-gray-400",children:p.jsx(t,{className:"h-12 w-12 text-sidebar-foreground/60 dark:text-gray-400"})}),p.jsx("h3",{className:"text-lg font-semibold text-sidebar-foreground mb-2 dark:text-gray-400",children:n}),p.jsx("p",{className:"text-sm text-sidebar-foreground/60 mb-6 max-w-md dark:text-gray-400",children:r}),s&&p.jsx(ft,{onClick:s.onClick,children:s.label})]})}function C5(){var D,V,te,fe,oe;const t=Vo(),{instances:n,isLoading:r,fetchInstances:s,removeInstance:i}=XS(),[c,u]=b.useState(""),[f,g]=b.useState(!1),[h,v]=b.useState({isOpen:!1,instance:null}),[y]=b.useState(1),[w]=b.useState(24),[N,E]=b.useState(null),[S,C]=b.useState({isOpen:!1,instance:null,confirmationText:""}),[A,O]=b.useState({isOpen:!1,instance:null}),[R,L]=b.useState({isOpen:!1,instance:null}),I=b.useRef(!1);b.useEffect(()=>{I.current||(s(),I.current=!0);const K=setInterval(()=>{s()},5e3);return()=>clearInterval(K)},[s]);const{paginatedInstances:ee,totalCount:U}=b.useMemo(()=>{const K=c?n.filter(De=>{var xe,je,at;const Le=c.toLowerCase();return((xe=De.instanceName)==null?void 0:xe.toLowerCase().includes(Le))||((je=De.profileName)==null?void 0:je.toLowerCase().includes(Le))||((at=De.owner)==null?void 0:at.toLowerCase().includes(Le))}):n,de=(y-1)*w,_e=de+w;return{paginatedInstances:K.slice(de,_e),totalCount:K.length}},[n,c,y,w]),Q=b.useCallback(()=>{g(!0)},[]),le=b.useCallback(K=>{t(`/manager/instances/${K.id}/settings`)},[t]),ue=b.useCallback(K=>{L({isOpen:!0,instance:K})},[]),me=b.useCallback(async(K,de)=>{try{if(!K.apikey){We.error("Token da instância não encontrado");return}if(We.info(`Conectando ${K.instanceName}...`),de.alwaysOnline!==void 0||de.rejectCall!==void 0||de.readMessages!==void 0||de.ignoreGroups!==void 0||de.ignoreStatus!==void 0){const De={alwaysOnline:de.alwaysOnline,rejectCall:de.rejectCall,readMessages:de.readMessages,ignoreGroups:de.ignoreGroups,ignoreStatus:de.ignoreStatus};await GS(K.id,K.apikey,De)}if(de.phone&&de.phone.trim()!==""){let De=de.phone.trim();De.startsWith("+")||(De=`+${De}`),await fh(K.apikey,{...de,phone:void 0}),await new Promise(xe=>setTimeout(xe,1e3));const Le=await s5(K.apikey,{subscribe:de.subscribe||[],phone:De});try{const xe=await zm(K.apikey),je={...K,qrcode:{base64:xe.qrcode,code:xe.code,pairingCode:Le.pairingCode}};v({isOpen:!0,instance:je}),We.success(`QR Code e Pairing Code gerados para ${K.instanceName}!`)}catch{const xe={...K,qrcode:{pairingCode:Le.pairingCode}};v({isOpen:!0,instance:xe}),We.success(`Pairing Code gerado para ${K.instanceName}!`)}}else{await fh(K.apikey,de),await new Promise(De=>setTimeout(De,2e3));try{const De=await zm(K.apikey),Le={...K,qrcode:{base64:De.qrcode,code:De.code}};v({isOpen:!0,instance:Le}),We.success(`QR Code gerado para ${K.instanceName}!`)}catch(De){console.error("Erro ao buscar QR Code:",De),We.error("QR Code ainda não disponível, aguarde alguns segundos..."),await s();const Le=n.find(xe=>xe.instanceName===K.instanceName);Le&&v({isOpen:!0,instance:Le})}}}catch(_e){console.error("Erro ao conectar instância:",_e),We.error(_e instanceof Error?_e.message:"Erro ao conectar instância")}},[s,n]),re=b.useCallback(async K=>{try{if(!K.apikey){We.error("Token da instância não encontrado");return}We.info(`Desconectando ${K.instanceName}...`),await YS(K.apikey),await s(),We.success(`${K.instanceName} desconectada!`)}catch(de){console.error("Erro ao desconectar instância:",de),We.error(de instanceof Error?de.message:"Erro ao desconectar instância")}},[s]),X=K=>{C({isOpen:!0,instance:K,confirmationText:""})},he=()=>{C({isOpen:!1,instance:null,confirmationText:""})},be=()=>{v({isOpen:!1,instance:null})},j=K=>{O({isOpen:!0,instance:K})},Z=()=>{O({isOpen:!1,instance:null})},P=()=>{L({isOpen:!1,instance:null})},se=b.useCallback(K=>{R.instance&&me(R.instance,K)},[R.instance,me]),we=b.useCallback(async()=>{if(!(!h.instance||!h.instance.apikey))try{await s();const K=n.find(de=>{var _e;return de.id===((_e=h.instance)==null?void 0:_e.id)});if(!K)return;if(K.connected){v({isOpen:!0,instance:K});return}try{const de=await zm(h.instance.apikey),_e={...K,qrcode:{base64:de.qrcode,code:de.code}};v({isOpen:!0,instance:_e})}catch{v({isOpen:!0,instance:K})}}catch(K){throw console.error("Erro ao atualizar QR Code:",K),K}},[h.instance,s,n]),T=async()=>{if(!S.instance)return;const K=S.instance.instanceName,de=S.instance.id;E(K);try{await ZS(de),i(K),We.success(`Instância ${K} removida com sucesso!`),he()}catch(_e){console.error("Erro ao remover instância:",_e),We.error((_e==null?void 0:_e.message)||"Erro ao remover instância"),await s()}finally{E(null)}},Y=S.confirmationText===((D=S.instance)==null?void 0:D.instanceName);return p.jsxs("div",{className:"h-full flex flex-col p-4",children:[p.jsx(u5,{totalCount:U,selectedCount:0,searchValue:c,onSearchChange:u,onNewInstance:Q,onClearSelection:()=>{}}),p.jsx("div",{className:"flex-1 overflow-auto",children:r?p.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((K,de)=>p.jsx(h3,{className:"h-48"},de))}):U===0?p.jsx(_5,{icon:qN,title:"Nenhuma instância encontrada",description:"Crie sua primeira instância para começar a usar o Evolution GO",action:{label:"Nova Instância",onClick:Q},className:"h-full"}):p.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:ee.map(K=>p.jsx(l5,{instance:K,isDeleting:N,onSettings:le,onDelete:X,onConnect:ue,onDisconnect:re,onSendMessage:j},K.instanceName))})}),p.jsx(y5,{open:f,onOpenChange:g}),p.jsx(v5,{instance:h.instance,open:h.isOpen,onOpenChange:be,onRefresh:we}),p.jsx(w5,{instance:R.instance,open:R.isOpen,onClose:P,onConfirm:se}),p.jsx(E5,{instance:A.instance,open:A.isOpen,onClose:Z}),p.jsx(hu,{open:S.isOpen,onOpenChange:he,children:p.jsxs(pu,{className:"sm:max-w-md",children:[p.jsxs(gu,{children:[p.jsxs(yu,{className:"flex items-center gap-2 text-red-400 dark:text-red-500",children:[p.jsx(Sh,{className:"h-5 w-5"}),"Remover Instância"]}),p.jsxs(vu,{className:"text-sidebar-foreground/70 dark:text-gray-400",children:["Você está prestes a remover a instância"," ",p.jsx("strong",{children:(V=S.instance)==null?void 0:V.instanceName}),". Esta ação não pode ser desfeita."]})]}),p.jsx("div",{className:"space-y-4",children:p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-sidebar-foreground dark:text-gray-400",children:"Digite o nome da instância para confirmar:"}),p.jsx(Na,{placeholder:((te=S.instance)==null?void 0:te.instanceName)||"",value:S.confirmationText,onChange:K=>C(de=>({...de,confirmationText:K.target.value})),className:"mt-2 bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50 dark:text-gray-400 dark:placeholder:text-gray-400"})]})}),p.jsxs(zS,{className:"flex gap-2",children:[p.jsx(ft,{variant:"outline",onClick:he,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:"Cancelar"}),p.jsx(ft,{variant:"destructive",onClick:T,disabled:!Y||N===((fe=S.instance)==null?void 0:fe.instanceName),className:"bg-red-600 hover:bg-red-700 text-white dark:bg-red-600 dark:hover:bg-red-700",children:N===((oe=S.instance)==null?void 0:oe.instanceName)?"Removendo...":"Remover Instância"})]})]})})]})}const N5=Zo({webhookUrl:It().url("URL inválida").optional().or(q3("")),subscribe:I3(It()).optional(),rabbitmqEnable:It().optional(),websocketEnable:It().optional(),natsEnable:It().optional()}),A5=Zo({alwaysOnline:Ra().optional(),rejectCall:Ra().optional(),readMessages:Ra().optional(),ignoreGroups:Ra().optional(),ignoreStatus:Ra().optional()}),R5=["ALL","MESSAGE","READ_RECEIPT","PRESENCE","HISTORY_SYNC","CHAT_PRESENCE","CALL","CONNECTION","QRCODE","LABEL","CONTACT","GROUP","NEWSLETTER"];function T5(){const{instanceId:t}=KC(),n=Vo(),[r,s]=b.useState(null),[i,c]=b.useState([]),[u,f]=b.useState(!1),[g,h]=b.useState(!0),[v,y]=b.useState(!1),w=b.useRef(!1),N=b.useRef(!1),{register:E,handleSubmit:S,formState:{errors:C},reset:A}=Oo({resolver:Uo(N5)}),{register:O,handleSubmit:R,reset:L}=Oo({resolver:Uo(A5)});b.useEffect(()=>{(async()=>{if(!(!t||N.current)){N.current=!0;try{h(!0);const me=await qc(t);s(me)}catch(me){console.error("Erro ao buscar instância:",me),We.error("Erro ao carregar dados da instância")}finally{h(!1)}}})()},[t]),b.useEffect(()=>{if(!(!r||w.current)){if(A({webhookUrl:r.webhook||"",rabbitmqEnable:r.rabbitmqEnable||"",websocketEnable:r.websocketEnable||"",natsEnable:r.natsEnable||""}),L({alwaysOnline:r.alwaysOnline||!1,rejectCall:r.rejectCall||!1,readMessages:r.readMessages||!1,ignoreGroups:r.ignoreGroups||!1,ignoreStatus:r.ignoreStatus||!1}),r.events){const ue=r.events.split(",").map(me=>me.trim()).filter(Boolean);c(ue)}else c([]);w.current=!0}},[r,A,L]);const I=ue=>{c(me=>ue==="ALL"?me.includes("ALL")?[]:["ALL"]:me.includes("ALL")?[ue]:me.includes(ue)?me.filter(re=>re!==ue):[...me,ue])},ee=async ue=>{if(!(r!=null&&r.apikey)||!t){We.error("Token da instância não encontrado");return}try{f(!0);const me={webhookUrl:ue.webhookUrl||"",subscribe:i,rabbitmqEnable:ue.rabbitmqEnable||"",websocketEnable:ue.websocketEnable||"",natsEnable:ue.natsEnable||""};await fh(r.apikey,me),We.success("Configurações de webhook atualizadas!");const re=await qc(t);s(re)}catch(me){console.error("Erro ao atualizar webhook:",me),We.error(me instanceof Error?me.message:"Erro ao atualizar webhook")}finally{f(!1)}},U=async ue=>{if(!(r!=null&&r.apikey)||!(r!=null&&r.id)||!t){We.error("Token da instância não encontrado");return}try{f(!0),await GS(r.id,r.apikey,ue),We.success("Configurações avançadas atualizadas!");const me=await qc(t);s(me)}catch(me){console.error("Erro ao atualizar configurações:",me),We.error(me instanceof Error?me.message:"Erro ao atualizar configurações")}finally{f(!1)}},Q=async()=>{if(!(r!=null&&r.apikey)||!t){We.error("Token da instância não encontrado");return}try{We.info(`Desconectando ${r.instanceName}...`),await YS(r.apikey);const ue=await qc(t);s(ue),We.success(`${r.instanceName} desconectada!`)}catch(ue){console.error("Erro ao desconectar instância:",ue),We.error(ue instanceof Error?ue.message:"Erro ao desconectar instância")}},le=async()=>{if(!(r!=null&&r.id)){We.error("ID da instância não encontrado");return}if(window.confirm(`Tem certeza que deseja deletar a instância ${r.instanceName}? Esta ação não pode ser desfeita.`))try{We.info(`Deletando ${r.instanceName}...`),await ZS(r.id),We.success(`${r.instanceName} deletada!`),n("/manager/instances")}catch(me){console.error("Erro ao deletar instância:",me),We.error(me instanceof Error?me.message:"Erro ao deletar instância")}};return g?p.jsx("div",{className:"flex h-full items-center justify-center",children:p.jsx("div",{className:"text-center",children:p.jsx("p",{className:"text-muted-foreground",children:"Carregando..."})})}):r?p.jsxs("div",{className:"h-full flex flex-col",children:[p.jsx("div",{className:"border-b border-sidebar-border bg-sidebar p-6",children:p.jsx("div",{className:"flex items-center justify-between",children:p.jsxs("div",{className:"flex items-center gap-4",children:[p.jsx(ft,{variant:"ghost",size:"icon",onClick:()=>n("/manager/instances"),className:"text-sidebar-foreground hover:bg-sidebar-accent",children:p.jsx(xb,{className:"h-5 w-5"})}),p.jsxs("div",{children:[p.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Configurações"}),p.jsx("p",{className:"text-sm text-muted-foreground",children:r.instanceName})]})]})})}),p.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:p.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[p.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[p.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Informações da Instância"}),p.jsx("div",{className:"space-y-4",children:p.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-foreground",children:"Nome da Instância"}),p.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.instanceName})]}),p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-foreground",children:"Token da Instância"}),p.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[p.jsx("p",{className:"text-sm text-muted-foreground font-mono",children:v?r.apikey||"":"•".repeat((r.apikey||"").length)}),p.jsx("button",{type:"button",onClick:()=>y(!v),className:"text-muted-foreground hover:text-foreground transition-colors",title:v?"Ocultar token":"Mostrar token",children:v?p.jsx(zN,{size:18}):p.jsx(UN,{size:18})})]})]}),p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-foreground",children:"Status"}),p.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.status==="open"?"Conectado":"Desconectado"})]}),r.owner&&p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-foreground",children:"Número"}),p.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.owner})]}),r.profileName&&p.jsxs("div",{children:[p.jsx("label",{className:"text-sm font-medium text-foreground",children:"Nome do Perfil"}),p.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.profileName})]})]})})]}),p.jsx("form",{onSubmit:S(ee),children:p.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[p.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Configurações de Webhook"}),p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"webhookUrl",className:"block text-sm font-medium text-foreground mb-1",children:"URL do Webhook"}),p.jsx("input",{id:"webhookUrl",type:"url",placeholder:"https://seu-servidor.com/webhook",...E("webhookUrl"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),C.webhookUrl&&p.jsx("p",{className:"mt-1 text-sm text-destructive",children:C.webhookUrl.message}),p.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"URL que receberá os eventos do WhatsApp"})]}),p.jsxs("div",{children:[p.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Eventos para Webhook"}),p.jsxs("div",{className:"space-y-2 rounded-md border border-input p-3 max-h-60 overflow-y-auto",children:[p.jsx("div",{className:"p-2 rounded-md bg-primary/10 border border-primary/20",children:p.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[p.jsx("input",{type:"checkbox",checked:i.includes("ALL"),onChange:()=>I("ALL"),className:"rounded border-input w-4 h-4"}),p.jsx("span",{className:"text-sm font-semibold text-primary",children:"ALL"})]})}),p.jsx("div",{className:"grid grid-cols-2 gap-2",children:R5.filter(ue=>ue!=="ALL").map(ue=>p.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer hover:bg-accent p-2 rounded",children:[p.jsx("input",{type:"checkbox",checked:i.includes(ue)||i.includes("ALL"),onChange:()=>I(ue),disabled:i.includes("ALL"),className:"rounded border-input"}),p.jsx("span",{className:i.includes("ALL")?"text-muted-foreground":"text-foreground",children:ue})]},ue))})]})]}),p.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"rabbitmqEnable",className:"block text-sm font-medium text-foreground mb-1",children:"RabbitMQ"}),p.jsxs("select",{id:"rabbitmqEnable",...E("rabbitmqEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"websocketEnable",className:"block text-sm font-medium text-foreground mb-1",children:"WebSocket"}),p.jsxs("select",{id:"websocketEnable",...E("websocketEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),p.jsxs("div",{children:[p.jsx("label",{htmlFor:"natsEnable",className:"block text-sm font-medium text-foreground mb-1",children:"NATS"}),p.jsxs("select",{id:"natsEnable",...E("natsEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[p.jsx("option",{value:"",children:"Padrão"}),p.jsx("option",{value:"enabled",children:"Habilitado"}),p.jsx("option",{value:"disabled",children:"Desabilitado"})]})]})]}),p.jsx("div",{className:"flex justify-end",children:p.jsxs(ft,{type:"submit",disabled:u,className:"gap-2",children:[p.jsx(Cb,{className:"h-4 w-4"}),u?"Salvando...":"Salvar Webhook"]})})]})]})}),p.jsx("form",{onSubmit:R(U),children:p.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[p.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Configurações Avançadas"}),p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"alwaysOnline",className:"text-sm font-medium text-foreground cursor-pointer",children:"Always Online"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Manter sempre online no WhatsApp"})]}),p.jsx("input",{id:"alwaysOnline",type:"checkbox",...O("alwaysOnline"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"rejectCall",className:"text-sm font-medium text-foreground cursor-pointer",children:"Reject Call"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Rejeitar chamadas automaticamente"})]}),p.jsx("input",{id:"rejectCall",type:"checkbox",...O("rejectCall"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"readMessages",className:"text-sm font-medium text-foreground cursor-pointer",children:"Read Messages"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Marcar mensagens como lidas"})]}),p.jsx("input",{id:"readMessages",type:"checkbox",...O("readMessages"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"ignoreGroups",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Groups"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar mensagens de grupos"})]}),p.jsx("input",{id:"ignoreGroups",type:"checkbox",...O("ignoreGroups"),className:"rounded border-input w-4 h-4"})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("label",{htmlFor:"ignoreStatus",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Status"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar atualizações de status"})]}),p.jsx("input",{id:"ignoreStatus",type:"checkbox",...O("ignoreStatus"),className:"rounded border-input w-4 h-4"})]}),p.jsx("div",{className:"flex justify-end",children:p.jsxs(ft,{type:"submit",disabled:u,className:"gap-2",children:[p.jsx(Cb,{className:"h-4 w-4"}),u?"Salvando...":"Salvar Avançadas"]})})]})]})}),p.jsxs("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-6",children:[p.jsx("h2",{className:"text-lg font-semibold text-destructive mb-4",children:"Zona de Perigo"}),p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Desconectar Instância"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Desconecta a instância do WhatsApp"})]}),p.jsxs(ft,{variant:"destructive",onClick:Q,className:"gap-2",children:[p.jsx(Ax,{className:"h-4 w-4"}),"Desconectar"]})]}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{children:[p.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Deletar Instância"}),p.jsx("p",{className:"text-xs text-muted-foreground",children:"Remove permanentemente esta instância"})]}),p.jsxs(ft,{variant:"destructive",onClick:le,className:"gap-2",children:[p.jsx(Sh,{className:"h-4 w-4"}),"Deletar"]})]})]})]})]})})]}):p.jsx("div",{className:"flex h-full items-center justify-center",children:p.jsxs("div",{className:"text-center",children:[p.jsx("h2",{className:"text-xl font-semibold text-foreground mb-2",children:"Instância não encontrada"}),p.jsxs("p",{className:"text-muted-foreground mb-4",children:['A instância "',t,'" não foi encontrada.']}),p.jsxs(ft,{onClick:()=>n("/manager/instances"),children:[p.jsx(xb,{className:"h-4 w-4 mr-2"}),"Voltar para Instâncias"]})]})})}function j5(){return p.jsxs("div",{className:"p-6",children:[p.jsx("h1",{className:"mb-4 text-2xl font-bold text-gray-900",children:"Mensagens"}),p.jsx("p",{className:"text-gray-600",children:"Messages sending will be implemented here..."})]})}function O5(){return p.jsxs("div",{className:"p-6",children:[p.jsx("h1",{className:"mb-4 text-2xl font-bold text-foreground",children:"Eventos"}),p.jsx("p",{className:"text-muted-foreground",children:"Events monitor will be implemented here..."})]})}function k5(){return p.jsxs("div",{className:"p-6",children:[p.jsx("h1",{className:"mb-4 text-2xl font-bold text-gray-900",children:"Configurações"}),p.jsx("p",{className:"text-gray-600",children:"Settings will be implemented here..."})]})}function M5(){const{isAuthenticated:t}=Th();return p.jsx(KT,{children:p.jsxs(EA,{children:[p.jsx(z2,{children:p.jsxs(f2,{children:[p.jsx(ta,{path:"/",element:p.jsx(p3,{})}),p.jsx(ta,{path:"/manager/login",element:t?p.jsx(mm,{to:"/manager",replace:!0}):p.jsx(t5,{})}),t?p.jsxs(ta,{path:"/manager",element:p.jsx(JT,{}),children:[p.jsx(ta,{index:!0,element:p.jsx(n5,{})}),p.jsx(ta,{path:"instances",element:p.jsx(C5,{})}),p.jsx(ta,{path:"instances/:instanceId/settings",element:p.jsx(T5,{})}),p.jsx(ta,{path:"messages",element:p.jsx(j5,{})}),p.jsx(ta,{path:"events",element:p.jsx(O5,{})}),p.jsx(ta,{path:"settings",element:p.jsx(k5,{})})]}):p.jsx(ta,{path:"/manager/*",element:p.jsx(mm,{to:"/manager/login",replace:!0})}),p.jsx(ta,{path:"*",element:p.jsx(mm,{to:"/",replace:!0})})]})}),p.jsx(gN,{position:"top-right",richColors:!0})]})})}vC.createRoot(document.getElementById("root")).render(p.jsx(b.StrictMode,{children:p.jsx(M5,{})}));diff --git a/manager/dist/assets/index-CzMe8w3S.css b/manager/dist/assets/index-CzMe8w3S.cssnew file mode 100644index 0000000..2fd7ead--- /dev/null+++ b/manager/dist/assets/index-CzMe8w3S.css@@ -0,0 +1 @@+@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-100: oklch(93.6% .032 17.717);--color-red-500: oklch(63.7% .237 25.331);--color-red-600: oklch(57.7% .245 27.325);--color-red-700: oklch(50.5% .213 27.518);--color-red-800: oklch(44.4% .177 26.899);--color-orange-100: oklch(95.4% .038 75.164);--color-orange-500: oklch(70.5% .213 47.604);--color-orange-600: oklch(64.6% .222 41.116);--color-orange-700: oklch(55.3% .195 38.402);--color-yellow-100: oklch(97.3% .071 103.193);--color-yellow-400: oklch(85.2% .199 91.936);--color-yellow-500: oklch(79.5% .184 86.047);--color-yellow-600: oklch(68.1% .162 75.834);--color-yellow-700: oklch(55.4% .135 66.442);--color-green-50: oklch(98.2% .018 155.826);--color-green-100: oklch(96.2% .044 156.743);--color-green-200: oklch(92.5% .084 155.995);--color-green-400: oklch(79.2% .209 151.711);--color-green-500: oklch(72.3% .219 149.579);--color-green-600: oklch(62.7% .194 149.214);--color-green-700: oklch(52.7% .154 150.069);--color-green-800: oklch(44.8% .119 151.328);--color-blue-50: oklch(97% .014 254.604);--color-blue-100: oklch(93.2% .032 255.585);--color-blue-200: oklch(88.2% .059 254.128);--color-blue-400: oklch(70.7% .165 254.624);--color-blue-500: oklch(62.3% .214 259.815);--color-blue-600: oklch(54.6% .245 262.881);--color-blue-700: oklch(48.8% .243 264.376);--color-blue-800: oklch(42.4% .199 265.638);--color-blue-900: oklch(37.9% .146 265.522);--color-purple-50: oklch(97.7% .014 308.299);--color-purple-100: oklch(94.6% .033 307.174);--color-purple-200: oklch(90.2% .063 306.703);--color-purple-500: oklch(62.7% .265 303.9);--color-purple-600: oklch(55.8% .288 302.321);--color-purple-700: oklch(49.6% .265 301.924);--color-purple-900: oklch(38.1% .176 304.987);--color-pink-50: oklch(97.1% .014 343.198);--color-pink-500: oklch(65.6% .241 354.308);--color-pink-600: oklch(59.2% .249 .584);--color-slate-50: oklch(98.4% .003 247.858);--color-slate-800: oklch(27.9% .041 260.031);--color-slate-900: oklch(20.8% .042 265.755);--color-gray-400: oklch(70.7% .022 261.325);--color-gray-600: oklch(44.6% .03 256.802);--color-gray-700: oklch(37.3% .034 259.733);--color-gray-900: oklch(21% .034 264.665);--color-black: #000;--color-white: #fff;--spacing: .25rem;--container-xs: 20rem;--container-sm: 24rem;--container-md: 28rem;--container-lg: 32rem;--container-2xl: 42rem;--container-4xl: 56rem;--container-6xl: 72rem;--text-xs: .75rem;--text-xs--line-height: calc(1 / .75);--text-sm: .875rem;--text-sm--line-height: calc(1.25 / .875);--text-base: 1rem;--text-base--line-height: 1.5 ;--text-lg: 1.125rem;--text-lg--line-height: calc(1.75 / 1.125);--text-xl: 1.25rem;--text-xl--line-height: calc(1.75 / 1.25);--text-2xl: 1.5rem;--text-2xl--line-height: calc(2 / 1.5);--text-3xl: 1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl: 2.25rem;--text-4xl--line-height: calc(2.5 / 2.25);--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--font-weight-bold: 700;--tracking-tight: -.025em;--tracking-widest: .1em;--leading-tight: 1.25;--leading-snug: 1.375;--leading-relaxed: 1.625;--radius-xs: .125rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--animate-pulse: pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--aspect-video: 16 / 9;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-background: var(--background);--color-foreground: var(--foreground);--color-primary: var(--primary);--color-primary-foreground: var(--primary-foreground);--color-secondary: var(--secondary);--color-secondary-foreground: var(--secondary-foreground);--color-muted: var(--muted);--color-muted-foreground: var(--muted-foreground);--color-accent: var(--accent);--color-accent-foreground: var(--accent-foreground);--color-destructive: var(--destructive);--color-destructive-foreground: var(--destructive-foreground);--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring)}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}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;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-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}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor}@supports (color: color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\@container\/card-header{container-type:inline-size;container-name:card-header}.pointer-events-none{pointer-events:none}.invisible{visibility:hidden}.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}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.inset-x-0{inset-inline:calc(var(--spacing) * 0)}.inset-y-0{inset-block:calc(var(--spacing) * 0)}.-top-2{top:calc(var(--spacing) * -2)}.-top-12{top:calc(var(--spacing) * -12)}.top-0{top:calc(var(--spacing) * 0)}.top-1\.5{top:calc(var(--spacing) * 1.5)}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-3\.5{top:calc(var(--spacing) * 3.5)}.top-4{top:calc(var(--spacing) * 4)}.top-\[1px\]{top:1px}.top-\[50\%\]{top:50%}.top-\[60\%\]{top:60%}.top-full{top:100%}.-right-0{right:calc(var(--spacing) * -0)}.-right-2{right:calc(var(--spacing) * -2)}.-right-12{right:calc(var(--spacing) * -12)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.-bottom-0{bottom:calc(var(--spacing) * -0)}.-bottom-12{bottom:calc(var(--spacing) * -12)}.bottom-0{bottom:calc(var(--spacing) * 0)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:calc(var(--spacing) * 0)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.left-\[50\%\]{left:50%}.isolate{isolation:isolate}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[1\]{z-index:1}.col-span-2{grid-column:span 2 / span 2}.col-span-3{grid-column:span 3 / span 3}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2 / span 2}.row-span-3{grid-row:span 3 / span 3}.row-start-1{grid-row-start:1}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-2{margin-inline:calc(var(--spacing) * 2)}.mx-3\.5{margin-inline:calc(var(--spacing) * 3.5)}.mx-auto{margin-inline:auto}.my-0\.5{margin-block:calc(var(--spacing) * .5)}.my-1{margin-block:calc(var(--spacing) * 1)}.my-4{margin-block:calc(var(--spacing) * 4)}.-mt-1{margin-top:calc(var(--spacing) * -1)}.-mt-4{margin-top:calc(var(--spacing) * -4)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.-ml-4{margin-left:calc(var(--spacing) * -4)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-8{margin-left:calc(var(--spacing) * 8)}.ml-12{margin-left:calc(var(--spacing) * 12)}.ml-auto{margin-left:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-row{display:table-row}.field-sizing-content{field-sizing:content}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:var(--aspect-video)}.size-\(--cell-size\){width:var(--cell-size);height:var(--cell-size)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-2\.5{width:calc(var(--spacing) * 2.5);height:calc(var(--spacing) * 2.5)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-auto{width:auto;height:auto}.size-full{width:100%;height:100%}.h-\(--cell-size\){height:var(--cell-size)}.h-1{height:calc(var(--spacing) * 1)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-24{height:calc(var(--spacing) * 24)}.h-32{height:calc(var(--spacing) * 32)}.h-48{height:calc(var(--spacing) * 48)}.h-\[1\.15rem\]{height:1.15rem}.h-\[100px\]{height:100px}.h-\[150px\]{height:150px}.h-\[200px\]{height:200px}.h-\[300px\]{height:300px}.h-\[400px\]{height:400px}.h-\[500px\]{height:500px}.h-\[calc\(100\%-1px\)\]{height:calc(100% - 1px)}.h-\[var\(--radix-navigation-menu-viewport-height\)\]{height:var(--radix-navigation-menu-viewport-height)}.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}.h-svh{height:100svh}.max-h-\(--radix-context-menu-content-available-height\){max-height:var(--radix-context-menu-content-available-height)}.max-h-\(--radix-dropdown-menu-content-available-height\){max-height:var(--radix-dropdown-menu-content-available-height)}.max-h-\(--radix-select-content-available-height\){max-height:var(--radix-select-content-available-height)}.max-h-\[80vh\]{max-height:80vh}.max-h-\[300px\]{max-height:300px}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-4{min-height:calc(var(--spacing) * 4)}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[80px\]{min-height:80px}.min-h-\[100px\]{min-height:100px}.min-h-\[100vh\]{min-height:100vh}.min-h-svh{min-height:100svh}.w-\(--cell-size\){width:var(--cell-size)}.w-0{width:calc(var(--spacing) * 0)}.w-1{width:calc(var(--spacing) * 1)}.w-1\/2{width:50%}.w-2{width:calc(var(--spacing) * 2)}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-2\/3{width:calc(2/3 * 100%)}.w-3{width:calc(var(--spacing) * 3)}.w-3\/4{width:75%}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-18{width:calc(var(--spacing) * 18)}.w-20{width:calc(var(--spacing) * 20)}.w-24{width:calc(var(--spacing) * 24)}.w-32{width:calc(var(--spacing) * 32)}.w-48{width:calc(var(--spacing) * 48)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-72{width:calc(var(--spacing) * 72)}.w-80{width:calc(var(--spacing) * 80)}.w-96{width:calc(var(--spacing) * 96)}.w-\[--radix-dropdown-menu-trigger-width\]{width:--radix-dropdown-menu-trigger-width}.w-\[50px\]{width:50px}.w-\[100px\]{width:100px}.w-\[180px\]{width:180px}.w-\[200px\]{width:200px}.w-\[250px\]{width:250px}.w-\[280px\]{width:280px}.w-\[300px\]{width:300px}.w-\[350px\]{width:350px}.w-\[400px\]{width:400px}.w-\[500px\]{width:500px}.w-\[600px\]{width:600px}.w-\[var\(--sidebar-width\)\]{width:var(--sidebar-width)}.w-auto{width:auto}.w-fit{width:fit-content}.w-full{width:100%}.w-max{width:max-content}.w-px{width:1px}.max-w-\(--skeleton-width\){max-width:var(--skeleton-width)}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-6xl{max-width:var(--container-6xl)}.max-w-\[calc\(100\%-2rem\)\]{max-width:calc(100% - 2rem)}.max-w-lg{max-width:var(--container-lg)}.max-w-max{max-width:max-content}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xs{max-width:var(--container-xs)}.min-w-\(--cell-size\){min-width:var(--cell-size)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-8{min-width:calc(var(--spacing) * 8)}.min-w-9{min-width:calc(var(--spacing) * 9)}.min-w-10{min-width:calc(var(--spacing) * 10)}.min-w-56{min-width:calc(var(--spacing) * 56)}.min-w-\[8rem\]{min-width:8rem}.min-w-\[12rem\]{min-width:12rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.flex-1{flex:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.origin-\(--radix-context-menu-content-transform-origin\){transform-origin:var(--radix-context-menu-content-transform-origin)}.origin-\(--radix-dropdown-menu-content-transform-origin\){transform-origin:var(--radix-dropdown-menu-content-transform-origin)}.origin-\(--radix-hover-card-content-transform-origin\){transform-origin:var(--radix-hover-card-content-transform-origin)}.origin-\(--radix-menubar-content-transform-origin\){transform-origin:var(--radix-menubar-content-transform-origin)}.origin-\(--radix-select-content-transform-origin\){transform-origin:var(--radix-select-content-transform-origin)}.origin-\(--radix-tooltip-content-transform-origin\){transform-origin:var(--radix-tooltip-content-transform-origin)}.-translate-x-1\/2{--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-px{--tw-translate-x: -1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-\[-50\%\]{--tw-translate-x: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-px{--tw-translate-x: 1px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-0\.5{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[-50\%\]{--tw-translate-y: -50%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-\[calc\(-50\%_-_2px\)\]{--tw-translate-y: calc(-50% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-45{rotate:45deg}.rotate-90{rotate:90deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-caret-blink{animation:caret-blink 1.25s ease-out infinite}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize-none{resize:none}.scroll-my-1{scroll-margin-block:calc(var(--spacing) * 1)}.scroll-py-1{scroll-padding-block:calc(var(--spacing) * 1)}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.list-none{list-style-type:none}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.auto-rows-min{grid-auto-rows:min-content}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-\[0_1fr\]{grid-template-columns:0 1fr}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.justify-items-start{justify-items:start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-0>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 0) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 0) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 8) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-y-reverse)))}:where(.-space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * -2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * -2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 4) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-6>:not(:last-child)){--tw-space-x-reverse: 0;margin-inline-start:calc(calc(var(--spacing) * 6) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[4px\]{border-radius:4px}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:calc(infinity * 1px)}.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:calc(var(--radius) + 4px)}.rounded-xs{border-radius:var(--radius-xs)}.rounded-l-md{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.rounded-r-md{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-\[1\.5px\]{border-style:var(--tw-border-style);border-width:1.5px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style: dashed;border-style:dashed}.border-\(--color-border\){border-color:var(--color-border)}.border-background{border-color:var(--background)}.border-blue-200{border-color:var(--color-blue-200)}.border-border\/50{border-color:var(--border)}@supports (color: color-mix(in lab,red,red)){.border-border\/50{border-color:color-mix(in oklab,var(--border) 50%,transparent)}}.border-current{border-color:currentcolor}.border-destructive{border-color:var(--destructive)}.border-destructive\/20{border-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.border-destructive\/20{border-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.border-gray-700{border-color:var(--color-gray-700)}.border-green-200{border-color:var(--color-green-200)}.border-green-500{border-color:var(--color-green-500)}.border-input{border-color:var(--input)}.border-muted{border-color:var(--muted)}.border-primary{border-color:var(--primary)}.border-purple-100{border-color:var(--color-purple-100)}.border-purple-200{border-color:var(--color-purple-200)}.border-sidebar-border{border-color:var(--sidebar-border)}.border-transparent{border-color:transparent}.border-white{border-color:var(--color-white)}.border-yellow-500{border-color:var(--color-yellow-500)}.border-t-transparent{border-top-color:transparent}.border-l-transparent{border-left-color:transparent}.bg-\(--color-bg\){background-color:var(--color-bg)}.bg-accent{background-color:var(--accent)}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\/50{background-color:color-mix(in srgb,#000 50%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-100{background-color:var(--color-blue-100)}.bg-blue-500{background-color:var(--color-blue-500)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-border{background-color:var(--border)}.bg-card{background-color:var(--card)}.bg-destructive{background-color:var(--destructive)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.bg-foreground{background-color:var(--foreground)}.bg-gray-400{background-color:var(--color-gray-400)}.bg-gray-600{background-color:var(--color-gray-600)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-500{background-color:var(--color-green-500)}.bg-green-600{background-color:var(--color-green-600)}.bg-muted{background-color:var(--muted)}.bg-muted\/50{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.bg-muted\/50{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}.bg-orange-100{background-color:var(--color-orange-100)}.bg-orange-500{background-color:var(--color-orange-500)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-popover{background-color:var(--popover)}.bg-primary{background-color:var(--primary)}.bg-primary\/10{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary) 10%,transparent)}}.bg-primary\/20{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.bg-primary\/20{background-color:color-mix(in oklab,var(--primary) 20%,transparent)}}.bg-purple-100{background-color:var(--color-purple-100)}.bg-purple-500{background-color:var(--color-purple-500)}.bg-purple-600{background-color:var(--color-purple-600)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500{background-color:var(--color-red-500)}.bg-red-600{background-color:var(--color-red-600)}.bg-secondary{background-color:var(--secondary)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-sidebar-primary{background-color:var(--sidebar-primary)}.bg-slate-50{background-color:var(--color-slate-50)}.bg-transparent{background-color:transparent}.bg-white{background-color:var(--color-white)}.bg-white\/60{background-color:color-mix(in srgb,#fff 60%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/60{background-color:color-mix(in oklab,var(--color-white) 60%,transparent)}}.bg-white\/80{background-color:color-mix(in srgb,#fff 80%,transparent)}@supports (color: color-mix(in lab,red,red)){.bg-white\/80{background-color:color-mix(in oklab,var(--color-white) 80%,transparent)}}.bg-yellow-100{background-color:var(--color-yellow-100)}.bg-yellow-500{background-color:var(--color-yellow-500)}.bg-yellow-600{background-color:var(--color-yellow-600)}.bg-gradient-to-b{--tw-gradient-position: to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-br{--tw-gradient-position: to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-r{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-400{--tw-gradient-from: var(--color-blue-400);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500{--tw-gradient-from: var(--color-blue-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500\/20{--tw-gradient-from: color-mix(in srgb, oklch(62.3% .214 259.815) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-blue-500\/20{--tw-gradient-from: color-mix(in oklab, var(--color-blue-500) 20%, transparent)}}.from-muted\/50{--tw-gradient-from: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.from-muted\/50{--tw-gradient-from: color-mix(in oklab, var(--muted) 50%, transparent)}}.from-purple-50{--tw-gradient-from: var(--color-purple-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-purple-500{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-white{--tw-gradient-from: var(--color-white);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-blue-600\/20{--tw-gradient-to: color-mix(in srgb, oklch(54.6% .245 262.881) 20%, transparent);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}@supports (color: color-mix(in lab,red,red)){.to-blue-600\/20{--tw-gradient-to: color-mix(in oklab, var(--color-blue-600) 20%, transparent)}}.to-gray-900{--tw-gradient-to: var(--color-gray-900);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-muted{--tw-gradient-to: var(--muted);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-50{--tw-gradient-to: var(--color-pink-50);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-500{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-purple-600{--tw-gradient-to: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-blue-400{fill:var(--color-blue-400)}.fill-current{fill:currentcolor}.fill-primary{fill:var(--primary)}.fill-yellow-400{fill:var(--color-yellow-400)}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing) * 0)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[3px\]{padding:3px}.p-px{padding:1px}.px-\(--cell-size\){padding-inline:var(--cell-size)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-0{padding-top:calc(var(--spacing) * 0)}.pt-1{padding-top:calc(var(--spacing) * 1)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-1{padding-right:calc(var(--spacing) * 1)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-0{padding-bottom:calc(var(--spacing) * 0)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading, var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading, var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading, var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading, var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading, var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading, var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.text-\[0\.8rem\]{font-size:.8rem}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading: 1;line-height:1}.leading-relaxed{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading: var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading: var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight: var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking: var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-widest{--tw-tracking: var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.break-words{overflow-wrap:break-word}.whitespace-nowrap{white-space:nowrap}.text-accent-foreground{color:var(--accent-foreground)}.text-blue-400{color:var(--color-blue-400)}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-blue-700{color:var(--color-blue-700)}.text-blue-800{color:var(--color-blue-800)}.text-blue-900{color:var(--color-blue-900)}.text-card-foreground{color:var(--card-foreground)}.text-current{color:currentcolor}.text-destructive{color:var(--destructive)}.text-destructive-foreground{color:var(--destructive-foreground)}.text-foreground{color:var(--foreground)}.text-green-400{color:var(--color-green-400)}.text-green-500{color:var(--color-green-500)}.text-green-600{color:var(--color-green-600)}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted-foreground{color:var(--muted-foreground)}.text-orange-600{color:var(--color-orange-600)}.text-orange-700{color:var(--color-orange-700)}.text-pink-600{color:var(--color-pink-600)}.text-popover-foreground{color:var(--popover-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-purple-500{color:var(--color-purple-500)}.text-purple-600{color:var(--color-purple-600)}.text-purple-700{color:var(--color-purple-700)}.text-purple-900{color:var(--color-purple-900)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-red-800{color:var(--color-red-800)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-sidebar-foreground{color:var(--sidebar-foreground)}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color: color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground) 70%,transparent)}}.text-sidebar-primary-foreground{color:var(--sidebar-primary-foreground)}.text-white{color:var(--color-white)}.text-yellow-400{color:var(--color-yellow-400)}.text-yellow-600{color:var(--color-yellow-600)}.text-yellow-700{color:var(--color-yellow-700)}.capitalize{text-transform:capitalize}.italic{font-style:italic}.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,)}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0%}.opacity-50{opacity:50%}.opacity-70{opacity:70%}.opacity-75{opacity:75%}.opacity-90{opacity:90%}.opacity-100{opacity:100%}.shadow{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-border)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 8px 10px -6px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-xs{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-0{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-primary{--tw-ring-color: var(--primary)}.ring-ring\/50{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.ring-ring\/50{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.ring-sidebar-ring{--tw-ring-color: var(--sidebar-ring)}.ring-offset-background{--tw-ring-offset-color: var(--background)}.outline-hidden{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.outline-hidden{outline:2px solid transparent;outline-offset:2px}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[margin\,opacity\]{transition-property:margin,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\,height\]{transition-property:width,height;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\[width\]{transition-property:width;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-none{transition-property:none}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-300{--tw-duration: .3s;transition-duration:.3s}.duration-1000{--tw-duration: 1s;transition-duration:1s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-linear{--tw-ease: linear;transition-timing-function:linear}.fade-in-0{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.outline-none{--tw-outline-style: none;outline-style:none}.select-all{-webkit-user-select:all;user-select:all}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.\[--cell-size\:--spacing\(8\)\]{--cell-size: calc(var(--spacing) * 8)}.group-focus-within\/menu-item\:opacity-100:is(:where(.group\/menu-item):focus-within *){opacity:100%}@media(hover:hover){.group-hover\/menu-item\:opacity-100:is(:where(.group\/menu-item):hover *){opacity:100%}}.group-has-data-\[sidebar\=menu-action\]\/menu-item\:pr-8:is(:where(.group\/menu-item):has(*[data-sidebar=menu-action]) *){padding-right:calc(var(--spacing) * 8)}.group-has-\[\[data-collapsible\=icon\]\]\/sidebar-wrapper\:h-12:is(:where(.group\/sidebar-wrapper):has(*:is([data-collapsible=icon])) *){height:calc(var(--spacing) * 12)}.group-data-\[collapsible\=icon\]\:-mt-8:is(:where(.group)[data-collapsible=icon] *){margin-top:calc(var(--spacing) * -8)}.group-data-\[collapsible\=icon\]\:hidden:is(:where(.group)[data-collapsible=icon] *){display:none}.group-data-\[collapsible\=icon\]\:size-8\!:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--spacing) * 8)!important;height:calc(var(--spacing) * 8)!important}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem)}.group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+1rem\+2px\)\]:is(:where(.group)[data-collapsible=icon] *){width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group-data-\[collapsible\=icon\]\:w-\[var\(--sidebar-width-icon\)\]:is(:where(.group)[data-collapsible=icon] *){width:var(--sidebar-width-icon)}.group-data-\[collapsible\=icon\]\:overflow-hidden:is(:where(.group)[data-collapsible=icon] *){overflow:hidden}.group-data-\[collapsible\=icon\]\:p-0\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 0)!important}.group-data-\[collapsible\=icon\]\:p-2\!:is(:where(.group)[data-collapsible=icon] *){padding:calc(var(--spacing) * 2)!important}.group-data-\[collapsible\=icon\]\:opacity-0:is(:where(.group)[data-collapsible=icon] *){opacity:0%}.group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){right:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]:is(:where(.group)[data-collapsible=offcanvas] *){left:calc(var(--sidebar-width) * -1)}.group-data-\[collapsible\=offcanvas\]\:w-0:is(:where(.group)[data-collapsible=offcanvas] *){width:calc(var(--spacing) * 0)}.group-data-\[collapsible\=offcanvas\]\:translate-x-0:is(:where(.group)[data-collapsible=offcanvas] *){--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[disabled\=true\]\:pointer-events-none:is(:where(.group)[data-disabled=true] *){pointer-events:none}.group-data-\[disabled\=true\]\:opacity-50:is(:where(.group)[data-disabled=true] *){opacity:50%}.group-data-\[focused\=true\]\/day\:relative:is(:where(.group\/day)[data-focused=true] *){position:relative}.group-data-\[focused\=true\]\/day\:z-10:is(:where(.group\/day)[data-focused=true] *){z-index:10}.group-data-\[focused\=true\]\/day\:border-ring:is(:where(.group\/day)[data-focused=true] *){border-color:var(--ring)}.group-data-\[focused\=true\]\/day\:ring-\[3px\]:is(:where(.group\/day)[data-focused=true] *){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.group-data-\[focused\=true\]\/day\:ring-ring\/50:is(:where(.group\/day)[data-focused=true] *){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.group-data-\[side\=left\]\:-right-4:is(:where(.group)[data-side=left] *){right:calc(var(--spacing) * -4)}.group-data-\[side\=left\]\:border-r:is(:where(.group)[data-side=left] *){border-right-style:var(--tw-border-style);border-right-width:1px}.group-data-\[side\=right\]\:left-0:is(:where(.group)[data-side=right] *){left:calc(var(--spacing) * 0)}.group-data-\[side\=right\]\:rotate-180:is(:where(.group)[data-side=right] *){rotate:180deg}.group-data-\[side\=right\]\:border-l:is(:where(.group)[data-side=right] *){border-left-style:var(--tw-border-style);border-left-width:1px}.group-data-\[state\=open\]\:rotate-180:is(:where(.group)[data-state=open] *){rotate:180deg}.group-data-\[state\=open\]\/collapsible\:rotate-180:is(:where(.group\/collapsible)[data-state=open] *){rotate:180deg}.group-data-\[variant\=floating\]\:rounded-lg:is(:where(.group)[data-variant=floating] *){border-radius:var(--radius)}.group-data-\[variant\=floating\]\:border:is(:where(.group)[data-variant=floating] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[variant\=floating\]\:border-sidebar-border:is(:where(.group)[data-variant=floating] *){border-color:var(--sidebar-border)}.group-data-\[variant\=floating\]\:shadow-sm:is(:where(.group)[data-variant=floating] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:block:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){display:block}.group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=bottom] *){text-align:center}.group-data-\[vaul-drawer-direction\=top\]\/drawer-content\:text-center:is(:where(.group\/drawer-content)[data-vaul-drawer-direction=top] *){text-align:center}.group-data-\[viewport\=false\]\/navigation-menu\:top-full:is(:where(.group\/navigation-menu)[data-viewport=false] *){top:100%}.group-data-\[viewport\=false\]\/navigation-menu\:mt-1\.5:is(:where(.group\/navigation-menu)[data-viewport=false] *){margin-top:calc(var(--spacing) * 1.5)}.group-data-\[viewport\=false\]\/navigation-menu\:overflow-hidden:is(:where(.group\/navigation-menu)[data-viewport=false] *){overflow:hidden}.group-data-\[viewport\=false\]\/navigation-menu\:rounded-md:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-radius:calc(var(--radius) - 2px)}.group-data-\[viewport\=false\]\/navigation-menu\:border:is(:where(.group\/navigation-menu)[data-viewport=false] *){border-style:var(--tw-border-style);border-width:1px}.group-data-\[viewport\=false\]\/navigation-menu\:bg-popover:is(:where(.group\/navigation-menu)[data-viewport=false] *){background-color:var(--popover)}.group-data-\[viewport\=false\]\/navigation-menu\:text-popover-foreground:is(:where(.group\/navigation-menu)[data-viewport=false] *){color:var(--popover-foreground)}.group-data-\[viewport\=false\]\/navigation-menu\:shadow:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.group-data-\[viewport\=false\]\/navigation-menu\:duration-200:is(:where(.group\/navigation-menu)[data-viewport=false] *){--tw-duration: .2s;transition-duration:.2s}@media(hover:hover){.peer-hover\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button):hover~*){color:var(--sidebar-accent-foreground)}}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-50:is(:where(.peer):disabled~*){opacity:50%}.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground:is(:where(.peer\/menu-button)[data-active=true]~*){color:var(--sidebar-accent-foreground)}.peer-data-\[size\=default\]\/menu-button\:top-1\.5:is(:where(.peer\/menu-button)[data-size=default]~*){top:calc(var(--spacing) * 1.5)}.peer-data-\[size\=lg\]\/menu-button\:top-2\.5:is(:where(.peer\/menu-button)[data-size=lg]~*){top:calc(var(--spacing) * 2.5)}.peer-data-\[size\=sm\]\/menu-button\:top-1:is(:where(.peer\/menu-button)[data-size=sm]~*){top:calc(var(--spacing) * 1)}.selection\:bg-primary *::selection{background-color:var(--primary)}.selection\:bg-primary::selection{background-color:var(--primary)}.selection\:text-primary-foreground *::selection{color:var(--primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-foreground::file-selector-button{color:var(--foreground)}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);inset:calc(var(--spacing) * -2)}.after\:inset-y-0:after{content:var(--tw-content);inset-block:calc(var(--spacing) * 0)}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:calc(var(--spacing) * 1)}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.group-data-\[collapsible\=offcanvas\]\:after\:left-full:is(:where(.group)[data-collapsible=offcanvas] *):after{content:var(--tw-content);left:100%}.first\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\:border-l:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.last\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}@media(hover:hover){.hover\:border-muted-foreground\/50:hover{border-color:var(--muted-foreground)}@supports (color: color-mix(in lab,red,red)){.hover\:border-muted-foreground\/50:hover{border-color:color-mix(in oklab,var(--muted-foreground) 50%,transparent)}}}@media(hover:hover){.hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}}@media(hover:hover){.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){.hover\:bg-gray-700:hover{background-color:var(--color-gray-700)}}@media(hover:hover){.hover\:bg-green-700:hover{background-color:var(--color-green-700)}}@media(hover:hover){.hover\:bg-muted:hover{background-color:var(--muted)}}@media(hover:hover){.hover\:bg-muted\/50:hover{background-color:var(--muted)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab,var(--muted) 50%,transparent)}}}@media(hover:hover){.hover\:bg-orange-700:hover{background-color:var(--color-orange-700)}}@media(hover:hover){.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){.hover\:bg-purple-700:hover{background-color:var(--color-purple-700)}}@media(hover:hover){.hover\:bg-red-700:hover{background-color:var(--color-red-700)}}@media(hover:hover){.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab,var(--secondary) 80%,transparent)}}}@media(hover:hover){.hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.hover\:bg-white:hover{background-color:var(--color-white)}}@media(hover:hover){.hover\:bg-yellow-700:hover{background-color:var(--color-yellow-700)}}@media(hover:hover){.hover\:from-purple-600:hover{--tw-gradient-from: var(--color-purple-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:to-pink-600:hover{--tw-gradient-to: var(--color-pink-600);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}}@media(hover:hover){.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}@media(hover:hover){.hover\:text-destructive:hover{color:var(--destructive)}}@media(hover:hover){.hover\:text-foreground:hover{color:var(--foreground)}}@media(hover:hover){.hover\:text-muted-foreground:hover{color:var(--muted-foreground)}}@media(hover:hover){.hover\:text-primary:hover{color:var(--primary)}}@media(hover:hover){.hover\:text-sidebar-accent-foreground:hover{color:var(--sidebar-accent-foreground)}}@media(hover:hover){.hover\:underline:hover{text-decoration-line:underline}}@media(hover:hover){.hover\:opacity-90:hover{opacity:90%}}@media(hover:hover){.hover\:opacity-100:hover{opacity:100%}}@media(hover:hover){.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px var(--tw-shadow-color, hsl(var(--sidebar-accent)));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:ring-4:hover{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(hover:hover){.hover\:group-data-\[collapsible\=offcanvas\]\:bg-sidebar:hover:is(:where(.group)[data-collapsible=offcanvas] *){background-color:var(--sidebar)}}@media(hover:hover){.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:var(--sidebar-border)}}.focus\:z-10:focus{z-index:10}.focus\:bg-accent:focus{background-color:var(--accent)}.focus\:text-accent-foreground:focus{color:var(--accent-foreground)}.focus\:shadow-md:focus{--tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-ring:focus{--tw-ring-color: var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-hidden:focus{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus\:outline-hidden:focus{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:z-10:focus-visible{z-index:10}.focus-visible\:border-ring:focus-visible{border-color:var(--ring)}.focus-visible\:ring-1:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-4:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(72.3% .219 149.579) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-green-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-green-500) 20%, transparent)}}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: var(--ring)}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in srgb, oklch(79.5% .184 86.047) 20%, transparent)}@supports (color: color-mix(in lab,red,red)){.focus-visible\:ring-yellow-500\/20:focus-visible{--tw-ring-color: color-mix(in oklab, var(--color-yellow-500) 20%, transparent)}}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px;--tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:outline-hidden:focus-visible{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.focus-visible\:outline-hidden:focus-visible{outline:2px solid transparent;outline-offset:2px}}.focus-visible\:outline-1:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-ring:focus-visible{outline-color:var(--ring)}.focus-visible\:outline-none:focus-visible{--tw-outline-style: none;outline-style:none}.active\:bg-sidebar-accent:active{background-color:var(--sidebar-accent)}.active\:text-sidebar-accent-foreground:active{color:var(--sidebar-accent-foreground)}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:50%}:where(*[data-side=left]) .in-data-\[side\=left\]\:cursor-w-resize{cursor:w-resize}:where(*[data-side=right]) .in-data-\[side\=right\]\:cursor-e-resize{cursor:e-resize}.has-focus\:border-ring:has(*:focus){border-color:var(--ring)}.has-focus\:ring-\[3px\]:has(*:focus){--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.has-focus\:ring-ring\/50:has(*:focus){--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}.has-disabled\:opacity-50:has(*:disabled){opacity:50%}.has-data-\[slot\=card-action\]\:grid-cols-\[1fr_auto\]:has(*[data-slot=card-action]){grid-template-columns:1fr auto}.has-data-\[variant\=inset\]\:bg-sidebar:has(*[data-variant=inset]){background-color:var(--sidebar)}.has-\[\>svg\]\:grid-cols-\[calc\(var\(--spacing\)\*4\)_1fr\]:has(>svg){grid-template-columns:calc(var(--spacing) * 4) 1fr}.has-\[\>svg\]\:gap-x-3:has(>svg){column-gap:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.has-\[\>svg\]\:px-3:has(>svg){padding-inline:calc(var(--spacing) * 3)}.has-\[\>svg\]\:px-4:has(>svg){padding-inline:calc(var(--spacing) * 4)}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:50%}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.aria-selected\:text-muted-foreground[aria-selected=true]{color:var(--muted-foreground)}.data-\[active\=true\]\:z-10[data-active=true]{z-index:10}.data-\[active\=true\]\:border-ring[data-active=true]{border-color:var(--ring)}.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:var(--sidebar-accent)}.data-\[active\=true\]\:font-medium[data-active=true]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.data-\[active\=true\]\:text-accent-foreground[data-active=true]{color:var(--accent-foreground)}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:var(--sidebar-accent-foreground)}.data-\[active\=true\]\:ring-\[3px\][data-active=true]{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: var(--ring)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: color-mix(in oklab, var(--ring) 50%, transparent)}}@media(hover:hover){.data-\[active\=true\]\:hover\:bg-accent[data-active=true]:hover{background-color:var(--accent)}}.data-\[active\=true\]\:focus\:bg-accent[data-active=true]:focus{background-color:var(--accent)}.data-\[active\=true\]\:aria-invalid\:border-destructive[data-active=true][aria-invalid=true]{border-color:var(--destructive)}.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[active\=true\]\:aria-invalid\:ring-destructive\/20[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 20%, transparent)}}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:50%}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true]{pointer-events:none}.data-\[disabled\=true\]\:opacity-50[data-disabled=true]{opacity:50%}.data-\[empty\=true\]\:text-muted-foreground[data-empty=true]{color:var(--muted-foreground)}.data-\[error\=true\]\:text-destructive[data-error=true]{color:var(--destructive)}.data-\[inset\]\:pl-8[data-inset]{padding-left:calc(var(--spacing) * 8)}.data-\[motion\=from-end\]\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: calc(52*var(--spacing))}.data-\[motion\=from-start\]\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\=to-end\]\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: calc(52*var(--spacing))}.data-\[motion\=to-start\]\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: calc(52*var(--spacing)*-1)}.data-\[motion\^\=from-\]\:animate-in[data-motion^=from-]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=from-\]\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\[motion\^\=to-\]\:animate-out[data-motion^=to-]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[motion\^\=to-\]\:fade-out[data-motion^=to-]{--tw-exit-opacity: 0}.data-\[orientation\=horizontal\]\:h-1\.5[data-orientation=horizontal]{height:calc(var(--spacing) * 1.5)}.data-\[orientation\=horizontal\]\:h-full[data-orientation=horizontal]{height:100%}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[orientation\=vertical\]\:min-h-44[data-orientation=vertical]{min-height:calc(var(--spacing) * 44)}.data-\[orientation\=vertical\]\:w-1\.5[data-orientation=vertical]{width:calc(var(--spacing) * 1.5)}.data-\[orientation\=vertical\]\:w-auto[data-orientation=vertical]{width:auto}.data-\[orientation\=vertical\]\:w-full[data-orientation=vertical]{width:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[orientation\=vertical\]\:flex-col[data-orientation=vertical]{flex-direction:column}.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-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:calc(var(--spacing) * 0)}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:calc(var(--spacing) * 1)}.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-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--muted-foreground)}.data-\[range-end\=true\]\:rounded-md[data-range-end=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:rounded-r-md[data-range-end=true]{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.data-\[range-end\=true\]\:bg-primary[data-range-end=true]{background-color:var(--primary)}.data-\[range-end\=true\]\:text-primary-foreground[data-range-end=true]{color:var(--primary-foreground)}.data-\[range-middle\=true\]\:rounded-none[data-range-middle=true]{border-radius:0}.data-\[range-middle\=true\]\:bg-accent[data-range-middle=true]{background-color:var(--accent)}.data-\[range-middle\=true\]\:text-accent-foreground[data-range-middle=true]{color:var(--accent-foreground)}.data-\[range-start\=true\]\:rounded-md[data-range-start=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:rounded-l-md[data-range-start=true]{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:bg-primary[data-range-start=true]{background-color:var(--primary)}.data-\[range-start\=true\]\:text-primary-foreground[data-range-start=true]{color:var(--primary-foreground)}.data-\[selected-single\=true\]\:bg-primary[data-selected-single=true]{background-color:var(--primary)}.data-\[selected-single\=true\]\:text-primary-foreground[data-selected-single=true]{color:var(--primary-foreground)}.data-\[selected\=true\]\:rounded-none[data-selected=true]{border-radius:0}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:var(--accent)}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:var(--accent-foreground)}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: calc(2*var(--spacing)*-1)}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: calc(2*var(--spacing))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: calc(2*var(--spacing)*-1)}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: calc(var(--spacing) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: calc(2*var(--spacing))}.data-\[size\=default\]\:h-9[data-size=default]{height:calc(var(--spacing) * 9)}.data-\[size\=sm\]\:h-8[data-size=sm]{height:calc(var(--spacing) * 8)}:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){:is(.\*\:data-\[slot\=alert-description\]\:text-destructive\/90>*)[data-slot=alert-description]{color:color-mix(in oklab,var(--destructive) 90%,transparent)}}:is(.\*\*\:data-\[slot\=command-input-wrapper\]\:h-12 *)[data-slot=command-input-wrapper]{height:calc(var(--spacing) * 12)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:ring-0 *)[data-slot=navigation-menu-link]:focus{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}:is(.\*\*\:data-\[slot\=navigation-menu-link\]\:focus\:outline-none *)[data-slot=navigation-menu-link]:focus{--tw-outline-style: none;outline-style:none}:is(.\*\:data-\[slot\=select-value\]\:line-clamp-1>*)[data-slot=select-value]{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}:is(.\*\:data-\[slot\=select-value\]\:flex>*)[data-slot=select-value]{display:flex}:is(.\*\:data-\[slot\=select-value\]\:items-center>*)[data-slot=select-value]{align-items:center}:is(.\*\:data-\[slot\=select-value\]\:gap-2>*)[data-slot=select-value]{gap:calc(var(--spacing) * 2)}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:var(--background)}.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[state\=checked\]\:translate-x-\[calc\(100\%-2px\)\][data-state=checked]{--tw-translate-x: calc(100% - 2px) ;translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=checked\]\:border-primary[data-state=checked]{border-color:var(--primary)}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:var(--primary)}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:var(--primary-foreground)}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:duration-300[data-state=closed]{--tw-duration: .3s;transition-duration:.3s}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:animate-out:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:fade-out-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-opacity: 0 ;--tw-exit-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:zoom-out-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=closed]{--tw-exit-scale: 95% ;--tw-exit-scale: .95}.data-\[state\=hidden\]\:animate-out[data-state=hidden]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=hidden\]\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\[state\=on\]\:bg-accent[data-state=on]{background-color:var(--accent)}.data-\[state\=on\]\:text-accent-foreground[data-state=on]{color:var(--accent-foreground)}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down var(--tw-animation-duration,var(--tw-duration,.2s))ease-out}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:var(--accent)}.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:var(--secondary)}.data-\[state\=open\]\:bg-sidebar-accent[data-state=open]{background-color:var(--sidebar-accent)}.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:var(--accent-foreground)}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:var(--muted-foreground)}.data-\[state\=open\]\:text-sidebar-accent-foreground[data-state=open]{color:var(--sidebar-accent-foreground)}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:100%}.data-\[state\=open\]\:duration-500[data-state=open]{--tw-duration: .5s;transition-duration:.5s}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.data-\[state\=open\]\:zoom-in-90[data-state=open]{--tw-enter-scale: 90% ;--tw-enter-scale: .9}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:animate-in:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:fade-in-0:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-opacity: 0 ;--tw-enter-opacity: 0}.group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:zoom-in-95:is(:where(.group\/navigation-menu)[data-viewport=false] *)[data-state=open]{--tw-enter-scale: 95% ;--tw-enter-scale: .95}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-accent[data-state=open]:hover{background-color:var(--accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:bg-sidebar-accent[data-state=open]:hover{background-color:var(--sidebar-accent)}}@media(hover:hover){.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground[data-state=open]:hover{color:var(--sidebar-accent-foreground)}}.data-\[state\=open\]\:focus\:bg-accent[data-state=open]:focus{background-color:var(--accent)}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:var(--muted)}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:var(--input)}.data-\[state\=visible\]\:animate-in[data-state=visible]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=visible\]\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{color:var(--destructive)}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.data-\[variant\=destructive\]\:focus\:bg-destructive\/10[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.data-\[variant\=destructive\]\:focus\:text-destructive[data-variant=destructive]:focus{color:var(--destructive)}.data-\[variant\=outline\]\:border-l-0[data-variant=outline]{border-left-style:var(--tw-border-style);border-left-width:0px}.data-\[variant\=outline\]\:shadow-xs[data-variant=outline]{--tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / .05));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\[variant\=outline\]\:first\:border-l[data-variant=outline]:first-child{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=bottom\]\:inset-x-0[data-vaul-drawer-direction=bottom]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:bottom-0[data-vaul-drawer-direction=bottom]{bottom:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=bottom\]\:mt-24[data-vaul-drawer-direction=bottom]{margin-top:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=bottom\]\:max-h-\[80vh\][data-vaul-drawer-direction=bottom]{max-height:80vh}.data-\[vaul-drawer-direction\=bottom\]\:rounded-t-lg[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.data-\[vaul-drawer-direction\=bottom\]\:border-t[data-vaul-drawer-direction=bottom]{border-top-style:var(--tw-border-style);border-top-width:1px}.data-\[vaul-drawer-direction\=left\]\:inset-y-0[data-vaul-drawer-direction=left]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:left-0[data-vaul-drawer-direction=left]{left:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=left\]\:w-3\/4[data-vaul-drawer-direction=left]{width:75%}.data-\[vaul-drawer-direction\=left\]\:border-r[data-vaul-drawer-direction=left]{border-right-style:var(--tw-border-style);border-right-width:1px}.data-\[vaul-drawer-direction\=right\]\:inset-y-0[data-vaul-drawer-direction=right]{inset-block:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:right-0[data-vaul-drawer-direction=right]{right:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=right\]\:w-3\/4[data-vaul-drawer-direction=right]{width:75%}.data-\[vaul-drawer-direction\=right\]\:border-l[data-vaul-drawer-direction=right]{border-left-style:var(--tw-border-style);border-left-width:1px}.data-\[vaul-drawer-direction\=top\]\:inset-x-0[data-vaul-drawer-direction=top]{inset-inline:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:top-0[data-vaul-drawer-direction=top]{top:calc(var(--spacing) * 0)}.data-\[vaul-drawer-direction\=top\]\:mb-24[data-vaul-drawer-direction=top]{margin-bottom:calc(var(--spacing) * 24)}.data-\[vaul-drawer-direction\=top\]\:max-h-\[80vh\][data-vaul-drawer-direction=top]{max-height:80vh}.data-\[vaul-drawer-direction\=top\]\:rounded-b-lg[data-vaul-drawer-direction=top]{border-bottom-right-radius:var(--radius);border-bottom-left-radius:var(--radius)}.data-\[vaul-drawer-direction\=top\]\:border-b[data-vaul-drawer-direction=top]{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}@media(min-width:40rem){.sm\:block{display:block}}@media(min-width:40rem){.sm\:flex{display:flex}}@media(min-width:40rem){.sm\:w-auto{width:auto}}@media(min-width:40rem){.sm\:max-w-\[425px\]{max-width:425px}}@media(min-width:40rem){.sm\:max-w-lg{max-width:var(--container-lg)}}@media(min-width:40rem){.sm\:max-w-md{max-width:var(--container-md)}}@media(min-width:40rem){.sm\:max-w-sm{max-width:var(--container-sm)}}@media(min-width:40rem){.sm\:flex-row{flex-direction:row}}@media(min-width:40rem){.sm\:justify-end{justify-content:flex-end}}@media(min-width:40rem){.sm\:gap-2\.5{gap:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pr-2\.5{padding-right:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:pl-2\.5{padding-left:calc(var(--spacing) * 2.5)}}@media(min-width:40rem){.sm\:text-left{text-align:left}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=left\]\:sm\:max-w-sm[data-vaul-drawer-direction=left]{max-width:var(--container-sm)}}@media(min-width:40rem){.data-\[vaul-drawer-direction\=right\]\:sm\:max-w-sm[data-vaul-drawer-direction=right]{max-width:var(--container-sm)}}@media(min-width:48rem){.md\:absolute{position:absolute}}@media(min-width:48rem){.md\:block{display:block}}@media(min-width:48rem){.md\:flex{display:flex}}@media(min-width:48rem){.md\:min-h-min{min-height:min-content}}@media(min-width:48rem){.md\:w-\[400px\]{width:400px}}@media(min-width:48rem){.md\:w-\[500px\]{width:500px}}@media(min-width:48rem){.md\:w-\[var\(--radix-navigation-menu-viewport-width\)\]{width:var(--radix-navigation-menu-viewport-width)}}@media(min-width:48rem){.md\:w-auto{width:auto}}@media(min-width:48rem){.md\:basis-1\/2{flex-basis:50%}}@media(min-width:48rem){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:48rem){.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:48rem){.md\:flex-row{flex-direction:row}}@media(min-width:48rem){.md\:gap-1\.5{gap:calc(var(--spacing) * 1.5)}}@media(min-width:48rem){.md\:text-left{text-align:left}}@media(min-width:48rem){.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}}@media(min-width:48rem){.md\:opacity-0{opacity:0%}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:m-2:is(:where(.peer)[data-variant=inset]~*){margin:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:ml-0:is(:where(.peer)[data-variant=inset]~*){margin-left:calc(var(--spacing) * 0)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:rounded-xl:is(:where(.peer)[data-variant=inset]~*){border-radius:calc(var(--radius) + 4px)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:shadow-sm:is(:where(.peer)[data-variant=inset]~*){--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}@media(min-width:48rem){.md\:peer-data-\[variant\=inset\]\:peer-data-\[state\=collapsed\]\:ml-2:is(:where(.peer)[data-variant=inset]~*):is(:where(.peer)[data-state=collapsed]~*){margin-left:calc(var(--spacing) * 2)}}@media(min-width:48rem){.md\:after\:hidden:after{content:var(--tw-content);display:none}}@media(min-width:64rem){.lg\:w-\[500px\]{width:500px}}@media(min-width:64rem){.lg\:w-\[600px\]{width:600px}}@media(min-width:64rem){.lg\:basis-1\/3{flex-basis:calc(1/3 * 100%)}}@media(min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-\[\.75fr_1fr\]{grid-template-columns:.75fr 1fr}}.dark\:border-input:is(.dark *){border-color:var(--input)}.dark\:bg-destructive\/60:is(.dark *){background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-destructive\/60:is(.dark *){background-color:color-mix(in oklab,var(--destructive) 60%,transparent)}}.dark\:bg-input\/30:is(.dark *){background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:bg-input\/30:is(.dark *){background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:bg-slate-800:is(.dark *){background-color:var(--color-slate-800)}.dark\:bg-slate-900:is(.dark *){background-color:var(--color-slate-900)}.dark\:text-muted-foreground:is(.dark *){color:var(--muted-foreground)}@media(hover:hover){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:var(--accent)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-accent\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--accent) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:hover\:bg-input\/50:is(.dark *):hover{background-color:color-mix(in oklab,var(--input) 50%,transparent)}}}@media(hover:hover){.dark\:hover\:text-accent-foreground:is(.dark *):hover{color:var(--accent-foreground)}}.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:focus-visible\:ring-destructive\/40:is(.dark *):focus-visible{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:aria-invalid\:ring-destructive\/40:is(.dark *)[aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[active\=true\]\:aria-invalid\:ring-destructive\/40:is(.dark *)[data-active=true][aria-invalid=true]{--tw-ring-color: color-mix(in oklab, var(--destructive) 40%, transparent)}}.dark\:data-\[state\=active\]\:border-input:is(.dark *)[data-state=active]{border-color:var(--input)}.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=active\]\:bg-input\/30:is(.dark *)[data-state=active]{background-color:color-mix(in oklab,var(--input) 30%,transparent)}}.dark\:data-\[state\=active\]\:text-foreground:is(.dark *)[data-state=active]{color:var(--foreground)}.dark\:data-\[state\=checked\]\:bg-primary:is(.dark *)[data-state=checked]{background-color:var(--primary)}.dark\:data-\[state\=checked\]\:bg-primary-foreground:is(.dark *)[data-state=checked]{background-color:var(--primary-foreground)}.dark\:data-\[state\=unchecked\]\:bg-foreground:is(.dark *)[data-state=unchecked]{background-color:var(--foreground)}.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:var(--input)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[state\=unchecked\]\:bg-input\/80:is(.dark *)[data-state=unchecked]{background-color:color-mix(in oklab,var(--input) 80%,transparent)}}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:is(.dark *)[data-variant=destructive]:focus{background-color:color-mix(in oklab,var(--destructive) 20%,transparent)}}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:var(--muted-foreground)}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:var(--border)}@supports (color: color-mix(in lab,red,red)){.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:color-mix(in oklab,var(--border) 50%,transparent)}}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:var(--border)}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-layer\]\:outline-hidden .recharts-layer{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector{fill:var(--muted)}.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:var(--muted)}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:var(--border)}.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-sector\]\:outline-hidden .recharts-sector{outline:2px solid transparent;outline-offset:2px}}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{--tw-outline-style: none;outline-style:none}@media(forced-colors:active){.\[\&_\.recharts-surface\]\:outline-hidden .recharts-surface{outline:2px solid transparent;outline-offset:2px}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--muted-foreground)}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:calc(var(--spacing) * 0)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:calc(var(--spacing) * 5)}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:calc(var(--spacing) * 12)}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-block:calc(var(--spacing) * 3)}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:calc(var(--spacing) * 5)}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:calc(var(--spacing) * 5)}.\[\&_p\]\:leading-relaxed p{--tw-leading: var(--leading-relaxed);line-height:var(--leading-relaxed)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:var(--muted-foreground)}.\[\&_tr\]\:border-b tr{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-style:var(--tw-border-style);border-width:0px}.\[\&\:\:-webkit-calendar-picker-indicator\]\:hidden::-webkit-calendar-picker-indicator{display:none}.\[\&\:\:-webkit-calendar-picker-indicator\]\:appearance-none::-webkit-calendar-picker-indicator{-webkit-appearance:none;-moz-appearance:none;appearance:none}.\[\&\:first-child\[data-selected\=true\]_button\]\:rounded-l-md:first-child[data-selected=true] button{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:calc(var(--spacing) * 0)}.\[\.border-b\]\:pb-6:is(.border-b){padding-bottom:calc(var(--spacing) * 6)}.\[\.border-t\]\:pt-6:is(.border-t){padding-top:calc(var(--spacing) * 6)}:is(.rtl\:\*\*\:\[\.rdp-button\\_next\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_next>svg){rotate:180deg}:is(.rtl\:\*\*\:\[\.rdp-button\\_previous\>svg\]\:rotate-180:where(:dir(rtl),[dir=rtl],[dir=rtl] *) *):is(.rdp-button_previous>svg){rotate:180deg}:is(.\*\:\[span\]\:last\:flex>*):is(span):last-child{display:flex}:is(.\*\:\[span\]\:last\:items-center>*):is(span):last-child{align-items:center}:is(.\*\:\[span\]\:last\:gap-2>*):is(span):last-child{gap:calc(var(--spacing) * 2)}:is(.data-\[variant\=destructive\]\:\*\:\[svg\]\:\!text-destructive[data-variant=destructive]>*):is(svg){color:var(--destructive)!important}.\[\&\:last-child\[data-selected\=true\]_button\]\:rounded-r-md:last-child[data-selected=true] button{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y: 2px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>div\]\:bg-blue-500>div{background-color:var(--color-blue-500)}.\[\&\>div\]\:bg-green-500>div{background-color:var(--color-green-500)}.\[\&\>div\]\:bg-orange-500>div{background-color:var(--color-orange-500)}.\[\&\>div\]\:bg-red-500>div{background-color:var(--color-red-500)}.\[\&\>div\]\:bg-yellow-500>div{background-color:var(--color-yellow-500)}.\[\&\>div\]\:bg-gradient-to-r>div{--tw-gradient-position: to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.\[\&\>div\]\:from-purple-500>div{--tw-gradient-from: var(--color-purple-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>div\]\:to-pink-500>div{--tw-gradient-to: var(--color-pink-500);--tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.\[\&\>span\]\:text-xs>span{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.\[\&\>span\]\:opacity-70>span{opacity:70%}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:size-3>svg{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:size-3\.5>svg{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.\[\&\>svg\]\:size-4>svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&\>svg\]\:h-2\.5>svg{height:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:h-3>svg{height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:w-2\.5>svg{width:calc(var(--spacing) * 2.5)}.\[\&\>svg\]\:w-3>svg{width:calc(var(--spacing) * 3)}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:translate-y-0\.5>svg{--tw-translate-y: calc(var(--spacing) * .5);translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>svg\]\:text-current>svg{color:currentcolor}.\[\&\>svg\]\:text-muted-foreground>svg{color:var(--muted-foreground)}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:var(--sidebar-accent-foreground)}.\[\&\>tr\]\:last\:border-b-0>tr:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{rotate:90deg}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{rotate:180deg}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:calc(var(--spacing) * -2)}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:calc(var(--spacing) * -2)}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-slot=card-content] .\[\[data-slot\=card-content\]_\&\]\:bg-transparent{background-color:transparent}[data-slot=popover-content] .\[\[data-slot\=popover-content\]_\&\]\:bg-transparent{background-color:transparent}@media(hover:hover){a.\[a\&\]\:hover\:bg-accent:hover{background-color:var(--accent)}}@media(hover:hover){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab,var(--destructive) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:var(--secondary)}@supports (color: color-mix(in lab,red,red)){a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:color-mix(in oklab,var(--secondary) 90%,transparent)}}}@media(hover:hover){a.\[a\&\]\:hover\:text-accent-foreground:hover{color:var(--accent-foreground)}}}@property --tw-animation-delay{syntax: "*"; inherits: false; initial-value: 0s;}@property --tw-animation-direction{syntax: "*"; inherits: false; initial-value: normal;}@property --tw-animation-duration{syntax: "*"; inherits: false;}@property --tw-animation-fill-mode{syntax: "*"; inherits: false; initial-value: none;}@property --tw-animation-iteration-count{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-enter-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-enter-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-opacity{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-rotate{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-scale{syntax: "*"; inherits: false; initial-value: 1;}@property --tw-exit-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-exit-translate-y{syntax: "*"; inherits: false; initial-value: 0;}:root{--background: oklch(1 0 0);--foreground: oklch(.145 0 0);--card: oklch(1 0 0);--card-foreground: oklch(.145 0 0);--popover: oklch(1 0 0);--popover-foreground: oklch(.145 0 0);--primary: oklch(67.35% .153 159.64);--primary-foreground: oklch(.985 0 0);--secondary: oklch(.97 0 0);--secondary-foreground: oklch(.205 0 0);--muted: oklch(.97 0 0);--muted-foreground: oklch(.556 0 0);--accent: oklch(.97 0 0);--accent-foreground: oklch(.205 0 0);--destructive: oklch(.577 .245 27.325);--destructive-foreground: oklch(.577 .245 27.325);--border: oklch(.922 0 0);--input: oklch(.922 0 0);--ring: oklch(.708 0 0);--chart-1: oklch(.646 .222 41.116);--chart-2: oklch(.6 .118 184.704);--chart-3: oklch(.398 .07 227.392);--chart-4: oklch(.828 .189 84.429);--chart-5: oklch(.769 .188 70.08);--radius: .625rem;--sidebar: oklch(.985 0 0);--sidebar-foreground: oklch(.145 0 0);--sidebar-primary: oklch(.205 0 0);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.97 0 0);--sidebar-accent-foreground: oklch(.205 0 0);--sidebar-border: oklch(.922 0 0);--sidebar-ring: oklch(.708 0 0)}.dark{--background: oklch(.145 0 0);--foreground: oklch(.985 0 0);--card: oklch(.145 0 0);--card-foreground: oklch(.985 0 0);--popover: oklch(.145 0 0);--popover-foreground: oklch(.985 0 0);--primary: oklch(88.18% .202 159.34);--primary-foreground: oklch(.205 0 0);--secondary: oklch(.269 0 0);--secondary-foreground: oklch(.985 0 0);--muted: oklch(.269 0 0);--muted-foreground: oklch(.708 0 0);--accent: oklch(.269 0 0);--accent-foreground: oklch(.985 0 0);--destructive: oklch(.396 .141 25.723);--destructive-foreground: oklch(.637 .237 25.331);--border: oklch(.269 0 0);--input: oklch(.269 0 0);--ring: oklch(.439 0 0);--chart-1: oklch(.488 .243 264.376);--chart-2: oklch(.696 .17 162.48);--chart-3: oklch(.769 .188 70.08);--chart-4: oklch(.627 .265 303.9);--chart-5: oklch(.645 .246 16.439);--sidebar: oklch(.205 0 0);--sidebar-foreground: oklch(.985 0 0);--sidebar-primary: oklch(.488 .243 264.376);--sidebar-primary-foreground: oklch(.985 0 0);--sidebar-accent: oklch(.269 0 0);--sidebar-accent-foreground: oklch(.985 0 0);--sidebar-border: oklch(.269 0 0);--sidebar-ring: oklch(.439 0 0)}@layer base{*{border-color:var(--border);outline-color:var(--ring)}@supports (color: color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}}body{background-color:var(--background);color:var(--foreground)}}@property --tw-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-z{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-rotate-x{syntax: "*"; inherits: false;}@property --tw-rotate-y{syntax: "*"; inherits: false;}@property --tw-rotate-z{syntax: "*"; inherits: false;}@property --tw-skew-x{syntax: "*"; inherits: false;}@property --tw-skew-y{syntax: "*"; inherits: false;}@property --tw-space-y-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-space-x-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-gradient-position{syntax: "*"; inherits: false;}@property --tw-gradient-from{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-via{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-to{syntax: "<color>"; inherits: false; initial-value: #0000;}@property --tw-gradient-stops{syntax: "*"; inherits: false;}@property --tw-gradient-via-stops{syntax: "*"; inherits: false;}@property --tw-gradient-from-position{syntax: "<length-percentage>"; inherits: false; initial-value: 0%;}@property --tw-gradient-via-position{syntax: "<length-percentage>"; inherits: false; initial-value: 50%;}@property --tw-gradient-to-position{syntax: "<length-percentage>"; inherits: false; initial-value: 100%;}@property --tw-leading{syntax: "*"; inherits: false;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-tracking{syntax: "*"; inherits: false;}@property --tw-ordinal{syntax: "*"; inherits: false;}@property --tw-slashed-zero{syntax: "*"; inherits: false;}@property --tw-numeric-figure{syntax: "*"; inherits: false;}@property --tw-numeric-spacing{syntax: "*"; inherits: false;}@property --tw-numeric-fraction{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-outline-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@property --tw-content{syntax: "*"; initial-value: ""; inherits: false;}@keyframes pulse{50%{opacity:.5}}@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))}}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height,var(--bits-accordion-content-height,var(--reka-accordion-content-height,var(--kb-accordion-content-height,auto))))}to{height:0}}@keyframes caret-blink{0%,70%,to{opacity:1}20%,50%{opacity:0}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x: 0;--tw-translate-y: 0;--tw-translate-z: 0;--tw-rotate-x: initial;--tw-rotate-y: initial;--tw-rotate-z: initial;--tw-skew-x: initial;--tw-skew-y: initial;--tw-space-y-reverse: 0;--tw-space-x-reverse: 0;--tw-border-style: solid;--tw-gradient-position: initial;--tw-gradient-from: #0000;--tw-gradient-via: #0000;--tw-gradient-to: #0000;--tw-gradient-stops: initial;--tw-gradient-via-stops: initial;--tw-gradient-from-position: 0%;--tw-gradient-via-position: 50%;--tw-gradient-to-position: 100%;--tw-leading: initial;--tw-font-weight: initial;--tw-tracking: initial;--tw-ordinal: initial;--tw-slashed-zero: initial;--tw-numeric-figure: initial;--tw-numeric-spacing: initial;--tw-numeric-fraction: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-outline-style: solid;--tw-duration: initial;--tw-ease: initial;--tw-content: "";--tw-animation-delay: 0s;--tw-animation-direction: normal;--tw-animation-duration: initial;--tw-animation-fill-mode: none;--tw-animation-iteration-count: 1;--tw-enter-opacity: 1;--tw-enter-rotate: 0;--tw-enter-scale: 1;--tw-enter-translate-x: 0;--tw-enter-translate-y: 0;--tw-exit-opacity: 1;--tw-exit-rotate: 0;--tw-exit-scale: 1;--tw-exit-translate-x: 0;--tw-exit-translate-y: 0}}}/*! tailwindcss v4.1.10 | MIT License | https://tailwindcss.com *//*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-800:oklch(44.4% .177 26.899);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-gray-50:oklch(98.5% .002 247.839);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-900:oklch(21% .034 264.665);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-6xl:3.75rem;--text-6xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--animate-spin:spin 1s linear infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}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;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--border);outline-color:var(--ring)}@supports (color:color-mix(in lab,red,red)){*{outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}}html,body{height:100%;margin:0;padding:0}body{background-color:var(--background);color:var(--foreground);font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif}#root{height:100%}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0;border-radius:4px}::-webkit-scrollbar-thumb{background-color:#ffffff26;background-clip:content-box;border:2px solid #0000;border-radius:4px;transition:background-color .2s}::-webkit-scrollbar-thumb:hover{background-color:#ffffff40}::-webkit-scrollbar-thumb:active{background-color:#ffffff59}*{scrollbar-width:thin;scrollbar-color:#ffffff26 transparent}@media(max-width:768px){*{scrollbar-width:none}::-webkit-scrollbar{display:none}}}@layer components;@layer utilities{.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.end{inset-inline-end:var(--spacing)}.top-1\/2{top:50%}.left-3{left:calc(var(--spacing) * 3)}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mt-16{margin-top:calc(var(--spacing) * 16)}.mt-auto{margin-top:auto}.mr-1{margin-right:calc(var(--spacing) * 1)}.mr-1\.5{margin-right:calc(var(--spacing) * 1.5)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-3{height:calc(var(--spacing) * 3)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-12{height:calc(var(--spacing) * 12)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-48{height:calc(var(--spacing) * 48)}.h-64{height:calc(var(--spacing) * 64)}.h-full{height:100%}.h-screen{height:100vh}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-48{max-height:calc(var(--spacing) * 48)}.max-h-60{max-height:calc(var(--spacing) * 60)}.max-h-\[90vh\]{max-height:90vh}.min-h-screen{min-height:100vh}.w-3{width:calc(var(--spacing) * 3)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-12{width:calc(var(--spacing) * 12)}.w-14{width:calc(var(--spacing) * 14)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[150px\]{max-width:150px}.max-w-md{max-width:var(--container-md)}.min-w-0{min-width:calc(var(--spacing) * 0)}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-8>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 8) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-y-reverse)))}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-destructive\/50{border-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.border-destructive\/50{border-color:color-mix(in oklab,var(--destructive) 50%,transparent)}}.border-gray-300{border-color:var(--color-gray-300)}.border-input{border-color:var(--input)}.border-primary\/20{border-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.border-primary\/20{border-color:color-mix(in oklab,var(--primary) 20%,transparent)}}.border-sidebar-border{border-color:var(--sidebar-border)}.bg-background,.bg-background\/80{background-color:var(--background)}@supports (color:color-mix(in lab,red,red)){.bg-background\/80{background-color:color-mix(in oklab,var(--background) 80%,transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab,red,red)){.bg-black\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}}.bg-blue-600{background-color:var(--color-blue-600)}.bg-card{background-color:var(--card)}.bg-destructive\/10{background-color:var(--destructive)}@supports (color:color-mix(in lab,red,red)){.bg-destructive\/10{background-color:color-mix(in oklab,var(--destructive) 10%,transparent)}}.bg-gray-50{background-color:var(--color-gray-50)}.bg-gray-900{background-color:var(--color-gray-900)}.bg-green-500\/10{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.bg-green-500\/10{background-color:color-mix(in oklab,var(--color-green-500) 10%,transparent)}}.bg-muted{background-color:var(--muted)}.bg-primary,.bg-primary\/10{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.bg-primary\/10{background-color:color-mix(in oklab,var(--primary) 10%,transparent)}}.bg-red-50{background-color:var(--color-red-50)}.bg-red-100{background-color:var(--color-red-100)}.bg-red-500\/10{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.bg-red-500\/10{background-color:color-mix(in oklab,var(--color-red-500) 10%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-sidebar{background-color:var(--sidebar)}.bg-sidebar-accent,.bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent) 50%,transparent)}}.bg-sidebar-border{background-color:var(--sidebar-border)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-t{--tw-gradient-position:to top in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-primary\/10{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/10{--tw-gradient-from:color-mix(in oklab, var(--primary) 10%, transparent)}}.from-primary\/10{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-primary\/20{--tw-gradient-from:var(--primary)}@supports (color:color-mix(in lab,red,red)){.from-primary\/20{--tw-gradient-from:color-mix(in oklab, var(--primary) 20%, transparent)}}.from-primary\/20{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-background{--tw-gradient-via:var(--background);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-background\/95{--tw-gradient-via:var(--background)}@supports (color:color-mix(in lab,red,red)){.via-background\/95{--tw-gradient-via:color-mix(in oklab, var(--background) 95%, transparent)}}.via-background\/95{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-background{--tw-gradient-to:var(--background);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing) * 0)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-0{padding-inline:calc(var(--spacing) * 0)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-8{padding-inline:calc(var(--spacing) * 8)}.px-\[0\.3rem\]{padding-inline:.3rem}.py-1{padding-block:calc(var(--spacing) * 1)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-16{padding-block:calc(var(--spacing) * 16)}.py-\[0\.2rem\]{padding-block:.2rem}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-8{padding-top:calc(var(--spacing) * 8)}.pr-1{padding-right:calc(var(--spacing) * 1)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-9{padding-left:calc(var(--spacing) * 9)}.text-center{text-align:center}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-6xl{font-size:var(--text-6xl);line-height:var(--tw-leading,var(--text-6xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.whitespace-nowrap{white-space:nowrap}.text-blue-500{color:var(--color-blue-500)}.text-blue-600{color:var(--color-blue-600)}.text-destructive{color:var(--destructive)}.text-foreground{color:var(--foreground)}.text-gray-500{color:var(--color-gray-500)}.text-gray-600{color:var(--color-gray-600)}.text-gray-700{color:var(--color-gray-700)}.text-gray-900{color:var(--color-gray-900)}.text-green-500{color:var(--color-green-500)}.text-muted-foreground{color:var(--muted-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-red-400{color:var(--color-red-400)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-800{color:var(--color-red-800)}.text-sidebar-foreground,.text-sidebar-foreground\/40{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/40{color:color-mix(in oklab,var(--sidebar-foreground) 40%,transparent)}}.text-sidebar-foreground\/60{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/60{color:color-mix(in oklab,var(--sidebar-foreground) 60%,transparent)}}.text-sidebar-foreground\/70{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.text-sidebar-foreground\/70{color:color-mix(in oklab,var(--sidebar-foreground) 70%,transparent)}}.text-white{color:var(--color-white)}.text-yellow-500{color:var(--color-yellow-500)}.lowercase{text-transform:lowercase}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.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(var(--blur-sm));-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:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}@media(hover:hover){.group-hover\:translate-x-1:is(:where(.group):hover *){--tw-translate-x:calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.placeholder\:text-sidebar-foreground\/50::placeholder{color:var(--sidebar-foreground)}@supports (color:color-mix(in lab,red,red)){.placeholder\:text-sidebar-foreground\/50::placeholder{color:color-mix(in oklab,var(--sidebar-foreground) 50%,transparent)}}@media(hover:hover){.hover\:border-primary:hover{border-color:var(--primary)}.hover\:bg-accent:hover{background-color:var(--accent)}.hover\:bg-blue-500\/10:hover{background-color:#3080ff1a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-blue-500\/10:hover{background-color:color-mix(in oklab,var(--color-blue-500) 10%,transparent)}}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-gray-50:hover{background-color:var(--color-gray-50)}.hover\:bg-gray-500\/10:hover{background-color:#6a72821a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-gray-500\/10:hover{background-color:color-mix(in oklab,var(--color-gray-500) 10%,transparent)}}.hover\:bg-green-500\/10:hover{background-color:#00c7581a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/10:hover{background-color:color-mix(in oklab,var(--color-green-500) 10%,transparent)}}.hover\:bg-green-500\/20:hover{background-color:#00c75833}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-500\/20:hover{background-color:color-mix(in oklab,var(--color-green-500) 20%,transparent)}}.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab,var(--primary) 90%,transparent)}}.hover\:bg-red-500\/10:hover{background-color:#fb2c361a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/10:hover{background-color:color-mix(in oklab,var(--color-red-500) 10%,transparent)}}.hover\:bg-red-500\/20:hover{background-color:#fb2c3633}@supports (color:color-mix(in lab,red,red)){.hover\:bg-red-500\/20:hover{background-color:color-mix(in oklab,var(--color-red-500) 20%,transparent)}}.hover\:bg-red-700:hover{background-color:var(--color-red-700)}.hover\:bg-sidebar:hover{background-color:var(--sidebar)}.hover\:bg-sidebar-accent:hover,.hover\:bg-sidebar-accent\/30:hover{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.hover\:bg-sidebar-accent\/30:hover{background-color:color-mix(in oklab,var(--sidebar-accent) 30%,transparent)}}.hover\:bg-transparent:hover{background-color:#0000}.hover\:bg-yellow-500\/10:hover{background-color:#edb2001a}@supports (color:color-mix(in lab,red,red)){.hover\:bg-yellow-500\/10:hover{background-color:color-mix(in oklab,var(--color-yellow-500) 10%,transparent)}}.hover\:text-blue-400:hover{color:var(--color-blue-400)}.hover\:text-foreground:hover{color:var(--foreground)}.hover\:text-gray-300:hover{color:var(--color-gray-300)}.hover\:text-green-400:hover{color:var(--color-green-400)}.hover\:text-primary:hover{color:var(--primary)}.hover\:text-red-400:hover{color:var(--color-red-400)}.hover\:text-sidebar-foreground:hover{color:var(--sidebar-foreground)}.hover\:text-yellow-400:hover{color:var(--color-yellow-400)}.hover\:shadow-lg:hover{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\:shadow-black\/10:hover{--tw-shadow-color:#0000001a}@supports (color:color-mix(in lab,red,red)){.hover\:shadow-black\/10:hover{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-black) 10%, transparent) var(--tw-shadow-alpha), transparent)}}}.focus\:border-sidebar-border:focus{border-color:var(--sidebar-border)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus\:ring-blue-500:focus{--tw-ring-color:var(--color-blue-500)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:opacity-50:disabled{opacity:.5}@media(min-width:40rem){.sm\:w-auto{width:auto}.sm\:max-w-md{max-width:var(--container-md)}.sm\:gap-0{gap:calc(var(--spacing) * 0)}}@media(min-width:48rem){.md\:flex{display:flex}.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\:items-center{align-items:center}.md\:items-start{align-items:flex-start}.md\:justify-between{justify-content:space-between}}@media(min-width:64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(min-width:80rem){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(prefers-color-scheme:dark){.dark\:bg-red-600{background-color:var(--color-red-600)}.dark\:bg-sidebar-accent\/50{background-color:var(--sidebar-accent)}@supports (color:color-mix(in lab,red,red)){.dark\:bg-sidebar-accent\/50{background-color:color-mix(in oklab,var(--sidebar-accent) 50%,transparent)}}.dark\:text-gray-200{color:var(--color-gray-200)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-red-500{color:var(--color-red-500)}.dark\:placeholder\:text-gray-400::placeholder{color:var(--color-gray-400)}@media(hover:hover){.dark\:hover\:bg-red-700:hover{background-color:var(--color-red-700)}.dark\:hover\:bg-sidebar:hover{background-color:var(--sidebar)}.dark\:hover\:bg-sidebar-accent:hover{background-color:var(--sidebar-accent)}.dark\:hover\:text-gray-400:hover{color:var(--color-gray-400)}}}.scrollbar-hidden{scrollbar-width:none!important;-ms-overflow-style:none!important}.scrollbar-hidden::-webkit-scrollbar{display:none!important}.scrollbar-thin::-webkit-scrollbar{width:6px!important;height:6px!important}.scrollbar-thin::-webkit-scrollbar-thumb{background-color:#9ca3af4d!important;border-radius:3px!important}.scrollbar-thin::-webkit-scrollbar-thumb:hover{background-color:#9ca3af80!important}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}diff --git a/manager/dist/assets/index-LD46dRLh.js b/manager/dist/assets/index-LD46dRLh.jsnew file mode 100644index 0000000..88252c6--- /dev/null+++ b/manager/dist/assets/index-LD46dRLh.js@@ -0,0 +1,350 @@+var EC=Object.defineProperty;var _C=(t,n,r)=>n in t?EC(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r;var cb=(t,n,r)=>_C(t,typeof n!="symbol"?n+"":n,r);function CC(t,n){for(var r=0;r<n.length;r++){const s=n[r];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in t)){const c=Object.getOwnPropertyDescriptor(s,i);c&&Object.defineProperty(t,i,c.get?c:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=r(i);fetch(i.href,c)}})();function v0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var um={exports:{}},Hi={};/**+ * @license React+ * react-jsx-runtime.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var ub;function NC(){if(ub)return Hi;ub=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,i,c){var u=null;if(c!==void 0&&(u=""+c),i.key!==void 0&&(u=""+i.key),"key"in i){c={};for(var f in i)f!=="key"&&(c[f]=i[f])}else c=i;return i=c.ref,{$$typeof:t,type:s,key:u,ref:i!==void 0?i:null,props:c}}return Hi.Fragment=n,Hi.jsx=r,Hi.jsxs=r,Hi}var db;function RC(){return db||(db=1,um.exports=NC()),um.exports}var h=RC(),dm={exports:{}},Ve={};/**+ * @license React+ * react.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var fb;function AC(){if(fb)return Ve;fb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),w=Symbol.iterator;function C(j){return j===null||typeof j!="object"?null:(j=w&&j[w]||j["@@iterator"],typeof j=="function"?j:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,E={};function R(j,X,L){this.props=j,this.context=X,this.refs=E,this.updater=L||S}R.prototype.isReactComponent={},R.prototype.setState=function(j,X){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,X,"setState")},R.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function k(){}k.prototype=R.prototype;function A(j,X,L){this.props=j,this.context=X,this.refs=E,this.updater=L||S}var D=A.prototype=new k;D.constructor=A,_(D,R.prototype),D.isPureReactComponent=!0;var H=Array.isArray;function $(){}var U={H:null,A:null,T:null,S:null},F=Object.prototype.hasOwnProperty;function de(j,X,L){var Y=L.ref;return{$$typeof:t,type:j,key:X,ref:Y!==void 0?Y:null,props:L}}function fe(j,X){return de(j.type,X,j.props)}function me(j){return typeof j=="object"&&j!==null&&j.$$typeof===t}function se(j){var X={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(L){return X[L]})}var G=/\/+/g;function he(j,X){return typeof j=="object"&&j!==null&&j.key!=null?se(""+j.key):X.toString(36)}function ve(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then($,$):(j.status="pending",j.then(function(X){j.status==="pending"&&(j.status="fulfilled",j.value=X)},function(X){j.status==="pending"&&(j.status="rejected",j.reason=X)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function T(j,X,L,Y,J){var ie=typeof j;(ie==="undefined"||ie==="boolean")&&(j=null);var pe=!1;if(j===null)pe=!0;else switch(ie){case"bigint":case"string":case"number":pe=!0;break;case"object":switch(j.$$typeof){case t:case n:pe=!0;break;case y:return pe=j._init,T(pe(j._payload),X,L,Y,J)}}if(pe)return J=J(j),pe=Y===""?"."+he(j,0):Y,H(J)?(L="",pe!=null&&(L=pe.replace(G,"$&/")+"/"),T(J,X,L,"",function(Re){return Re})):J!=null&&(me(J)&&(J=fe(J,L+(J.key==null||j&&j.key===J.key?"":(""+J.key).replace(G,"$&/")+"/")+pe)),X.push(J)),1;pe=0;var Q=Y===""?".":Y+":";if(H(j))for(var oe=0;oe<j.length;oe++)Y=j[oe],ie=Q+he(Y,oe),pe+=T(Y,X,L,ie,J);else if(oe=C(j),typeof oe=="function")for(j=oe.call(j),oe=0;!(Y=j.next()).done;)Y=Y.value,ie=Q+he(Y,oe++),pe+=T(Y,X,L,ie,J);else if(ie==="object"){if(typeof j.then=="function")return T(ve(j),X,L,Y,J);throw X=String(j),Error("Objects are not valid as a React child (found: "+(X==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":X)+"). If you meant to render a collection of children, use an array instead.")}return pe}function K(j,X,L){if(j==null)return j;var Y=[],J=0;return T(j,Y,"","",function(ie){return X.call(L,ie,J++)}),Y}function te(j){if(j._status===-1){var X=j._result;X=X(),X.then(function(L){(j._status===0||j._status===-1)&&(j._status=1,j._result=L)},function(L){(j._status===0||j._status===-1)&&(j._status=2,j._result=L)}),j._status===-1&&(j._status=0,j._result=X)}if(j._status===1)return j._result.default;throw j._result}var le=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var X=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(X))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},ne={map:K,forEach:function(j,X,L){K(j,function(){X.apply(this,arguments)},L)},count:function(j){var X=0;return K(j,function(){X++}),X},toArray:function(j){return K(j,function(X){return X})||[]},only:function(j){if(!me(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return Ve.Activity=v,Ve.Children=ne,Ve.Component=R,Ve.Fragment=r,Ve.Profiler=i,Ve.PureComponent=A,Ve.StrictMode=s,Ve.Suspense=g,Ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=U,Ve.__COMPILER_RUNTIME={__proto__:null,c:function(j){return U.H.useMemoCache(j)}},Ve.cache=function(j){return function(){return j.apply(null,arguments)}},Ve.cacheSignal=function(){return null},Ve.cloneElement=function(j,X,L){if(j==null)throw Error("The argument must be a React element, but you passed "+j+".");var Y=_({},j.props),J=j.key;if(X!=null)for(ie in X.key!==void 0&&(J=""+X.key),X)!F.call(X,ie)||ie==="key"||ie==="__self"||ie==="__source"||ie==="ref"&&X.ref===void 0||(Y[ie]=X[ie]);var ie=arguments.length-2;if(ie===1)Y.children=L;else if(1<ie){for(var pe=Array(ie),Q=0;Q<ie;Q++)pe[Q]=arguments[Q+2];Y.children=pe}return de(j.type,J,Y)},Ve.createContext=function(j){return j={$$typeof:u,_currentValue:j,_currentValue2:j,_threadCount:0,Provider:null,Consumer:null},j.Provider=j,j.Consumer={$$typeof:c,_context:j},j},Ve.createElement=function(j,X,L){var Y,J={},ie=null;if(X!=null)for(Y in X.key!==void 0&&(ie=""+X.key),X)F.call(X,Y)&&Y!=="key"&&Y!=="__self"&&Y!=="__source"&&(J[Y]=X[Y]);var pe=arguments.length-2;if(pe===1)J.children=L;else if(1<pe){for(var Q=Array(pe),oe=0;oe<pe;oe++)Q[oe]=arguments[oe+2];J.children=Q}if(j&&j.defaultProps)for(Y in pe=j.defaultProps,pe)J[Y]===void 0&&(J[Y]=pe[Y]);return de(j,ie,J)},Ve.createRef=function(){return{current:null}},Ve.forwardRef=function(j){return{$$typeof:f,render:j}},Ve.isValidElement=me,Ve.lazy=function(j){return{$$typeof:y,_payload:{_status:-1,_result:j},_init:te}},Ve.memo=function(j,X){return{$$typeof:p,type:j,compare:X===void 0?null:X}},Ve.startTransition=function(j){var X=U.T,L={};U.T=L;try{var Y=j(),J=U.S;J!==null&&J(L,Y),typeof Y=="object"&&Y!==null&&typeof Y.then=="function"&&Y.then($,le)}catch(ie){le(ie)}finally{X!==null&&L.types!==null&&(X.types=L.types),U.T=X}},Ve.unstable_useCacheRefresh=function(){return U.H.useCacheRefresh()},Ve.use=function(j){return U.H.use(j)},Ve.useActionState=function(j,X,L){return U.H.useActionState(j,X,L)},Ve.useCallback=function(j,X){return U.H.useCallback(j,X)},Ve.useContext=function(j){return U.H.useContext(j)},Ve.useDebugValue=function(){},Ve.useDeferredValue=function(j,X){return U.H.useDeferredValue(j,X)},Ve.useEffect=function(j,X){return U.H.useEffect(j,X)},Ve.useEffectEvent=function(j){return U.H.useEffectEvent(j)},Ve.useId=function(){return U.H.useId()},Ve.useImperativeHandle=function(j,X,L){return U.H.useImperativeHandle(j,X,L)},Ve.useInsertionEffect=function(j,X){return U.H.useInsertionEffect(j,X)},Ve.useLayoutEffect=function(j,X){return U.H.useLayoutEffect(j,X)},Ve.useMemo=function(j,X){return U.H.useMemo(j,X)},Ve.useOptimistic=function(j,X){return U.H.useOptimistic(j,X)},Ve.useReducer=function(j,X,L){return U.H.useReducer(j,X,L)},Ve.useRef=function(j){return U.H.useRef(j)},Ve.useState=function(j){return U.H.useState(j)},Ve.useSyncExternalStore=function(j,X,L){return U.H.useSyncExternalStore(j,X,L)},Ve.useTransition=function(){return U.H.useTransition()},Ve.version="19.2.4",Ve}var mb;function wh(){return mb||(mb=1,dm.exports=AC()),dm.exports}var b=wh();const ae=v0(b),Nu=CC({__proto__:null,default:ae},[b]);var fm={exports:{}},Vi={},mm={exports:{}},hm={};/**+ * @license React+ * scheduler.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var hb;function TC(){return hb||(hb=1,(function(t){function n(T,K){var te=T.length;T.push(K);e:for(;0<te;){var le=te-1>>>1,ne=T[le];if(0<i(ne,K))T[le]=K,T[te]=ne,te=le;else break e}}function r(T){return T.length===0?null:T[0]}function s(T){if(T.length===0)return null;var K=T[0],te=T.pop();if(te!==K){T[0]=te;e:for(var le=0,ne=T.length,j=ne>>>1;le<j;){var X=2*(le+1)-1,L=T[X],Y=X+1,J=T[Y];if(0>i(L,te))Y<ne&&0>i(J,L)?(T[le]=J,T[Y]=te,le=Y):(T[le]=L,T[X]=te,le=X);else if(Y<ne&&0>i(J,te))T[le]=J,T[Y]=te,le=Y;else break e}}return K}function i(T,K){var te=T.sortIndex-K.sortIndex;return te!==0?te:T.id-K.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;t.unstable_now=function(){return c.now()}}else{var u=Date,f=u.now();t.unstable_now=function(){return u.now()-f}}var g=[],p=[],y=1,v=null,w=3,C=!1,S=!1,_=!1,E=!1,R=typeof setTimeout=="function"?setTimeout:null,k=typeof clearTimeout=="function"?clearTimeout:null,A=typeof setImmediate<"u"?setImmediate:null;function D(T){for(var K=r(p);K!==null;){if(K.callback===null)s(p);else if(K.startTime<=T)s(p),K.sortIndex=K.expirationTime,n(g,K);else break;K=r(p)}}function H(T){if(_=!1,D(T),!S)if(r(g)!==null)S=!0,$||($=!0,se());else{var K=r(p);K!==null&&ve(H,K.startTime-T)}}var $=!1,U=-1,F=5,de=-1;function fe(){return E?!0:!(t.unstable_now()-de<F)}function me(){if(E=!1,$){var T=t.unstable_now();de=T;var K=!0;try{e:{S=!1,_&&(_=!1,k(U),U=-1),C=!0;var te=w;try{t:{for(D(T),v=r(g);v!==null&&!(v.expirationTime>T&&fe());){var le=v.callback;if(typeof le=="function"){v.callback=null,w=v.priorityLevel;var ne=le(v.expirationTime<=T);if(T=t.unstable_now(),typeof ne=="function"){v.callback=ne,D(T),K=!0;break t}v===r(g)&&s(g),D(T)}else s(g);v=r(g)}if(v!==null)K=!0;else{var j=r(p);j!==null&&ve(H,j.startTime-T),K=!1}}break e}finally{v=null,w=te,C=!1}K=void 0}}finally{K?se():$=!1}}}var se;if(typeof A=="function")se=function(){A(me)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,he=G.port2;G.port1.onmessage=me,se=function(){he.postMessage(null)}}else se=function(){R(me,0)};function ve(T,K){U=R(function(){T(t.unstable_now())},K)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(T){T.callback=null},t.unstable_forceFrameRate=function(T){0>T||125<T?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):F=0<T?Math.floor(1e3/T):5},t.unstable_getCurrentPriorityLevel=function(){return w},t.unstable_next=function(T){switch(w){case 1:case 2:case 3:var K=3;break;default:K=w}var te=w;w=K;try{return T()}finally{w=te}},t.unstable_requestPaint=function(){E=!0},t.unstable_runWithPriority=function(T,K){switch(T){case 1:case 2:case 3:case 4:case 5:break;default:T=3}var te=w;w=T;try{return K()}finally{w=te}},t.unstable_scheduleCallback=function(T,K,te){var le=t.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?le+te:le):te=le,T){case 1:var ne=-1;break;case 2:ne=250;break;case 5:ne=1073741823;break;case 4:ne=1e4;break;default:ne=5e3}return ne=te+ne,T={id:y++,callback:K,priorityLevel:T,startTime:te,expirationTime:ne,sortIndex:-1},te>le?(T.sortIndex=te,n(p,T),r(g)===null&&T===r(p)&&(_?(k(U),U=-1):_=!0,ve(H,te-le))):(T.sortIndex=ne,n(g,T),S||C||(S=!0,$||($=!0,se()))),T},t.unstable_shouldYield=fe,t.unstable_wrapCallback=function(T){var K=w;return function(){var te=w;w=K;try{return T.apply(this,arguments)}finally{w=te}}}})(hm)),hm}var pb;function OC(){return pb||(pb=1,mm.exports=TC()),mm.exports}var pm={exports:{}},fn={};/**+ * @license React+ * react-dom.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var gb;function jC(){if(gb)return fn;gb=1;var t=wh();function n(g){var p="https://react.dev/errors/"+g;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var y=2;y<arguments.length;y++)p+="&args[]="+encodeURIComponent(arguments[y])}return"Minified React error #"+g+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(){}var s={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},i=Symbol.for("react.portal");function c(g,p,y){var v=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:v==null?null:""+v,children:g,containerInfo:p,implementation:y}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(g,p){if(g==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return fn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,fn.createPortal=function(g,p){var y=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(n(299));return c(g,p,null,y)},fn.flushSync=function(g){var p=u.T,y=s.p;try{if(u.T=null,s.p=2,g)return g()}finally{u.T=p,s.p=y,s.d.f()}},fn.preconnect=function(g,p){typeof g=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,s.d.C(g,p))},fn.prefetchDNS=function(g){typeof g=="string"&&s.d.D(g)},fn.preinit=function(g,p){if(typeof g=="string"&&p&&typeof p.as=="string"){var y=p.as,v=f(y,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,C=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;y==="style"?s.d.S(g,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:v,integrity:w,fetchPriority:C}):y==="script"&&s.d.X(g,{crossOrigin:v,integrity:w,fetchPriority:C,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},fn.preinitModule=function(g,p){if(typeof g=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var y=f(p.as,p.crossOrigin);s.d.M(g,{crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&s.d.M(g)},fn.preload=function(g,p){if(typeof g=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var y=p.as,v=f(y,p.crossOrigin);s.d.L(g,y,{crossOrigin:v,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},fn.preloadModule=function(g,p){if(typeof g=="string")if(p){var y=f(p.as,p.crossOrigin);s.d.m(g,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:y,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else s.d.m(g)},fn.requestFormReset=function(g){s.d.r(g)},fn.unstable_batchedUpdates=function(g,p){return g(p)},fn.useFormState=function(g,p,y){return u.H.useFormState(g,p,y)},fn.useFormStatus=function(){return u.H.useHostTransitionStatus()},fn.version="19.2.4",fn}var vb;function y0(){if(vb)return pm.exports;vb=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),pm.exports=jC(),pm.exports}/**+ * @license React+ * react-dom-client.production.js+ *+ * Copyright (c) Meta Platforms, Inc. and affiliates.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ */var yb;function kC(){if(yb)return Vi;yb=1;var t=OC(),n=wh(),r=y0();function s(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var o=2;o<arguments.length;o++)a+="&args[]="+encodeURIComponent(arguments[o])}return"Minified React error #"+e+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function c(e){var a=e,o=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(o=a.return),e=a.return;while(e)}return a.tag===3?o:null}function u(e){if(e.tag===13){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function f(e){if(e.tag===31){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function g(e){if(c(e)!==e)throw Error(s(188))}function p(e){var a=e.alternate;if(!a){if(a=c(e),a===null)throw Error(s(188));return a!==e?null:e}for(var o=e,l=a;;){var d=o.return;if(d===null)break;var m=d.alternate;if(m===null){if(l=d.return,l!==null){o=l;continue}break}if(d.child===m.child){for(m=d.child;m;){if(m===o)return g(d),e;if(m===l)return g(d),a;m=m.sibling}throw Error(s(188))}if(o.return!==l.return)o=d,l=m;else{for(var x=!1,N=d.child;N;){if(N===o){x=!0,o=d,l=m;break}if(N===l){x=!0,l=d,o=m;break}N=N.sibling}if(!x){for(N=m.child;N;){if(N===o){x=!0,o=m,l=d;break}if(N===l){x=!0,l=m,o=d;break}N=N.sibling}if(!x)throw Error(s(189))}}if(o.alternate!==l)throw Error(s(190))}if(o.tag!==3)throw Error(s(188));return o.stateNode.current===o?e:a}function y(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=y(e),a!==null)return a;e=e.sibling}return null}var v=Object.assign,w=Symbol.for("react.element"),C=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),_=Symbol.for("react.fragment"),E=Symbol.for("react.strict_mode"),R=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),A=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),H=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),U=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),de=Symbol.for("react.activity"),fe=Symbol.for("react.memo_cache_sentinel"),me=Symbol.iterator;function se(e){return e===null||typeof e!="object"?null:(e=me&&e[me]||e["@@iterator"],typeof e=="function"?e:null)}var G=Symbol.for("react.client.reference");function he(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===G?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case _:return"Fragment";case R:return"Profiler";case E:return"StrictMode";case H:return"Suspense";case $:return"SuspenseList";case de:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case S:return"Portal";case A:return e.displayName||"Context";case k:return(e._context.displayName||"Context")+".Consumer";case D:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case U:return a=e.displayName||null,a!==null?a:he(e.type)||"Memo";case F:a=e._payload,e=e._init;try{return he(e(a))}catch{}}return null}var ve=Array.isArray,T=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te={pending:!1,data:null,method:null,action:null},le=[],ne=-1;function j(e){return{current:e}}function X(e){0>ne||(e.current=le[ne],le[ne]=null,ne--)}function L(e,a){ne++,le[ne]=e.current,e.current=a}var Y=j(null),J=j(null),ie=j(null),pe=j(null);function Q(e,a){switch(L(ie,a),L(J,e),L(Y,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?ky(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=ky(a),e=My(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}X(Y),L(Y,e)}function oe(){X(Y),X(J),X(ie)}function Re(e){e.memoizedState!==null&&L(pe,e);var a=Y.current,o=My(a,e.type);a!==o&&(L(J,e),L(Y,o))}function et(e){J.current===e&&(X(Y),X(J)),pe.current===e&&(X(pe),Li._currentValue=te)}var Me,ze;function be(e){if(Me===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);Me=a&&a[1]||"",ze=-1<o.stack.indexOf(`+ at`)?" (<anonymous>)":-1<o.stack.indexOf("@")?"@unknown:0:0":""}return`+`+Me+e+ze}var je=!1;function at(e,a){if(!e||je)return"";je=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var l={DetermineComponentFrameRoot:function(){try{if(a){var ue=function(){throw Error()};if(Object.defineProperty(ue.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ue,[])}catch(ee){var Z=ee}Reflect.construct(e,[],ue)}else{try{ue.call()}catch(ee){Z=ee}e.call(ue.prototype)}}else{try{throw Error()}catch(ee){Z=ee}(ue=e())&&typeof ue.catch=="function"&&ue.catch(function(){})}}catch(ee){if(ee&&Z&&typeof ee.stack=="string")return[ee.stack,Z.stack]}return[null,null]}};l.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var d=Object.getOwnPropertyDescriptor(l.DetermineComponentFrameRoot,"name");d&&d.configurable&&Object.defineProperty(l.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var m=l.DetermineComponentFrameRoot(),x=m[0],N=m[1];if(x&&N){var M=x.split(`+`),q=N.split(`+`);for(d=l=0;l<M.length&&!M[l].includes("DetermineComponentFrameRoot");)l++;for(;d<q.length&&!q[d].includes("DetermineComponentFrameRoot");)d++;if(l===M.length||d===q.length)for(l=M.length-1,d=q.length-1;1<=l&&0<=d&&M[l]!==q[d];)d--;for(;1<=l&&0<=d;l--,d--)if(M[l]!==q[d]){if(l!==1||d!==1)do if(l--,d--,0>d||M[l]!==q[d]){var re=`+`+M[l].replace(" at new "," at ");return e.displayName&&re.includes("<anonymous>")&&(re=re.replace("<anonymous>",e.displayName)),re}while(1<=l&&0<=d);break}}}finally{je=!1,Error.prepareStackTrace=o}return(o=e?e.displayName||e.name:"")?be(o):""}function ht(e,a){switch(e.tag){case 26:case 27:case 5:return be(e.type);case 16:return be("Lazy");case 13:return e.child!==a&&a!==null?be("Suspense Fallback"):be("Suspense");case 19:return be("SuspenseList");case 0:case 15:return at(e.type,!1);case 11:return at(e.type.render,!1);case 1:return at(e.type,!0);case 31:return be("Activity");default:return""}}function Qe(e){try{var a="",o=null;do a+=ht(e,o),o=e,e=e.return;while(e);return a}catch(l){return`+Error generating stack: `+l.message+`+`+l.stack}}var Pe=Object.prototype.hasOwnProperty,Tt=t.unstable_scheduleCallback,Zt=t.unstable_cancelCallback,O=t.unstable_shouldYield,B=t.unstable_requestPaint,V=t.unstable_now,we=t.unstable_getCurrentPriorityLevel,ge=t.unstable_ImmediatePriority,ye=t.unstable_UserBlockingPriority,Se=t.unstable_NormalPriority,Ue=t.unstable_LowPriority,Ge=t.unstable_IdlePriority,Pt=t.log,Mt=t.unstable_setDisableYieldValue,mt=null,Dt=null;function an(e){if(typeof Pt=="function"&&Mt(e),Dt&&typeof Dt.setStrictMode=="function")try{Dt.setStrictMode(mt,e)}catch{}}var Ht=Math.clz32?Math.clz32:Yn,Ko=Math.log,ur=Math.LN2;function Yn(e){return e>>>=0,e===0?32:31-(Ko(e)/ur|0)|0}var Ua=256,ks=262144,Wr=4194304;function xa(e){var a=e&42;if(a!==0)return a;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:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function He(e,a,o){var l=e.pendingLanes;if(l===0)return 0;var d=0,m=e.suspendedLanes,x=e.pingedLanes;e=e.warmLanes;var N=l&134217727;return N!==0?(l=N&~m,l!==0?d=xa(l):(x&=N,x!==0?d=xa(x):o||(o=N&~e,o!==0&&(d=xa(o))))):(N=l&~m,N!==0?d=xa(N):x!==0?d=xa(x):o||(o=l&~e,o!==0&&(d=xa(o)))),d===0?0:a!==0&&a!==d&&(a&m)===0&&(m=d&-d,o=a&-a,m>=o||m===32&&(o&4194048)!==0)?a:d}function _t(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function en(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32: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+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function dn(){var e=Wr;return Wr<<=1,(Wr&62914560)===0&&(Wr=4194304),e}function dr(e){for(var a=[],o=0;31>o;o++)a.push(e);return a}function Rt(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function bn(e,a,o,l,d,m){var x=e.pendingLanes;e.pendingLanes=o,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=o,e.entangledLanes&=o,e.errorRecoveryDisabledLanes&=o,e.shellSuspendCounter=0;var N=e.entanglements,M=e.expirationTimes,q=e.hiddenUpdates;for(o=x&~o;0<o;){var re=31-Ht(o),ue=1<<re;N[re]=0,M[re]=-1;var Z=q[re];if(Z!==null)for(q[re]=null,re=0;re<Z.length;re++){var ee=Z[re];ee!==null&&(ee.lane&=-536870913)}o&=~ue}l!==0&&Jr(e,l,0),m!==0&&d===0&&e.tag!==0&&(e.suspendedLanes|=m&~(x&~a))}function Jr(e,a,o){e.pendingLanes|=a,e.suspendedLanes&=~a;var l=31-Ht(a);e.entangledLanes|=a,e.entanglements[l]=e.entanglements[l]|1073741824|o&261930}function xn(e,a){var o=e.entangledLanes|=a;for(e=e.entanglements;o;){var l=31-Ht(o),d=1<<l;d&a|e[l]&a&&(e[l]|=a),o&=~d}}function wn(e,a){var o=a&-a;return o=(o&42)!==0?1:Ms(o),(o&(e.suspendedLanes|a))!==0?0:o}function Ms(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function ca(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Ju(){var e=K.p;return e!==0?e:(e=window.event,e===void 0?32:nb(e.type))}function yp(e,a){var o=K.p;try{return K.p=e,a()}finally{K.p=o}}var fr=Math.random().toString(36).slice(2),rn="__reactFiber$"+fr,Sn="__reactProps$"+fr,Ds="__reactContainer$"+fr,ed="__reactEvents$"+fr,fE="__reactListeners$"+fr,mE="__reactHandles$"+fr,bp="__reactResources$"+fr,Qo="__reactMarker$"+fr;function td(e){delete e[rn],delete e[Sn],delete e[ed],delete e[fE],delete e[mE]}function zs(e){var a=e[rn];if(a)return a;for(var o=e.parentNode;o;){if(a=o[Ds]||o[rn]){if(o=a.alternate,a.child!==null||o!==null&&o.child!==null)for(e=Hy(e);e!==null;){if(o=e[rn])return o;e=Hy(e)}return a}e=o,o=e.parentNode}return null}function Ls(e){if(e=e[rn]||e[Ds]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Wo(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(s(33))}function Us(e){var a=e[bp];return a||(a=e[bp]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function tn(e){e[Qo]=!0}var xp=new Set,wp={};function es(e,a){Bs(e,a),Bs(e+"Capture",a)}function Bs(e,a){for(wp[e]=a,e=0;e<a.length;e++)xp.add(a[e])}var hE=RegExp("^[: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]*$"),Sp={},Ep={};function pE(e){return Pe.call(Ep,e)?!0:Pe.call(Sp,e)?!1:hE.test(e)?Ep[e]=!0:(Sp[e]=!0,!1)}function xl(e,a,o){if(pE(a))if(o===null)e.removeAttribute(a);else{switch(typeof o){case"undefined":case"function":case"symbol":e.removeAttribute(a);return;case"boolean":var l=a.toLowerCase().slice(0,5);if(l!=="data-"&&l!=="aria-"){e.removeAttribute(a);return}}e.setAttribute(a,""+o)}}function wl(e,a,o){if(o===null)e.removeAttribute(a);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(a);return}e.setAttribute(a,""+o)}}function Ba(e,a,o,l){if(l===null)e.removeAttribute(o);else{switch(typeof l){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(o);return}e.setAttributeNS(a,o,""+l)}}function Zn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function _p(e){var a=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function gE(e,a,o){var l=Object.getOwnPropertyDescriptor(e.constructor.prototype,a);if(!e.hasOwnProperty(a)&&typeof l<"u"&&typeof l.get=="function"&&typeof l.set=="function"){var d=l.get,m=l.set;return Object.defineProperty(e,a,{configurable:!0,get:function(){return d.call(this)},set:function(x){o=""+x,m.call(this,x)}}),Object.defineProperty(e,a,{enumerable:l.enumerable}),{getValue:function(){return o},setValue:function(x){o=""+x},stopTracking:function(){e._valueTracker=null,delete e[a]}}}}function nd(e){if(!e._valueTracker){var a=_p(e)?"checked":"value";e._valueTracker=gE(e,a,""+e[a])}}function Cp(e){if(!e)return!1;var a=e._valueTracker;if(!a)return!0;var o=a.getValue(),l="";return e&&(l=_p(e)?e.checked?"true":"false":e.value),e=l,e!==o?(a.setValue(e),!0):!1}function Sl(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}}var vE=/[\n"\\]/g;function Xn(e){return e.replace(vE,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function ad(e,a,o,l,d,m,x,N){e.name="",x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"?e.type=x:e.removeAttribute("type"),a!=null?x==="number"?(a===0&&e.value===""||e.value!=a)&&(e.value=""+Zn(a)):e.value!==""+Zn(a)&&(e.value=""+Zn(a)):x!=="submit"&&x!=="reset"||e.removeAttribute("value"),a!=null?rd(e,x,Zn(a)):o!=null?rd(e,x,Zn(o)):l!=null&&e.removeAttribute("value"),d==null&&m!=null&&(e.defaultChecked=!!m),d!=null&&(e.checked=d&&typeof d!="function"&&typeof d!="symbol"),N!=null&&typeof N!="function"&&typeof N!="symbol"&&typeof N!="boolean"?e.name=""+Zn(N):e.removeAttribute("name")}function Np(e,a,o,l,d,m,x,N){if(m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(e.type=m),a!=null||o!=null){if(!(m!=="submit"&&m!=="reset"||a!=null)){nd(e);return}o=o!=null?""+Zn(o):"",a=a!=null?""+Zn(a):o,N||a===e.value||(e.value=a),e.defaultValue=a}l=l??d,l=typeof l!="function"&&typeof l!="symbol"&&!!l,e.checked=N?e.checked:!!l,e.defaultChecked=!!l,x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"&&(e.name=x),nd(e)}function rd(e,a,o){a==="number"&&Sl(e.ownerDocument)===e||e.defaultValue===""+o||(e.defaultValue=""+o)}function Ps(e,a,o,l){if(e=e.options,a){a={};for(var d=0;d<o.length;d++)a["$"+o[d]]=!0;for(o=0;o<e.length;o++)d=a.hasOwnProperty("$"+e[o].value),e[o].selected!==d&&(e[o].selected=d),d&&l&&(e[o].defaultSelected=!0)}else{for(o=""+Zn(o),a=null,d=0;d<e.length;d++){if(e[d].value===o){e[d].selected=!0,l&&(e[d].defaultSelected=!0);return}a!==null||e[d].disabled||(a=e[d])}a!==null&&(a.selected=!0)}}function Rp(e,a,o){if(a!=null&&(a=""+Zn(a),a!==e.value&&(e.value=a),o==null)){e.defaultValue!==a&&(e.defaultValue=a);return}e.defaultValue=o!=null?""+Zn(o):""}function Ap(e,a,o,l){if(a==null){if(l!=null){if(o!=null)throw Error(s(92));if(ve(l)){if(1<l.length)throw Error(s(93));l=l[0]}o=l}o==null&&(o=""),a=o}o=Zn(a),e.defaultValue=o,l=e.textContent,l===o&&l!==""&&l!==null&&(e.value=l),nd(e)}function Hs(e,a){if(a){var o=e.firstChild;if(o&&o===e.lastChild&&o.nodeType===3){o.nodeValue=a;return}}e.textContent=a}var yE=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Tp(e,a,o){var l=a.indexOf("--")===0;o==null||typeof o=="boolean"||o===""?l?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="":l?e.setProperty(a,o):typeof o!="number"||o===0||yE.has(a)?a==="float"?e.cssFloat=o:e[a]=(""+o).trim():e[a]=o+"px"}function Op(e,a,o){if(a!=null&&typeof a!="object")throw Error(s(62));if(e=e.style,o!=null){for(var l in o)!o.hasOwnProperty(l)||a!=null&&a.hasOwnProperty(l)||(l.indexOf("--")===0?e.setProperty(l,""):l==="float"?e.cssFloat="":e[l]="");for(var d in a)l=a[d],a.hasOwnProperty(d)&&o[d]!==l&&Tp(e,d,l)}else for(var m in a)a.hasOwnProperty(m)&&Tp(e,m,a[m])}function sd(e){if(e.indexOf("-")===-1)return!1;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 bE=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),xE=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function El(e){return xE.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Pa(){}var od=null;function id(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Vs=null,Is=null;function jp(e){var a=Ls(e);if(a&&(e=a.stateNode)){var o=e[Sn]||null;e:switch(e=a.stateNode,a.type){case"input":if(ad(e,o.value,o.defaultValue,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name),a=o.name,o.type==="radio"&&a!=null){for(o=e;o.parentNode;)o=o.parentNode;for(o=o.querySelectorAll('input[name="'+Xn(""+a)+'"][type="radio"]'),a=0;a<o.length;a++){var l=o[a];if(l!==e&&l.form===e.form){var d=l[Sn]||null;if(!d)throw Error(s(90));ad(l,d.value,d.defaultValue,d.defaultValue,d.checked,d.defaultChecked,d.type,d.name)}}for(a=0;a<o.length;a++)l=o[a],l.form===e.form&&Cp(l)}break e;case"textarea":Rp(e,o.value,o.defaultValue);break e;case"select":a=o.value,a!=null&&Ps(e,!!o.multiple,a,!1)}}}var ld=!1;function kp(e,a,o){if(ld)return e(a,o);ld=!0;try{var l=e(a);return l}finally{if(ld=!1,(Vs!==null||Is!==null)&&(uc(),Vs&&(a=Vs,e=Is,Is=Vs=null,jp(a),e)))for(a=0;a<e.length;a++)jp(e[a])}}function Jo(e,a){var o=e.stateNode;if(o===null)return null;var l=o[Sn]||null;if(l===null)return null;o=l[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(l=!l.disabled)||(e=e.type,l=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!l;break e;default:e=!1}if(e)return null;if(o&&typeof o!="function")throw Error(s(231,a,typeof o));return o}var Ha=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),cd=!1;if(Ha)try{var ei={};Object.defineProperty(ei,"passive",{get:function(){cd=!0}}),window.addEventListener("test",ei,ei),window.removeEventListener("test",ei,ei)}catch{cd=!1}var mr=null,ud=null,_l=null;function Mp(){if(_l)return _l;var e,a=ud,o=a.length,l,d="value"in mr?mr.value:mr.textContent,m=d.length;for(e=0;e<o&&a[e]===d[e];e++);var x=o-e;for(l=1;l<=x&&a[o-l]===d[m-l];l++);return _l=d.slice(e,1<l?1-l:void 0)}function Cl(e){var a=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&a===13&&(e=13)):e=a,e===10&&(e=13),32<=e||e===13?e:0}function Nl(){return!0}function Dp(){return!1}function En(e){function a(o,l,d,m,x){this._reactName=o,this._targetInst=d,this.type=l,this.nativeEvent=m,this.target=x,this.currentTarget=null;for(var N in e)e.hasOwnProperty(N)&&(o=e[N],this[N]=o?o(m):m[N]);return this.isDefaultPrevented=(m.defaultPrevented!=null?m.defaultPrevented:m.returnValue===!1)?Nl:Dp,this.isPropagationStopped=Dp,this}return v(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var o=this.nativeEvent;o&&(o.preventDefault?o.preventDefault():typeof o.returnValue!="unknown"&&(o.returnValue=!1),this.isDefaultPrevented=Nl)},stopPropagation:function(){var o=this.nativeEvent;o&&(o.stopPropagation?o.stopPropagation():typeof o.cancelBubble!="unknown"&&(o.cancelBubble=!0),this.isPropagationStopped=Nl)},persist:function(){},isPersistent:Nl}),a}var ts={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Rl=En(ts),ti=v({},ts,{view:0,detail:0}),wE=En(ti),dd,fd,ni,Al=v({},ti,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:hd,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==ni&&(ni&&e.type==="mousemove"?(dd=e.screenX-ni.screenX,fd=e.screenY-ni.screenY):fd=dd=0,ni=e),dd)},movementY:function(e){return"movementY"in e?e.movementY:fd}}),zp=En(Al),SE=v({},Al,{dataTransfer:0}),EE=En(SE),_E=v({},ti,{relatedTarget:0}),md=En(_E),CE=v({},ts,{animationName:0,elapsedTime:0,pseudoElement:0}),NE=En(CE),RE=v({},ts,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),AE=En(RE),TE=v({},ts,{data:0}),Lp=En(TE),OE={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},jE={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},kE={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ME(e){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(e):(e=kE[e])?!!a[e]:!1}function hd(){return ME}var DE=v({},ti,{key:function(e){if(e.key){var a=OE[e.key]||e.key;if(a!=="Unidentified")return a}return e.type==="keypress"?(e=Cl(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?jE[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:hd,charCode:function(e){return e.type==="keypress"?Cl(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Cl(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),zE=En(DE),LE=v({},Al,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Up=En(LE),UE=v({},ti,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:hd}),BE=En(UE),PE=v({},ts,{propertyName:0,elapsedTime:0,pseudoElement:0}),HE=En(PE),VE=v({},Al,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),IE=En(VE),qE=v({},ts,{newState:0,oldState:0}),FE=En(qE),$E=[9,13,27,32],pd=Ha&&"CompositionEvent"in window,ai=null;Ha&&"documentMode"in document&&(ai=document.documentMode);var GE=Ha&&"TextEvent"in window&&!ai,Bp=Ha&&(!pd||ai&&8<ai&&11>=ai),Pp=" ",Hp=!1;function Vp(e,a){switch(e){case"keyup":return $E.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ip(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var qs=!1;function YE(e,a){switch(e){case"compositionend":return Ip(a);case"keypress":return a.which!==32?null:(Hp=!0,Pp);case"textInput":return e=a.data,e===Pp&&Hp?null:e;default:return null}}function ZE(e,a){if(qs)return e==="compositionend"||!pd&&Vp(e,a)?(e=Mp(),_l=ud=mr=null,qs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return Bp&&a.locale!=="ko"?null:a.data;default:return null}}var XE={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function qp(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a==="input"?!!XE[e.type]:a==="textarea"}function Fp(e,a,o,l){Vs?Is?Is.push(l):Is=[l]:Vs=l,a=vc(a,"onChange"),0<a.length&&(o=new Rl("onChange","change",null,o,l),e.push({event:o,listeners:a}))}var ri=null,si=null;function KE(e){Ny(e,0)}function Tl(e){var a=Wo(e);if(Cp(a))return e}function $p(e,a){if(e==="change")return a}var Gp=!1;if(Ha){var gd;if(Ha){var vd="oninput"in document;if(!vd){var Yp=document.createElement("div");Yp.setAttribute("oninput","return;"),vd=typeof Yp.oninput=="function"}gd=vd}else gd=!1;Gp=gd&&(!document.documentMode||9<document.documentMode)}function Zp(){ri&&(ri.detachEvent("onpropertychange",Xp),si=ri=null)}function Xp(e){if(e.propertyName==="value"&&Tl(si)){var a=[];Fp(a,si,e,id(e)),kp(KE,a)}}function QE(e,a,o){e==="focusin"?(Zp(),ri=a,si=o,ri.attachEvent("onpropertychange",Xp)):e==="focusout"&&Zp()}function WE(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Tl(si)}function JE(e,a){if(e==="click")return Tl(a)}function e_(e,a){if(e==="input"||e==="change")return Tl(a)}function t_(e,a){return e===a&&(e!==0||1/e===1/a)||e!==e&&a!==a}var Mn=typeof Object.is=="function"?Object.is:t_;function oi(e,a){if(Mn(e,a))return!0;if(typeof e!="object"||e===null||typeof a!="object"||a===null)return!1;var o=Object.keys(e),l=Object.keys(a);if(o.length!==l.length)return!1;for(l=0;l<o.length;l++){var d=o[l];if(!Pe.call(a,d)||!Mn(e[d],a[d]))return!1}return!0}function Kp(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Qp(e,a){var o=Kp(e);e=0;for(var l;o;){if(o.nodeType===3){if(l=e+o.textContent.length,e<=a&&l>=a)return{node:o,offset:a-e};e=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Kp(o)}}function Wp(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?Wp(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function Jp(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=Sl(e.document);a instanceof e.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)e=a.contentWindow;else break;a=Sl(e.document)}return a}function yd(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a&&(a==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||a==="textarea"||e.contentEditable==="true")}var n_=Ha&&"documentMode"in document&&11>=document.documentMode,Fs=null,bd=null,ii=null,xd=!1;function eg(e,a,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;xd||Fs==null||Fs!==Sl(l)||(l=Fs,"selectionStart"in l&&yd(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),ii&&oi(ii,l)||(ii=l,l=vc(bd,"onSelect"),0<l.length&&(a=new Rl("onSelect","select",null,a,o),e.push({event:a,listeners:l}),a.target=Fs)))}function ns(e,a){var o={};return o[e.toLowerCase()]=a.toLowerCase(),o["Webkit"+e]="webkit"+a,o["Moz"+e]="moz"+a,o}var $s={animationend:ns("Animation","AnimationEnd"),animationiteration:ns("Animation","AnimationIteration"),animationstart:ns("Animation","AnimationStart"),transitionrun:ns("Transition","TransitionRun"),transitionstart:ns("Transition","TransitionStart"),transitioncancel:ns("Transition","TransitionCancel"),transitionend:ns("Transition","TransitionEnd")},wd={},tg={};Ha&&(tg=document.createElement("div").style,"AnimationEvent"in window||(delete $s.animationend.animation,delete $s.animationiteration.animation,delete $s.animationstart.animation),"TransitionEvent"in window||delete $s.transitionend.transition);function as(e){if(wd[e])return wd[e];if(!$s[e])return e;var a=$s[e],o;for(o in a)if(a.hasOwnProperty(o)&&o in tg)return wd[e]=a[o];return e}var ng=as("animationend"),ag=as("animationiteration"),rg=as("animationstart"),a_=as("transitionrun"),r_=as("transitionstart"),s_=as("transitioncancel"),sg=as("transitionend"),og=new Map,Sd="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");Sd.push("scrollEnd");function ua(e,a){og.set(e,a),es(a,[e])}var Ol=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},Kn=[],Gs=0,Ed=0;function jl(){for(var e=Gs,a=Ed=Gs=0;a<e;){var o=Kn[a];Kn[a++]=null;var l=Kn[a];Kn[a++]=null;var d=Kn[a];Kn[a++]=null;var m=Kn[a];if(Kn[a++]=null,l!==null&&d!==null){var x=l.pending;x===null?d.next=d:(d.next=x.next,x.next=d),l.pending=d}m!==0&&ig(o,d,m)}}function kl(e,a,o,l){Kn[Gs++]=e,Kn[Gs++]=a,Kn[Gs++]=o,Kn[Gs++]=l,Ed|=l,e.lanes|=l,e=e.alternate,e!==null&&(e.lanes|=l)}function _d(e,a,o,l){return kl(e,a,o,l),Ml(e)}function rs(e,a){return kl(e,null,null,a),Ml(e)}function ig(e,a,o){e.lanes|=o;var l=e.alternate;l!==null&&(l.lanes|=o);for(var d=!1,m=e.return;m!==null;)m.childLanes|=o,l=m.alternate,l!==null&&(l.childLanes|=o),m.tag===22&&(e=m.stateNode,e===null||e._visibility&1||(d=!0)),e=m,m=m.return;return e.tag===3?(m=e.stateNode,d&&a!==null&&(d=31-Ht(o),e=m.hiddenUpdates,l=e[d],l===null?e[d]=[a]:l.push(a),a.lane=o|536870912),m):null}function Ml(e){if(50<Ti)throw Ti=0,Df=null,Error(s(185));for(var a=e.return;a!==null;)e=a,a=e.return;return e.tag===3?e.stateNode:null}var Ys={};function o_(e,a,o,l){this.tag=e,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dn(e,a,o,l){return new o_(e,a,o,l)}function Cd(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Va(e,a){var o=e.alternate;return o===null?(o=Dn(e.tag,a,e.key,e.mode),o.elementType=e.elementType,o.type=e.type,o.stateNode=e.stateNode,o.alternate=e,e.alternate=o):(o.pendingProps=a,o.type=e.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=e.flags&65011712,o.childLanes=e.childLanes,o.lanes=e.lanes,o.child=e.child,o.memoizedProps=e.memoizedProps,o.memoizedState=e.memoizedState,o.updateQueue=e.updateQueue,a=e.dependencies,o.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},o.sibling=e.sibling,o.index=e.index,o.ref=e.ref,o.refCleanup=e.refCleanup,o}function lg(e,a){e.flags&=65011714;var o=e.alternate;return o===null?(e.childLanes=0,e.lanes=a,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=o.childLanes,e.lanes=o.lanes,e.child=o.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=o.memoizedProps,e.memoizedState=o.memoizedState,e.updateQueue=o.updateQueue,e.type=o.type,a=o.dependencies,e.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e}function Dl(e,a,o,l,d,m){var x=0;if(l=e,typeof e=="function")Cd(e)&&(x=1);else if(typeof e=="string")x=dC(e,o,Y.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case de:return e=Dn(31,o,a,d),e.elementType=de,e.lanes=m,e;case _:return ss(o.children,d,m,a);case E:x=8,d|=24;break;case R:return e=Dn(12,o,a,d|2),e.elementType=R,e.lanes=m,e;case H:return e=Dn(13,o,a,d),e.elementType=H,e.lanes=m,e;case $:return e=Dn(19,o,a,d),e.elementType=$,e.lanes=m,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case A:x=10;break e;case k:x=9;break e;case D:x=11;break e;case U:x=14;break e;case F:x=16,l=null;break e}x=29,o=Error(s(130,e===null?"null":typeof e,"")),l=null}return a=Dn(x,o,a,d),a.elementType=e,a.type=l,a.lanes=m,a}function ss(e,a,o,l){return e=Dn(7,e,l,a),e.lanes=o,e}function Nd(e,a,o){return e=Dn(6,e,null,a),e.lanes=o,e}function cg(e){var a=Dn(18,null,null,0);return a.stateNode=e,a}function Rd(e,a,o){return a=Dn(4,e.children!==null?e.children:[],e.key,a),a.lanes=o,a.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},a}var ug=new WeakMap;function Qn(e,a){if(typeof e=="object"&&e!==null){var o=ug.get(e);return o!==void 0?o:(a={value:e,source:a,stack:Qe(a)},ug.set(e,a),a)}return{value:e,source:a,stack:Qe(a)}}var Zs=[],Xs=0,zl=null,li=0,Wn=[],Jn=0,hr=null,wa=1,Sa="";function Ia(e,a){Zs[Xs++]=li,Zs[Xs++]=zl,zl=e,li=a}function dg(e,a,o){Wn[Jn++]=wa,Wn[Jn++]=Sa,Wn[Jn++]=hr,hr=e;var l=wa;e=Sa;var d=32-Ht(l)-1;l&=~(1<<d),o+=1;var m=32-Ht(a)+d;if(30<m){var x=d-d%5;m=(l&(1<<x)-1).toString(32),l>>=x,d-=x,wa=1<<32-Ht(a)+d|o<<d|l,Sa=m+e}else wa=1<<m|o<<d|l,Sa=e}function Ad(e){e.return!==null&&(Ia(e,1),dg(e,1,0))}function Td(e){for(;e===zl;)zl=Zs[--Xs],Zs[Xs]=null,li=Zs[--Xs],Zs[Xs]=null;for(;e===hr;)hr=Wn[--Jn],Wn[Jn]=null,Sa=Wn[--Jn],Wn[Jn]=null,wa=Wn[--Jn],Wn[Jn]=null}function fg(e,a){Wn[Jn++]=wa,Wn[Jn++]=Sa,Wn[Jn++]=hr,wa=a.id,Sa=a.overflow,hr=e}var sn=null,St=null,rt=!1,pr=null,ea=!1,Od=Error(s(519));function gr(e){var a=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw ci(Qn(a,e)),Od}function mg(e){var a=e.stateNode,o=e.type,l=e.memoizedProps;switch(a[rn]=e,a[Sn]=l,o){case"dialog":Je("cancel",a),Je("close",a);break;case"iframe":case"object":case"embed":Je("load",a);break;case"video":case"audio":for(o=0;o<ji.length;o++)Je(ji[o],a);break;case"source":Je("error",a);break;case"img":case"image":case"link":Je("error",a),Je("load",a);break;case"details":Je("toggle",a);break;case"input":Je("invalid",a),Np(a,l.value,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name,!0);break;case"select":Je("invalid",a);break;case"textarea":Je("invalid",a),Ap(a,l.value,l.defaultValue,l.children)}o=l.children,typeof o!="string"&&typeof o!="number"&&typeof o!="bigint"||a.textContent===""+o||l.suppressHydrationWarning===!0||Oy(a.textContent,o)?(l.popover!=null&&(Je("beforetoggle",a),Je("toggle",a)),l.onScroll!=null&&Je("scroll",a),l.onScrollEnd!=null&&Je("scrollend",a),l.onClick!=null&&(a.onclick=Pa),a=!0):a=!1,a||gr(e,!0)}function hg(e){for(sn=e.return;sn;)switch(sn.tag){case 5:case 31:case 13:ea=!1;return;case 27:case 3:ea=!0;return;default:sn=sn.return}}function Ks(e){if(e!==sn)return!1;if(!rt)return hg(e),rt=!0,!1;var a=e.tag,o;if((o=a!==3&&a!==27)&&((o=a===5)&&(o=e.type,o=!(o!=="form"&&o!=="button")||Xf(e.type,e.memoizedProps)),o=!o),o&&St&&gr(e),hg(e),a===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));St=Py(e)}else if(a===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(317));St=Py(e)}else a===27?(a=St,Or(e.type)?(e=em,em=null,St=e):St=a):St=sn?na(e.stateNode.nextSibling):null;return!0}function os(){St=sn=null,rt=!1}function jd(){var e=pr;return e!==null&&(Rn===null?Rn=e:Rn.push.apply(Rn,e),pr=null),e}function ci(e){pr===null?pr=[e]:pr.push(e)}var kd=j(null),is=null,qa=null;function vr(e,a,o){L(kd,a._currentValue),a._currentValue=o}function Fa(e){e._currentValue=kd.current,X(kd)}function Md(e,a,o){for(;e!==null;){var l=e.alternate;if((e.childLanes&a)!==a?(e.childLanes|=a,l!==null&&(l.childLanes|=a)):l!==null&&(l.childLanes&a)!==a&&(l.childLanes|=a),e===o)break;e=e.return}}function Dd(e,a,o,l){var d=e.child;for(d!==null&&(d.return=e);d!==null;){var m=d.dependencies;if(m!==null){var x=d.child;m=m.firstContext;e:for(;m!==null;){var N=m;m=d;for(var M=0;M<a.length;M++)if(N.context===a[M]){m.lanes|=o,N=m.alternate,N!==null&&(N.lanes|=o),Md(m.return,o,e),l||(x=null);break e}m=N.next}}else if(d.tag===18){if(x=d.return,x===null)throw Error(s(341));x.lanes|=o,m=x.alternate,m!==null&&(m.lanes|=o),Md(x,o,e),x=null}else x=d.child;if(x!==null)x.return=d;else for(x=d;x!==null;){if(x===e){x=null;break}if(d=x.sibling,d!==null){d.return=x.return,x=d;break}x=x.return}d=x}}function Qs(e,a,o,l){e=null;for(var d=a,m=!1;d!==null;){if(!m){if((d.flags&524288)!==0)m=!0;else if((d.flags&262144)!==0)break}if(d.tag===10){var x=d.alternate;if(x===null)throw Error(s(387));if(x=x.memoizedProps,x!==null){var N=d.type;Mn(d.pendingProps.value,x.value)||(e!==null?e.push(N):e=[N])}}else if(d===pe.current){if(x=d.alternate,x===null)throw Error(s(387));x.memoizedState.memoizedState!==d.memoizedState.memoizedState&&(e!==null?e.push(Li):e=[Li])}d=d.return}e!==null&&Dd(a,e,o,l),a.flags|=262144}function Ll(e){for(e=e.firstContext;e!==null;){if(!Mn(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function ls(e){is=e,qa=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function on(e){return pg(is,e)}function Ul(e,a){return is===null&&ls(e),pg(e,a)}function pg(e,a){var o=a._currentValue;if(a={context:a,memoizedValue:o,next:null},qa===null){if(e===null)throw Error(s(308));qa=a,e.dependencies={lanes:0,firstContext:a},e.flags|=524288}else qa=qa.next=a;return o}var i_=typeof AbortController<"u"?AbortController:function(){var e=[],a=this.signal={aborted:!1,addEventListener:function(o,l){e.push(l)}};this.abort=function(){a.aborted=!0,e.forEach(function(o){return o()})}},l_=t.unstable_scheduleCallback,c_=t.unstable_NormalPriority,Vt={$$typeof:A,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function zd(){return{controller:new i_,data:new Map,refCount:0}}function ui(e){e.refCount--,e.refCount===0&&l_(c_,function(){e.controller.abort()})}var di=null,Ld=0,Ws=0,Js=null;function u_(e,a){if(di===null){var o=di=[];Ld=0,Ws=Hf(),Js={status:"pending",value:void 0,then:function(l){o.push(l)}}}return Ld++,a.then(gg,gg),a}function gg(){if(--Ld===0&&di!==null){Js!==null&&(Js.status="fulfilled");var e=di;di=null,Ws=0,Js=null;for(var a=0;a<e.length;a++)(0,e[a])()}}function d_(e,a){var o=[],l={status:"pending",value:null,reason:null,then:function(d){o.push(d)}};return e.then(function(){l.status="fulfilled",l.value=a;for(var d=0;d<o.length;d++)(0,o[d])(a)},function(d){for(l.status="rejected",l.reason=d,d=0;d<o.length;d++)(0,o[d])(void 0)}),l}var vg=T.S;T.S=function(e,a){ey=V(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&u_(e,a),vg!==null&&vg(e,a)};var cs=j(null);function Ud(){var e=cs.current;return e!==null?e:wt.pooledCache}function Bl(e,a){a===null?L(cs,cs.current):L(cs,a.pool)}function yg(){var e=Ud();return e===null?null:{parent:Vt._currentValue,pool:e}}var eo=Error(s(460)),Bd=Error(s(474)),Pl=Error(s(542)),Hl={then:function(){}};function bg(e){return e=e.status,e==="fulfilled"||e==="rejected"}function xg(e,a,o){switch(o=e[o],o===void 0?e.push(a):o!==a&&(a.then(Pa,Pa),a=o),a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,Sg(e),e;default:if(typeof a.status=="string")a.then(Pa,Pa);else{if(e=wt,e!==null&&100<e.shellSuspendCounter)throw Error(s(482));e=a,e.status="pending",e.then(function(l){if(a.status==="pending"){var d=a;d.status="fulfilled",d.value=l}},function(l){if(a.status==="pending"){var d=a;d.status="rejected",d.reason=l}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,Sg(e),e}throw ds=a,eo}}function us(e){try{var a=e._init;return a(e._payload)}catch(o){throw o!==null&&typeof o=="object"&&typeof o.then=="function"?(ds=o,eo):o}}var ds=null;function wg(){if(ds===null)throw Error(s(459));var e=ds;return ds=null,e}function Sg(e){if(e===eo||e===Pl)throw Error(s(483))}var to=null,fi=0;function Vl(e){var a=fi;return fi+=1,to===null&&(to=[]),xg(to,e,a)}function mi(e,a){a=a.props.ref,e.ref=a!==void 0?a:null}function Il(e,a){throw a.$$typeof===w?Error(s(525)):(e=Object.prototype.toString.call(a),Error(s(31,e==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":e)))}function Eg(e){function a(P,z){if(e){var I=P.deletions;I===null?(P.deletions=[z],P.flags|=16):I.push(z)}}function o(P,z){if(!e)return null;for(;z!==null;)a(P,z),z=z.sibling;return null}function l(P){for(var z=new Map;P!==null;)P.key!==null?z.set(P.key,P):z.set(P.index,P),P=P.sibling;return z}function d(P,z){return P=Va(P,z),P.index=0,P.sibling=null,P}function m(P,z,I){return P.index=I,e?(I=P.alternate,I!==null?(I=I.index,I<z?(P.flags|=67108866,z):I):(P.flags|=67108866,z)):(P.flags|=1048576,z)}function x(P){return e&&P.alternate===null&&(P.flags|=67108866),P}function N(P,z,I,ce){return z===null||z.tag!==6?(z=Nd(I,P.mode,ce),z.return=P,z):(z=d(z,I),z.return=P,z)}function M(P,z,I,ce){var De=I.type;return De===_?re(P,z,I.props.children,ce,I.key):z!==null&&(z.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===F&&us(De)===z.type)?(z=d(z,I.props),mi(z,I),z.return=P,z):(z=Dl(I.type,I.key,I.props,null,P.mode,ce),mi(z,I),z.return=P,z)}function q(P,z,I,ce){return z===null||z.tag!==4||z.stateNode.containerInfo!==I.containerInfo||z.stateNode.implementation!==I.implementation?(z=Rd(I,P.mode,ce),z.return=P,z):(z=d(z,I.children||[]),z.return=P,z)}function re(P,z,I,ce,De){return z===null||z.tag!==7?(z=ss(I,P.mode,ce,De),z.return=P,z):(z=d(z,I),z.return=P,z)}function ue(P,z,I){if(typeof z=="string"&&z!==""||typeof z=="number"||typeof z=="bigint")return z=Nd(""+z,P.mode,I),z.return=P,z;if(typeof z=="object"&&z!==null){switch(z.$$typeof){case C:return I=Dl(z.type,z.key,z.props,null,P.mode,I),mi(I,z),I.return=P,I;case S:return z=Rd(z,P.mode,I),z.return=P,z;case F:return z=us(z),ue(P,z,I)}if(ve(z)||se(z))return z=ss(z,P.mode,I,null),z.return=P,z;if(typeof z.then=="function")return ue(P,Vl(z),I);if(z.$$typeof===A)return ue(P,Ul(P,z),I);Il(P,z)}return null}function Z(P,z,I,ce){var De=z!==null?z.key:null;if(typeof I=="string"&&I!==""||typeof I=="number"||typeof I=="bigint")return De!==null?null:N(P,z,""+I,ce);if(typeof I=="object"&&I!==null){switch(I.$$typeof){case C:return I.key===De?M(P,z,I,ce):null;case S:return I.key===De?q(P,z,I,ce):null;case F:return I=us(I),Z(P,z,I,ce)}if(ve(I)||se(I))return De!==null?null:re(P,z,I,ce,null);if(typeof I.then=="function")return Z(P,z,Vl(I),ce);if(I.$$typeof===A)return Z(P,z,Ul(P,I),ce);Il(P,I)}return null}function ee(P,z,I,ce,De){if(typeof ce=="string"&&ce!==""||typeof ce=="number"||typeof ce=="bigint")return P=P.get(I)||null,N(z,P,""+ce,De);if(typeof ce=="object"&&ce!==null){switch(ce.$$typeof){case C:return P=P.get(ce.key===null?I:ce.key)||null,M(z,P,ce,De);case S:return P=P.get(ce.key===null?I:ce.key)||null,q(z,P,ce,De);case F:return ce=us(ce),ee(P,z,I,ce,De)}if(ve(ce)||se(ce))return P=P.get(I)||null,re(z,P,ce,De,null);if(typeof ce.then=="function")return ee(P,z,I,Vl(ce),De);if(ce.$$typeof===A)return ee(P,z,I,Ul(z,ce),De);Il(z,ce)}return null}function _e(P,z,I,ce){for(var De=null,lt=null,Oe=z,Ye=z=0,nt=null;Oe!==null&&Ye<I.length;Ye++){Oe.index>Ye?(nt=Oe,Oe=null):nt=Oe.sibling;var ct=Z(P,Oe,I[Ye],ce);if(ct===null){Oe===null&&(Oe=nt);break}e&&Oe&&ct.alternate===null&&a(P,Oe),z=m(ct,z,Ye),lt===null?De=ct:lt.sibling=ct,lt=ct,Oe=nt}if(Ye===I.length)return o(P,Oe),rt&&Ia(P,Ye),De;if(Oe===null){for(;Ye<I.length;Ye++)Oe=ue(P,I[Ye],ce),Oe!==null&&(z=m(Oe,z,Ye),lt===null?De=Oe:lt.sibling=Oe,lt=Oe);return rt&&Ia(P,Ye),De}for(Oe=l(Oe);Ye<I.length;Ye++)nt=ee(Oe,P,Ye,I[Ye],ce),nt!==null&&(e&&nt.alternate!==null&&Oe.delete(nt.key===null?Ye:nt.key),z=m(nt,z,Ye),lt===null?De=nt:lt.sibling=nt,lt=nt);return e&&Oe.forEach(function(zr){return a(P,zr)}),rt&&Ia(P,Ye),De}function Le(P,z,I,ce){if(I==null)throw Error(s(151));for(var De=null,lt=null,Oe=z,Ye=z=0,nt=null,ct=I.next();Oe!==null&&!ct.done;Ye++,ct=I.next()){Oe.index>Ye?(nt=Oe,Oe=null):nt=Oe.sibling;var zr=Z(P,Oe,ct.value,ce);if(zr===null){Oe===null&&(Oe=nt);break}e&&Oe&&zr.alternate===null&&a(P,Oe),z=m(zr,z,Ye),lt===null?De=zr:lt.sibling=zr,lt=zr,Oe=nt}if(ct.done)return o(P,Oe),rt&&Ia(P,Ye),De;if(Oe===null){for(;!ct.done;Ye++,ct=I.next())ct=ue(P,ct.value,ce),ct!==null&&(z=m(ct,z,Ye),lt===null?De=ct:lt.sibling=ct,lt=ct);return rt&&Ia(P,Ye),De}for(Oe=l(Oe);!ct.done;Ye++,ct=I.next())ct=ee(Oe,P,Ye,ct.value,ce),ct!==null&&(e&&ct.alternate!==null&&Oe.delete(ct.key===null?Ye:ct.key),z=m(ct,z,Ye),lt===null?De=ct:lt.sibling=ct,lt=ct);return e&&Oe.forEach(function(SC){return a(P,SC)}),rt&&Ia(P,Ye),De}function bt(P,z,I,ce){if(typeof I=="object"&&I!==null&&I.type===_&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case C:e:{for(var De=I.key;z!==null;){if(z.key===De){if(De=I.type,De===_){if(z.tag===7){o(P,z.sibling),ce=d(z,I.props.children),ce.return=P,P=ce;break e}}else if(z.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===F&&us(De)===z.type){o(P,z.sibling),ce=d(z,I.props),mi(ce,I),ce.return=P,P=ce;break e}o(P,z);break}else a(P,z);z=z.sibling}I.type===_?(ce=ss(I.props.children,P.mode,ce,I.key),ce.return=P,P=ce):(ce=Dl(I.type,I.key,I.props,null,P.mode,ce),mi(ce,I),ce.return=P,P=ce)}return x(P);case S:e:{for(De=I.key;z!==null;){if(z.key===De)if(z.tag===4&&z.stateNode.containerInfo===I.containerInfo&&z.stateNode.implementation===I.implementation){o(P,z.sibling),ce=d(z,I.children||[]),ce.return=P,P=ce;break e}else{o(P,z);break}else a(P,z);z=z.sibling}ce=Rd(I,P.mode,ce),ce.return=P,P=ce}return x(P);case F:return I=us(I),bt(P,z,I,ce)}if(ve(I))return _e(P,z,I,ce);if(se(I)){if(De=se(I),typeof De!="function")throw Error(s(150));return I=De.call(I),Le(P,z,I,ce)}if(typeof I.then=="function")return bt(P,z,Vl(I),ce);if(I.$$typeof===A)return bt(P,z,Ul(P,I),ce);Il(P,I)}return typeof I=="string"&&I!==""||typeof I=="number"||typeof I=="bigint"?(I=""+I,z!==null&&z.tag===6?(o(P,z.sibling),ce=d(z,I),ce.return=P,P=ce):(o(P,z),ce=Nd(I,P.mode,ce),ce.return=P,P=ce),x(P)):o(P,z)}return function(P,z,I,ce){try{fi=0;var De=bt(P,z,I,ce);return to=null,De}catch(Oe){if(Oe===eo||Oe===Pl)throw Oe;var lt=Dn(29,Oe,null,P.mode);return lt.lanes=ce,lt.return=P,lt}finally{}}}var fs=Eg(!0),_g=Eg(!1),yr=!1;function Pd(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Hd(e,a){e=e.updateQueue,a.updateQueue===e&&(a.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function br(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function xr(e,a,o){var l=e.updateQueue;if(l===null)return null;if(l=l.shared,(ft&2)!==0){var d=l.pending;return d===null?a.next=a:(a.next=d.next,d.next=a),l.pending=a,a=Ml(e),ig(e,null,o),a}return kl(e,l,a,o),Ml(e)}function hi(e,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,xn(e,o)}}function Vd(e,a){var o=e.updateQueue,l=e.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,m=null;if(o=o.firstBaseUpdate,o!==null){do{var x={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};m===null?d=m=x:m=m.next=x,o=o.next}while(o!==null);m===null?d=m=a:m=m.next=a}else d=m=a;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:m,shared:l.shared,callbacks:l.callbacks},e.updateQueue=o;return}e=o.lastBaseUpdate,e===null?o.firstBaseUpdate=a:e.next=a,o.lastBaseUpdate=a}var Id=!1;function pi(){if(Id){var e=Js;if(e!==null)throw e}}function gi(e,a,o,l){Id=!1;var d=e.updateQueue;yr=!1;var m=d.firstBaseUpdate,x=d.lastBaseUpdate,N=d.shared.pending;if(N!==null){d.shared.pending=null;var M=N,q=M.next;M.next=null,x===null?m=q:x.next=q,x=M;var re=e.alternate;re!==null&&(re=re.updateQueue,N=re.lastBaseUpdate,N!==x&&(N===null?re.firstBaseUpdate=q:N.next=q,re.lastBaseUpdate=M))}if(m!==null){var ue=d.baseState;x=0,re=q=M=null,N=m;do{var Z=N.lane&-536870913,ee=Z!==N.lane;if(ee?(tt&Z)===Z:(l&Z)===Z){Z!==0&&Z===Ws&&(Id=!0),re!==null&&(re=re.next={lane:0,tag:N.tag,payload:N.payload,callback:null,next:null});e:{var _e=e,Le=N;Z=a;var bt=o;switch(Le.tag){case 1:if(_e=Le.payload,typeof _e=="function"){ue=_e.call(bt,ue,Z);break e}ue=_e;break e;case 3:_e.flags=_e.flags&-65537|128;case 0:if(_e=Le.payload,Z=typeof _e=="function"?_e.call(bt,ue,Z):_e,Z==null)break e;ue=v({},ue,Z);break e;case 2:yr=!0}}Z=N.callback,Z!==null&&(e.flags|=64,ee&&(e.flags|=8192),ee=d.callbacks,ee===null?d.callbacks=[Z]:ee.push(Z))}else ee={lane:Z,tag:N.tag,payload:N.payload,callback:N.callback,next:null},re===null?(q=re=ee,M=ue):re=re.next=ee,x|=Z;if(N=N.next,N===null){if(N=d.shared.pending,N===null)break;ee=N,N=ee.next,ee.next=null,d.lastBaseUpdate=ee,d.shared.pending=null}}while(!0);re===null&&(M=ue),d.baseState=M,d.firstBaseUpdate=q,d.lastBaseUpdate=re,m===null&&(d.shared.lanes=0),Cr|=x,e.lanes=x,e.memoizedState=ue}}function Cg(e,a){if(typeof e!="function")throw Error(s(191,e));e.call(a)}function Ng(e,a){var o=e.callbacks;if(o!==null)for(e.callbacks=null,e=0;e<o.length;e++)Cg(o[e],a)}var no=j(null),ql=j(0);function Rg(e,a){e=Ja,L(ql,e),L(no,a),Ja=e|a.baseLanes}function qd(){L(ql,Ja),L(no,no.current)}function Fd(){Ja=ql.current,X(no),X(ql)}var zn=j(null),ta=null;function wr(e){var a=e.alternate;L(zt,zt.current&1),L(zn,e),ta===null&&(a===null||no.current!==null||a.memoizedState!==null)&&(ta=e)}function $d(e){L(zt,zt.current),L(zn,e),ta===null&&(ta=e)}function Ag(e){e.tag===22?(L(zt,zt.current),L(zn,e),ta===null&&(ta=e)):Sr()}function Sr(){L(zt,zt.current),L(zn,zn.current)}function Ln(e){X(zn),ta===e&&(ta=null),X(zt)}var zt=j(0);function Fl(e){for(var a=e;a!==null;){if(a.tag===13){var o=a.memoizedState;if(o!==null&&(o=o.dehydrated,o===null||Wf(o)||Jf(o)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var $a=0,$e=null,vt=null,It=null,$l=!1,ao=!1,ms=!1,Gl=0,vi=0,ro=null,f_=0;function Ot(){throw Error(s(321))}function Gd(e,a){if(a===null)return!1;for(var o=0;o<a.length&&o<e.length;o++)if(!Mn(e[o],a[o]))return!1;return!0}function Yd(e,a,o,l,d,m){return $a=m,$e=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,T.H=e===null||e.memoizedState===null?dv:cf,ms=!1,m=o(l,d),ms=!1,ao&&(m=Og(a,o,l,d)),Tg(e),m}function Tg(e){T.H=xi;var a=vt!==null&&vt.next!==null;if($a=0,It=vt=$e=null,$l=!1,vi=0,ro=null,a)throw Error(s(300));e===null||qt||(e=e.dependencies,e!==null&&Ll(e)&&(qt=!0))}function Og(e,a,o,l){$e=e;var d=0;do{if(ao&&(ro=null),vi=0,ao=!1,25<=d)throw Error(s(301));if(d+=1,It=vt=null,e.updateQueue!=null){var m=e.updateQueue;m.lastEffect=null,m.events=null,m.stores=null,m.memoCache!=null&&(m.memoCache.index=0)}T.H=fv,m=a(o,l)}while(ao);return m}function m_(){var e=T.H,a=e.useState()[0];return a=typeof a.then=="function"?yi(a):a,e=e.useState()[0],(vt!==null?vt.memoizedState:null)!==e&&($e.flags|=1024),a}function Zd(){var e=Gl!==0;return Gl=0,e}function Xd(e,a,o){a.updateQueue=e.updateQueue,a.flags&=-2053,e.lanes&=~o}function Kd(e){if($l){for(e=e.memoizedState;e!==null;){var a=e.queue;a!==null&&(a.pending=null),e=e.next}$l=!1}$a=0,It=vt=$e=null,ao=!1,vi=Gl=0,ro=null}function pn(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return It===null?$e.memoizedState=It=e:It=It.next=e,It}function Lt(){if(vt===null){var e=$e.alternate;e=e!==null?e.memoizedState:null}else e=vt.next;var a=It===null?$e.memoizedState:It.next;if(a!==null)It=a,vt=e;else{if(e===null)throw $e.alternate===null?Error(s(467)):Error(s(310));vt=e,e={memoizedState:vt.memoizedState,baseState:vt.baseState,baseQueue:vt.baseQueue,queue:vt.queue,next:null},It===null?$e.memoizedState=It=e:It=It.next=e}return It}function Yl(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function yi(e){var a=vi;return vi+=1,ro===null&&(ro=[]),e=xg(ro,e,a),a=$e,(It===null?a.memoizedState:It.next)===null&&(a=a.alternate,T.H=a===null||a.memoizedState===null?dv:cf),e}function Zl(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return yi(e);if(e.$$typeof===A)return on(e)}throw Error(s(438,String(e)))}function Qd(e){var a=null,o=$e.updateQueue;if(o!==null&&(a=o.memoCache),a==null){var l=$e.alternate;l!==null&&(l=l.updateQueue,l!==null&&(l=l.memoCache,l!=null&&(a={data:l.data.map(function(d){return d.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),o===null&&(o=Yl(),$e.updateQueue=o),o.memoCache=a,o=a.data[a.index],o===void 0)for(o=a.data[a.index]=Array(e),l=0;l<e;l++)o[l]=fe;return a.index++,o}function Ga(e,a){return typeof a=="function"?a(e):a}function Xl(e){var a=Lt();return Wd(a,vt,e)}function Wd(e,a,o){var l=e.queue;if(l===null)throw Error(s(311));l.lastRenderedReducer=o;var d=e.baseQueue,m=l.pending;if(m!==null){if(d!==null){var x=d.next;d.next=m.next,m.next=x}a.baseQueue=d=m,l.pending=null}if(m=e.baseState,d===null)e.memoizedState=m;else{a=d.next;var N=x=null,M=null,q=a,re=!1;do{var ue=q.lane&-536870913;if(ue!==q.lane?(tt&ue)===ue:($a&ue)===ue){var Z=q.revertLane;if(Z===0)M!==null&&(M=M.next={lane:0,revertLane:0,gesture:null,action:q.action,hasEagerState:q.hasEagerState,eagerState:q.eagerState,next:null}),ue===Ws&&(re=!0);else if(($a&Z)===Z){q=q.next,Z===Ws&&(re=!0);continue}else ue={lane:0,revertLane:q.revertLane,gesture:null,action:q.action,hasEagerState:q.hasEagerState,eagerState:q.eagerState,next:null},M===null?(N=M=ue,x=m):M=M.next=ue,$e.lanes|=Z,Cr|=Z;ue=q.action,ms&&o(m,ue),m=q.hasEagerState?q.eagerState:o(m,ue)}else Z={lane:ue,revertLane:q.revertLane,gesture:q.gesture,action:q.action,hasEagerState:q.hasEagerState,eagerState:q.eagerState,next:null},M===null?(N=M=Z,x=m):M=M.next=Z,$e.lanes|=ue,Cr|=ue;q=q.next}while(q!==null&&q!==a);if(M===null?x=m:M.next=N,!Mn(m,e.memoizedState)&&(qt=!0,re&&(o=Js,o!==null)))throw o;e.memoizedState=m,e.baseState=x,e.baseQueue=M,l.lastRenderedState=m}return d===null&&(l.lanes=0),[e.memoizedState,l.dispatch]}function Jd(e){var a=Lt(),o=a.queue;if(o===null)throw Error(s(311));o.lastRenderedReducer=e;var l=o.dispatch,d=o.pending,m=a.memoizedState;if(d!==null){o.pending=null;var x=d=d.next;do m=e(m,x.action),x=x.next;while(x!==d);Mn(m,a.memoizedState)||(qt=!0),a.memoizedState=m,a.baseQueue===null&&(a.baseState=m),o.lastRenderedState=m}return[m,l]}function jg(e,a,o){var l=$e,d=Lt(),m=rt;if(m){if(o===void 0)throw Error(s(407));o=o()}else o=a();var x=!Mn((vt||d).memoizedState,o);if(x&&(d.memoizedState=o,qt=!0),d=d.queue,nf(Dg.bind(null,l,d,e),[e]),d.getSnapshot!==a||x||It!==null&&It.memoizedState.tag&1){if(l.flags|=2048,so(9,{destroy:void 0},Mg.bind(null,l,d,o,a),null),wt===null)throw Error(s(349));m||($a&127)!==0||kg(l,a,o)}return o}function kg(e,a,o){e.flags|=16384,e={getSnapshot:a,value:o},a=$e.updateQueue,a===null?(a=Yl(),$e.updateQueue=a,a.stores=[e]):(o=a.stores,o===null?a.stores=[e]:o.push(e))}function Mg(e,a,o,l){a.value=o,a.getSnapshot=l,zg(a)&&Lg(e)}function Dg(e,a,o){return o(function(){zg(a)&&Lg(e)})}function zg(e){var a=e.getSnapshot;e=e.value;try{var o=a();return!Mn(e,o)}catch{return!0}}function Lg(e){var a=rs(e,2);a!==null&&An(a,e,2)}function ef(e){var a=pn();if(typeof e=="function"){var o=e;if(e=o(),ms){an(!0);try{o()}finally{an(!1)}}}return a.memoizedState=a.baseState=e,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ga,lastRenderedState:e},a}function Ug(e,a,o,l){return e.baseState=o,Wd(e,vt,typeof l=="function"?l:Ga)}function h_(e,a,o,l,d){if(Wl(e))throw Error(s(485));if(e=a.action,e!==null){var m={payload:d,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(x){m.listeners.push(x)}};T.T!==null?o(!0):m.isTransition=!1,l(m),o=a.pending,o===null?(m.next=a.pending=m,Bg(a,m)):(m.next=o.next,a.pending=o.next=m)}}function Bg(e,a){var o=a.action,l=a.payload,d=e.state;if(a.isTransition){var m=T.T,x={};T.T=x;try{var N=o(d,l),M=T.S;M!==null&&M(x,N),Pg(e,a,N)}catch(q){tf(e,a,q)}finally{m!==null&&x.types!==null&&(m.types=x.types),T.T=m}}else try{m=o(d,l),Pg(e,a,m)}catch(q){tf(e,a,q)}}function Pg(e,a,o){o!==null&&typeof o=="object"&&typeof o.then=="function"?o.then(function(l){Hg(e,a,l)},function(l){return tf(e,a,l)}):Hg(e,a,o)}function Hg(e,a,o){a.status="fulfilled",a.value=o,Vg(a),e.state=o,a=e.pending,a!==null&&(o=a.next,o===a?e.pending=null:(o=o.next,a.next=o,Bg(e,o)))}function tf(e,a,o){var l=e.pending;if(e.pending=null,l!==null){l=l.next;do a.status="rejected",a.reason=o,Vg(a),a=a.next;while(a!==l)}e.action=null}function Vg(e){e=e.listeners;for(var a=0;a<e.length;a++)(0,e[a])()}function Ig(e,a){return a}function qg(e,a){if(rt){var o=wt.formState;if(o!==null){e:{var l=$e;if(rt){if(St){t:{for(var d=St,m=ea;d.nodeType!==8;){if(!m){d=null;break t}if(d=na(d.nextSibling),d===null){d=null;break t}}m=d.data,d=m==="F!"||m==="F"?d:null}if(d){St=na(d.nextSibling),l=d.data==="F!";break e}}gr(l)}l=!1}l&&(a=o[0])}}return o=pn(),o.memoizedState=o.baseState=a,l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ig,lastRenderedState:a},o.queue=l,o=lv.bind(null,$e,l),l.dispatch=o,l=ef(!1),m=lf.bind(null,$e,!1,l.queue),l=pn(),d={state:a,dispatch:null,action:e,pending:null},l.queue=d,o=h_.bind(null,$e,d,m,o),d.dispatch=o,l.memoizedState=e,[a,o,!1]}function Fg(e){var a=Lt();return $g(a,vt,e)}function $g(e,a,o){if(a=Wd(e,a,Ig)[0],e=Xl(Ga)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var l=yi(a)}catch(x){throw x===eo?Pl:x}else l=a;a=Lt();var d=a.queue,m=d.dispatch;return o!==a.memoizedState&&($e.flags|=2048,so(9,{destroy:void 0},p_.bind(null,d,o),null)),[l,m,e]}function p_(e,a){e.action=a}function Gg(e){var a=Lt(),o=vt;if(o!==null)return $g(a,o,e);Lt(),a=a.memoizedState,o=Lt();var l=o.queue.dispatch;return o.memoizedState=e,[a,l,!1]}function so(e,a,o,l){return e={tag:e,create:o,deps:l,inst:a,next:null},a=$e.updateQueue,a===null&&(a=Yl(),$e.updateQueue=a),o=a.lastEffect,o===null?a.lastEffect=e.next=e:(l=o.next,o.next=e,e.next=l,a.lastEffect=e),e}function Yg(){return Lt().memoizedState}function Kl(e,a,o,l){var d=pn();$e.flags|=e,d.memoizedState=so(1|a,{destroy:void 0},o,l===void 0?null:l)}function Ql(e,a,o,l){var d=Lt();l=l===void 0?null:l;var m=d.memoizedState.inst;vt!==null&&l!==null&&Gd(l,vt.memoizedState.deps)?d.memoizedState=so(a,m,o,l):($e.flags|=e,d.memoizedState=so(1|a,m,o,l))}function Zg(e,a){Kl(8390656,8,e,a)}function nf(e,a){Ql(2048,8,e,a)}function g_(e){$e.flags|=4;var a=$e.updateQueue;if(a===null)a=Yl(),$e.updateQueue=a,a.events=[e];else{var o=a.events;o===null?a.events=[e]:o.push(e)}}function Xg(e){var a=Lt().memoizedState;return g_({ref:a,nextImpl:e}),function(){if((ft&2)!==0)throw Error(s(440));return a.impl.apply(void 0,arguments)}}function Kg(e,a){return Ql(4,2,e,a)}function Qg(e,a){return Ql(4,4,e,a)}function Wg(e,a){if(typeof a=="function"){e=e();var o=a(e);return function(){typeof o=="function"?o():a(null)}}if(a!=null)return e=e(),a.current=e,function(){a.current=null}}function Jg(e,a,o){o=o!=null?o.concat([e]):null,Ql(4,4,Wg.bind(null,a,e),o)}function af(){}function ev(e,a){var o=Lt();a=a===void 0?null:a;var l=o.memoizedState;return a!==null&&Gd(a,l[1])?l[0]:(o.memoizedState=[e,a],e)}function tv(e,a){var o=Lt();a=a===void 0?null:a;var l=o.memoizedState;if(a!==null&&Gd(a,l[1]))return l[0];if(l=e(),ms){an(!0);try{e()}finally{an(!1)}}return o.memoizedState=[l,a],l}function rf(e,a,o){return o===void 0||($a&1073741824)!==0&&(tt&261930)===0?e.memoizedState=a:(e.memoizedState=o,e=ny(),$e.lanes|=e,Cr|=e,o)}function nv(e,a,o,l){return Mn(o,a)?o:no.current!==null?(e=rf(e,o,l),Mn(e,a)||(qt=!0),e):($a&42)===0||($a&1073741824)!==0&&(tt&261930)===0?(qt=!0,e.memoizedState=o):(e=ny(),$e.lanes|=e,Cr|=e,a)}function av(e,a,o,l,d){var m=K.p;K.p=m!==0&&8>m?m:8;var x=T.T,N={};T.T=N,lf(e,!1,a,o);try{var M=d(),q=T.S;if(q!==null&&q(N,M),M!==null&&typeof M=="object"&&typeof M.then=="function"){var re=d_(M,l);bi(e,a,re,Pn(e))}else bi(e,a,l,Pn(e))}catch(ue){bi(e,a,{then:function(){},status:"rejected",reason:ue},Pn())}finally{K.p=m,x!==null&&N.types!==null&&(x.types=N.types),T.T=x}}function v_(){}function sf(e,a,o,l){if(e.tag!==5)throw Error(s(476));var d=rv(e).queue;av(e,d,a,te,o===null?v_:function(){return sv(e),o(l)})}function rv(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:te,baseState:te,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ga,lastRenderedState:te},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ga,lastRenderedState:o},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function sv(e){var a=rv(e);a.next===null&&(a=e.alternate.memoizedState),bi(e,a.next.queue,{},Pn())}function of(){return on(Li)}function ov(){return Lt().memoizedState}function iv(){return Lt().memoizedState}function y_(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var o=Pn();e=br(o);var l=xr(a,e,o);l!==null&&(An(l,a,o),hi(l,a,o)),a={cache:zd()},e.payload=a;return}a=a.return}}function b_(e,a,o){var l=Pn();o={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Wl(e)?cv(a,o):(o=_d(e,a,o,l),o!==null&&(An(o,e,l),uv(o,a,l)))}function lv(e,a,o){var l=Pn();bi(e,a,o,l)}function bi(e,a,o,l){var d={lane:l,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Wl(e))cv(a,d);else{var m=e.alternate;if(e.lanes===0&&(m===null||m.lanes===0)&&(m=a.lastRenderedReducer,m!==null))try{var x=a.lastRenderedState,N=m(x,o);if(d.hasEagerState=!0,d.eagerState=N,Mn(N,x))return kl(e,a,d,0),wt===null&&jl(),!1}catch{}finally{}if(o=_d(e,a,d,l),o!==null)return An(o,e,l),uv(o,a,l),!0}return!1}function lf(e,a,o,l){if(l={lane:2,revertLane:Hf(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Wl(e)){if(a)throw Error(s(479))}else a=_d(e,o,l,2),a!==null&&An(a,e,2)}function Wl(e){var a=e.alternate;return e===$e||a!==null&&a===$e}function cv(e,a){ao=$l=!0;var o=e.pending;o===null?a.next=a:(a.next=o.next,o.next=a),e.pending=a}function uv(e,a,o){if((o&4194048)!==0){var l=a.lanes;l&=e.pendingLanes,o|=l,a.lanes=o,xn(e,o)}}var xi={readContext:on,use:Zl,useCallback:Ot,useContext:Ot,useEffect:Ot,useImperativeHandle:Ot,useLayoutEffect:Ot,useInsertionEffect:Ot,useMemo:Ot,useReducer:Ot,useRef:Ot,useState:Ot,useDebugValue:Ot,useDeferredValue:Ot,useTransition:Ot,useSyncExternalStore:Ot,useId:Ot,useHostTransitionStatus:Ot,useFormState:Ot,useActionState:Ot,useOptimistic:Ot,useMemoCache:Ot,useCacheRefresh:Ot};xi.useEffectEvent=Ot;var dv={readContext:on,use:Zl,useCallback:function(e,a){return pn().memoizedState=[e,a===void 0?null:a],e},useContext:on,useEffect:Zg,useImperativeHandle:function(e,a,o){o=o!=null?o.concat([e]):null,Kl(4194308,4,Wg.bind(null,a,e),o)},useLayoutEffect:function(e,a){return Kl(4194308,4,e,a)},useInsertionEffect:function(e,a){Kl(4,2,e,a)},useMemo:function(e,a){var o=pn();a=a===void 0?null:a;var l=e();if(ms){an(!0);try{e()}finally{an(!1)}}return o.memoizedState=[l,a],l},useReducer:function(e,a,o){var l=pn();if(o!==void 0){var d=o(a);if(ms){an(!0);try{o(a)}finally{an(!1)}}}else d=a;return l.memoizedState=l.baseState=d,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:d},l.queue=e,e=e.dispatch=b_.bind(null,$e,e),[l.memoizedState,e]},useRef:function(e){var a=pn();return e={current:e},a.memoizedState=e},useState:function(e){e=ef(e);var a=e.queue,o=lv.bind(null,$e,a);return a.dispatch=o,[e.memoizedState,o]},useDebugValue:af,useDeferredValue:function(e,a){var o=pn();return rf(o,e,a)},useTransition:function(){var e=ef(!1);return e=av.bind(null,$e,e.queue,!0,!1),pn().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,o){var l=$e,d=pn();if(rt){if(o===void 0)throw Error(s(407));o=o()}else{if(o=a(),wt===null)throw Error(s(349));(tt&127)!==0||kg(l,a,o)}d.memoizedState=o;var m={value:o,getSnapshot:a};return d.queue=m,Zg(Dg.bind(null,l,m,e),[e]),l.flags|=2048,so(9,{destroy:void 0},Mg.bind(null,l,m,o,a),null),o},useId:function(){var e=pn(),a=wt.identifierPrefix;if(rt){var o=Sa,l=wa;o=(l&~(1<<32-Ht(l)-1)).toString(32)+o,a="_"+a+"R_"+o,o=Gl++,0<o&&(a+="H"+o.toString(32)),a+="_"}else o=f_++,a="_"+a+"r_"+o.toString(32)+"_";return e.memoizedState=a},useHostTransitionStatus:of,useFormState:qg,useActionState:qg,useOptimistic:function(e){var a=pn();a.memoizedState=a.baseState=e;var o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=o,a=lf.bind(null,$e,!0,o),o.dispatch=a,[e,a]},useMemoCache:Qd,useCacheRefresh:function(){return pn().memoizedState=y_.bind(null,$e)},useEffectEvent:function(e){var a=pn(),o={impl:e};return a.memoizedState=o,function(){if((ft&2)!==0)throw Error(s(440));return o.impl.apply(void 0,arguments)}}},cf={readContext:on,use:Zl,useCallback:ev,useContext:on,useEffect:nf,useImperativeHandle:Jg,useInsertionEffect:Kg,useLayoutEffect:Qg,useMemo:tv,useReducer:Xl,useRef:Yg,useState:function(){return Xl(Ga)},useDebugValue:af,useDeferredValue:function(e,a){var o=Lt();return nv(o,vt.memoizedState,e,a)},useTransition:function(){var e=Xl(Ga)[0],a=Lt().memoizedState;return[typeof e=="boolean"?e:yi(e),a]},useSyncExternalStore:jg,useId:ov,useHostTransitionStatus:of,useFormState:Fg,useActionState:Fg,useOptimistic:function(e,a){var o=Lt();return Ug(o,vt,e,a)},useMemoCache:Qd,useCacheRefresh:iv};cf.useEffectEvent=Xg;var fv={readContext:on,use:Zl,useCallback:ev,useContext:on,useEffect:nf,useImperativeHandle:Jg,useInsertionEffect:Kg,useLayoutEffect:Qg,useMemo:tv,useReducer:Jd,useRef:Yg,useState:function(){return Jd(Ga)},useDebugValue:af,useDeferredValue:function(e,a){var o=Lt();return vt===null?rf(o,e,a):nv(o,vt.memoizedState,e,a)},useTransition:function(){var e=Jd(Ga)[0],a=Lt().memoizedState;return[typeof e=="boolean"?e:yi(e),a]},useSyncExternalStore:jg,useId:ov,useHostTransitionStatus:of,useFormState:Gg,useActionState:Gg,useOptimistic:function(e,a){var o=Lt();return vt!==null?Ug(o,vt,e,a):(o.baseState=e,[e,o.queue.dispatch])},useMemoCache:Qd,useCacheRefresh:iv};fv.useEffectEvent=Xg;function uf(e,a,o,l){a=e.memoizedState,o=o(l,a),o=o==null?a:v({},a,o),e.memoizedState=o,e.lanes===0&&(e.updateQueue.baseState=o)}var df={enqueueSetState:function(e,a,o){e=e._reactInternals;var l=Pn(),d=br(l);d.payload=a,o!=null&&(d.callback=o),a=xr(e,d,l),a!==null&&(An(a,e,l),hi(a,e,l))},enqueueReplaceState:function(e,a,o){e=e._reactInternals;var l=Pn(),d=br(l);d.tag=1,d.payload=a,o!=null&&(d.callback=o),a=xr(e,d,l),a!==null&&(An(a,e,l),hi(a,e,l))},enqueueForceUpdate:function(e,a){e=e._reactInternals;var o=Pn(),l=br(o);l.tag=2,a!=null&&(l.callback=a),a=xr(e,l,o),a!==null&&(An(a,e,o),hi(a,e,o))}};function mv(e,a,o,l,d,m,x){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(l,m,x):a.prototype&&a.prototype.isPureReactComponent?!oi(o,l)||!oi(d,m):!0}function hv(e,a,o,l){e=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(o,l),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(o,l),a.state!==e&&df.enqueueReplaceState(a,a.state,null)}function hs(e,a){var o=a;if("ref"in a){o={};for(var l in a)l!=="ref"&&(o[l]=a[l])}if(e=e.defaultProps){o===a&&(o=v({},o));for(var d in e)o[d]===void 0&&(o[d]=e[d])}return o}function pv(e){Ol(e)}function gv(e){console.error(e)}function vv(e){Ol(e)}function Jl(e,a){try{var o=e.onUncaughtError;o(a.value,{componentStack:a.stack})}catch(l){setTimeout(function(){throw l})}}function yv(e,a,o){try{var l=e.onCaughtError;l(o.value,{componentStack:o.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(d){setTimeout(function(){throw d})}}function ff(e,a,o){return o=br(o),o.tag=3,o.payload={element:null},o.callback=function(){Jl(e,a)},o}function bv(e){return e=br(e),e.tag=3,e}function xv(e,a,o,l){var d=o.type.getDerivedStateFromError;if(typeof d=="function"){var m=l.value;e.payload=function(){return d(m)},e.callback=function(){yv(a,o,l)}}var x=o.stateNode;x!==null&&typeof x.componentDidCatch=="function"&&(e.callback=function(){yv(a,o,l),typeof d!="function"&&(Nr===null?Nr=new Set([this]):Nr.add(this));var N=l.stack;this.componentDidCatch(l.value,{componentStack:N!==null?N:""})})}function x_(e,a,o,l,d){if(o.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){if(a=o.alternate,a!==null&&Qs(a,o,d,!0),o=zn.current,o!==null){switch(o.tag){case 31:case 13:return ta===null?dc():o.alternate===null&&jt===0&&(jt=3),o.flags&=-257,o.flags|=65536,o.lanes=d,l===Hl?o.flags|=16384:(a=o.updateQueue,a===null?o.updateQueue=new Set([l]):a.add(l),Uf(e,l,d)),!1;case 22:return o.flags|=65536,l===Hl?o.flags|=16384:(a=o.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([l])},o.updateQueue=a):(o=a.retryQueue,o===null?a.retryQueue=new Set([l]):o.add(l)),Uf(e,l,d)),!1}throw Error(s(435,o.tag))}return Uf(e,l,d),dc(),!1}if(rt)return a=zn.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=d,l!==Od&&(e=Error(s(422),{cause:l}),ci(Qn(e,o)))):(l!==Od&&(a=Error(s(423),{cause:l}),ci(Qn(a,o))),e=e.current.alternate,e.flags|=65536,d&=-d,e.lanes|=d,l=Qn(l,o),d=ff(e.stateNode,l,d),Vd(e,d),jt!==4&&(jt=2)),!1;var m=Error(s(520),{cause:l});if(m=Qn(m,o),Ai===null?Ai=[m]:Ai.push(m),jt!==4&&(jt=2),a===null)return!0;l=Qn(l,o),o=a;do{switch(o.tag){case 3:return o.flags|=65536,e=d&-d,o.lanes|=e,e=ff(o.stateNode,l,e),Vd(o,e),!1;case 1:if(a=o.type,m=o.stateNode,(o.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||m!==null&&typeof m.componentDidCatch=="function"&&(Nr===null||!Nr.has(m))))return o.flags|=65536,d&=-d,o.lanes|=d,d=bv(d),xv(d,e,o,l),Vd(o,d),!1}o=o.return}while(o!==null);return!1}var mf=Error(s(461)),qt=!1;function ln(e,a,o,l){a.child=e===null?_g(a,null,o,l):fs(a,e.child,o,l)}function wv(e,a,o,l,d){o=o.render;var m=a.ref;if("ref"in l){var x={};for(var N in l)N!=="ref"&&(x[N]=l[N])}else x=l;return ls(a),l=Yd(e,a,o,x,m,d),N=Zd(),e!==null&&!qt?(Xd(e,a,d),Ya(e,a,d)):(rt&&N&&Ad(a),a.flags|=1,ln(e,a,l,d),a.child)}function Sv(e,a,o,l,d){if(e===null){var m=o.type;return typeof m=="function"&&!Cd(m)&&m.defaultProps===void 0&&o.compare===null?(a.tag=15,a.type=m,Ev(e,a,m,l,d)):(e=Dl(o.type,null,l,a,a.mode,d),e.ref=a.ref,e.return=a,a.child=e)}if(m=e.child,!wf(e,d)){var x=m.memoizedProps;if(o=o.compare,o=o!==null?o:oi,o(x,l)&&e.ref===a.ref)return Ya(e,a,d)}return a.flags|=1,e=Va(m,l),e.ref=a.ref,e.return=a,a.child=e}function Ev(e,a,o,l,d){if(e!==null){var m=e.memoizedProps;if(oi(m,l)&&e.ref===a.ref)if(qt=!1,a.pendingProps=l=m,wf(e,d))(e.flags&131072)!==0&&(qt=!0);else return a.lanes=e.lanes,Ya(e,a,d)}return hf(e,a,o,l,d)}function _v(e,a,o,l){var d=l.children,m=e!==null?e.memoizedState:null;if(e===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),l.mode==="hidden"){if((a.flags&128)!==0){if(m=m!==null?m.baseLanes|o:o,e!==null){for(l=a.child=e.child,d=0;l!==null;)d=d|l.lanes|l.childLanes,l=l.sibling;l=d&~m}else l=0,a.child=null;return Cv(e,a,m,o,l)}if((o&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},e!==null&&Bl(a,m!==null?m.cachePool:null),m!==null?Rg(a,m):qd(),Ag(a);else return l=a.lanes=536870912,Cv(e,a,m!==null?m.baseLanes|o:o,o,l)}else m!==null?(Bl(a,m.cachePool),Rg(a,m),Sr(),a.memoizedState=null):(e!==null&&Bl(a,null),qd(),Sr());return ln(e,a,d,o),a.child}function wi(e,a){return e!==null&&e.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Cv(e,a,o,l,d){var m=Ud();return m=m===null?null:{parent:Vt._currentValue,pool:m},a.memoizedState={baseLanes:o,cachePool:m},e!==null&&Bl(a,null),qd(),Ag(a),e!==null&&Qs(e,a,l,!0),a.childLanes=d,null}function ec(e,a){return a=nc({mode:a.mode,children:a.children},e.mode),a.ref=e.ref,e.child=a,a.return=e,a}function Nv(e,a,o){return fs(a,e.child,null,o),e=ec(a,a.pendingProps),e.flags|=2,Ln(a),a.memoizedState=null,e}function w_(e,a,o){var l=a.pendingProps,d=(a.flags&128)!==0;if(a.flags&=-129,e===null){if(rt){if(l.mode==="hidden")return e=ec(a,l),a.lanes=536870912,wi(null,e);if($d(a),(e=St)?(e=By(e,ea),e=e!==null&&e.data==="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:hr!==null?{id:wa,overflow:Sa}:null,retryLane:536870912,hydrationErrors:null},o=cg(e),o.return=a,a.child=o,sn=a,St=null)):e=null,e===null)throw gr(a);return a.lanes=536870912,null}return ec(a,l)}var m=e.memoizedState;if(m!==null){var x=m.dehydrated;if($d(a),d)if(a.flags&256)a.flags&=-257,a=Nv(e,a,o);else if(a.memoizedState!==null)a.child=e.child,a.flags|=128,a=null;else throw Error(s(558));else if(qt||Qs(e,a,o,!1),d=(o&e.childLanes)!==0,qt||d){if(l=wt,l!==null&&(x=wn(l,o),x!==0&&x!==m.retryLane))throw m.retryLane=x,rs(e,x),An(l,e,x),mf;dc(),a=Nv(e,a,o)}else e=m.treeContext,St=na(x.nextSibling),sn=a,rt=!0,pr=null,ea=!1,e!==null&&fg(a,e),a=ec(a,l),a.flags|=4096;return a}return e=Va(e.child,{mode:l.mode,children:l.children}),e.ref=a.ref,a.child=e,e.return=a,e}function tc(e,a){var o=a.ref;if(o===null)e!==null&&e.ref!==null&&(a.flags|=4194816);else{if(typeof o!="function"&&typeof o!="object")throw Error(s(284));(e===null||e.ref!==o)&&(a.flags|=4194816)}}function hf(e,a,o,l,d){return ls(a),o=Yd(e,a,o,l,void 0,d),l=Zd(),e!==null&&!qt?(Xd(e,a,d),Ya(e,a,d)):(rt&&l&&Ad(a),a.flags|=1,ln(e,a,o,d),a.child)}function Rv(e,a,o,l,d,m){return ls(a),a.updateQueue=null,o=Og(a,l,o,d),Tg(e),l=Zd(),e!==null&&!qt?(Xd(e,a,m),Ya(e,a,m)):(rt&&l&&Ad(a),a.flags|=1,ln(e,a,o,m),a.child)}function Av(e,a,o,l,d){if(ls(a),a.stateNode===null){var m=Ys,x=o.contextType;typeof x=="object"&&x!==null&&(m=on(x)),m=new o(l,m),a.memoizedState=m.state!==null&&m.state!==void 0?m.state:null,m.updater=df,a.stateNode=m,m._reactInternals=a,m=a.stateNode,m.props=l,m.state=a.memoizedState,m.refs={},Pd(a),x=o.contextType,m.context=typeof x=="object"&&x!==null?on(x):Ys,m.state=a.memoizedState,x=o.getDerivedStateFromProps,typeof x=="function"&&(uf(a,o,x,l),m.state=a.memoizedState),typeof o.getDerivedStateFromProps=="function"||typeof m.getSnapshotBeforeUpdate=="function"||typeof m.UNSAFE_componentWillMount!="function"&&typeof m.componentWillMount!="function"||(x=m.state,typeof m.componentWillMount=="function"&&m.componentWillMount(),typeof m.UNSAFE_componentWillMount=="function"&&m.UNSAFE_componentWillMount(),x!==m.state&&df.enqueueReplaceState(m,m.state,null),gi(a,l,m,d),pi(),m.state=a.memoizedState),typeof m.componentDidMount=="function"&&(a.flags|=4194308),l=!0}else if(e===null){m=a.stateNode;var N=a.memoizedProps,M=hs(o,N);m.props=M;var q=m.context,re=o.contextType;x=Ys,typeof re=="object"&&re!==null&&(x=on(re));var ue=o.getDerivedStateFromProps;re=typeof ue=="function"||typeof m.getSnapshotBeforeUpdate=="function",N=a.pendingProps!==N,re||typeof m.UNSAFE_componentWillReceiveProps!="function"&&typeof m.componentWillReceiveProps!="function"||(N||q!==x)&&hv(a,m,l,x),yr=!1;var Z=a.memoizedState;m.state=Z,gi(a,l,m,d),pi(),q=a.memoizedState,N||Z!==q||yr?(typeof ue=="function"&&(uf(a,o,ue,l),q=a.memoizedState),(M=yr||mv(a,o,M,l,Z,q,x))?(re||typeof m.UNSAFE_componentWillMount!="function"&&typeof m.componentWillMount!="function"||(typeof m.componentWillMount=="function"&&m.componentWillMount(),typeof m.UNSAFE_componentWillMount=="function"&&m.UNSAFE_componentWillMount()),typeof m.componentDidMount=="function"&&(a.flags|=4194308)):(typeof m.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=l,a.memoizedState=q),m.props=l,m.state=q,m.context=x,l=M):(typeof m.componentDidMount=="function"&&(a.flags|=4194308),l=!1)}else{m=a.stateNode,Hd(e,a),x=a.memoizedProps,re=hs(o,x),m.props=re,ue=a.pendingProps,Z=m.context,q=o.contextType,M=Ys,typeof q=="object"&&q!==null&&(M=on(q)),N=o.getDerivedStateFromProps,(q=typeof N=="function"||typeof m.getSnapshotBeforeUpdate=="function")||typeof m.UNSAFE_componentWillReceiveProps!="function"&&typeof m.componentWillReceiveProps!="function"||(x!==ue||Z!==M)&&hv(a,m,l,M),yr=!1,Z=a.memoizedState,m.state=Z,gi(a,l,m,d),pi();var ee=a.memoizedState;x!==ue||Z!==ee||yr||e!==null&&e.dependencies!==null&&Ll(e.dependencies)?(typeof N=="function"&&(uf(a,o,N,l),ee=a.memoizedState),(re=yr||mv(a,o,re,l,Z,ee,M)||e!==null&&e.dependencies!==null&&Ll(e.dependencies))?(q||typeof m.UNSAFE_componentWillUpdate!="function"&&typeof m.componentWillUpdate!="function"||(typeof m.componentWillUpdate=="function"&&m.componentWillUpdate(l,ee,M),typeof m.UNSAFE_componentWillUpdate=="function"&&m.UNSAFE_componentWillUpdate(l,ee,M)),typeof m.componentDidUpdate=="function"&&(a.flags|=4),typeof m.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof m.componentDidUpdate!="function"||x===e.memoizedProps&&Z===e.memoizedState||(a.flags|=4),typeof m.getSnapshotBeforeUpdate!="function"||x===e.memoizedProps&&Z===e.memoizedState||(a.flags|=1024),a.memoizedProps=l,a.memoizedState=ee),m.props=l,m.state=ee,m.context=M,l=re):(typeof m.componentDidUpdate!="function"||x===e.memoizedProps&&Z===e.memoizedState||(a.flags|=4),typeof m.getSnapshotBeforeUpdate!="function"||x===e.memoizedProps&&Z===e.memoizedState||(a.flags|=1024),l=!1)}return m=l,tc(e,a),l=(a.flags&128)!==0,m||l?(m=a.stateNode,o=l&&typeof o.getDerivedStateFromError!="function"?null:m.render(),a.flags|=1,e!==null&&l?(a.child=fs(a,e.child,null,d),a.child=fs(a,null,o,d)):ln(e,a,o,d),a.memoizedState=m.state,e=a.child):e=Ya(e,a,d),e}function Tv(e,a,o,l){return os(),a.flags|=256,ln(e,a,o,l),a.child}var pf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function gf(e){return{baseLanes:e,cachePool:yg()}}function vf(e,a,o){return e=e!==null?e.childLanes&~o:0,a&&(e|=Bn),e}function Ov(e,a,o){var l=a.pendingProps,d=!1,m=(a.flags&128)!==0,x;if((x=m)||(x=e!==null&&e.memoizedState===null?!1:(zt.current&2)!==0),x&&(d=!0,a.flags&=-129),x=(a.flags&32)!==0,a.flags&=-33,e===null){if(rt){if(d?wr(a):Sr(),(e=St)?(e=By(e,ea),e=e!==null&&e.data!=="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:hr!==null?{id:wa,overflow:Sa}:null,retryLane:536870912,hydrationErrors:null},o=cg(e),o.return=a,a.child=o,sn=a,St=null)):e=null,e===null)throw gr(a);return Jf(e)?a.lanes=32:a.lanes=536870912,null}var N=l.children;return l=l.fallback,d?(Sr(),d=a.mode,N=nc({mode:"hidden",children:N},d),l=ss(l,d,o,null),N.return=a,l.return=a,N.sibling=l,a.child=N,l=a.child,l.memoizedState=gf(o),l.childLanes=vf(e,x,o),a.memoizedState=pf,wi(null,l)):(wr(a),yf(a,N))}var M=e.memoizedState;if(M!==null&&(N=M.dehydrated,N!==null)){if(m)a.flags&256?(wr(a),a.flags&=-257,a=bf(e,a,o)):a.memoizedState!==null?(Sr(),a.child=e.child,a.flags|=128,a=null):(Sr(),N=l.fallback,d=a.mode,l=nc({mode:"visible",children:l.children},d),N=ss(N,d,o,null),N.flags|=2,l.return=a,N.return=a,l.sibling=N,a.child=l,fs(a,e.child,null,o),l=a.child,l.memoizedState=gf(o),l.childLanes=vf(e,x,o),a.memoizedState=pf,a=wi(null,l));else if(wr(a),Jf(N)){if(x=N.nextSibling&&N.nextSibling.dataset,x)var q=x.dgst;x=q,l=Error(s(419)),l.stack="",l.digest=x,ci({value:l,source:null,stack:null}),a=bf(e,a,o)}else if(qt||Qs(e,a,o,!1),x=(o&e.childLanes)!==0,qt||x){if(x=wt,x!==null&&(l=wn(x,o),l!==0&&l!==M.retryLane))throw M.retryLane=l,rs(e,l),An(x,e,l),mf;Wf(N)||dc(),a=bf(e,a,o)}else Wf(N)?(a.flags|=192,a.child=e.child,a=null):(e=M.treeContext,St=na(N.nextSibling),sn=a,rt=!0,pr=null,ea=!1,e!==null&&fg(a,e),a=yf(a,l.children),a.flags|=4096);return a}return d?(Sr(),N=l.fallback,d=a.mode,M=e.child,q=M.sibling,l=Va(M,{mode:"hidden",children:l.children}),l.subtreeFlags=M.subtreeFlags&65011712,q!==null?N=Va(q,N):(N=ss(N,d,o,null),N.flags|=2),N.return=a,l.return=a,l.sibling=N,a.child=l,wi(null,l),l=a.child,N=e.child.memoizedState,N===null?N=gf(o):(d=N.cachePool,d!==null?(M=Vt._currentValue,d=d.parent!==M?{parent:M,pool:M}:d):d=yg(),N={baseLanes:N.baseLanes|o,cachePool:d}),l.memoizedState=N,l.childLanes=vf(e,x,o),a.memoizedState=pf,wi(e.child,l)):(wr(a),o=e.child,e=o.sibling,o=Va(o,{mode:"visible",children:l.children}),o.return=a,o.sibling=null,e!==null&&(x=a.deletions,x===null?(a.deletions=[e],a.flags|=16):x.push(e)),a.child=o,a.memoizedState=null,o)}function yf(e,a){return a=nc({mode:"visible",children:a},e.mode),a.return=e,e.child=a}function nc(e,a){return e=Dn(22,e,null,a),e.lanes=0,e}function bf(e,a,o){return fs(a,e.child,null,o),e=yf(a,a.pendingProps.children),e.flags|=2,a.memoizedState=null,e}function jv(e,a,o){e.lanes|=a;var l=e.alternate;l!==null&&(l.lanes|=a),Md(e.return,a,o)}function xf(e,a,o,l,d,m){var x=e.memoizedState;x===null?e.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:l,tail:o,tailMode:d,treeForkCount:m}:(x.isBackwards=a,x.rendering=null,x.renderingStartTime=0,x.last=l,x.tail=o,x.tailMode=d,x.treeForkCount=m)}function kv(e,a,o){var l=a.pendingProps,d=l.revealOrder,m=l.tail;l=l.children;var x=zt.current,N=(x&2)!==0;if(N?(x=x&1|2,a.flags|=128):x&=1,L(zt,x),ln(e,a,l,o),l=rt?li:0,!N&&e!==null&&(e.flags&128)!==0)e:for(e=a.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&jv(e,o,a);else if(e.tag===19)jv(e,o,a);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===a)break e;for(;e.sibling===null;){if(e.return===null||e.return===a)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(d){case"forwards":for(o=a.child,d=null;o!==null;)e=o.alternate,e!==null&&Fl(e)===null&&(d=o),o=o.sibling;o=d,o===null?(d=a.child,a.child=null):(d=o.sibling,o.sibling=null),xf(a,!1,d,o,m,l);break;case"backwards":case"unstable_legacy-backwards":for(o=null,d=a.child,a.child=null;d!==null;){if(e=d.alternate,e!==null&&Fl(e)===null){a.child=d;break}e=d.sibling,d.sibling=o,o=d,d=e}xf(a,!0,o,null,m,l);break;case"together":xf(a,!1,null,null,void 0,l);break;default:a.memoizedState=null}return a.child}function Ya(e,a,o){if(e!==null&&(a.dependencies=e.dependencies),Cr|=a.lanes,(o&a.childLanes)===0)if(e!==null){if(Qs(e,a,o,!1),(o&a.childLanes)===0)return null}else return null;if(e!==null&&a.child!==e.child)throw Error(s(153));if(a.child!==null){for(e=a.child,o=Va(e,e.pendingProps),a.child=o,o.return=a;e.sibling!==null;)e=e.sibling,o=o.sibling=Va(e,e.pendingProps),o.return=a;o.sibling=null}return a.child}function wf(e,a){return(e.lanes&a)!==0?!0:(e=e.dependencies,!!(e!==null&&Ll(e)))}function S_(e,a,o){switch(a.tag){case 3:Q(a,a.stateNode.containerInfo),vr(a,Vt,e.memoizedState.cache),os();break;case 27:case 5:Re(a);break;case 4:Q(a,a.stateNode.containerInfo);break;case 10:vr(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,$d(a),null;break;case 13:var l=a.memoizedState;if(l!==null)return l.dehydrated!==null?(wr(a),a.flags|=128,null):(o&a.child.childLanes)!==0?Ov(e,a,o):(wr(a),e=Ya(e,a,o),e!==null?e.sibling:null);wr(a);break;case 19:var d=(e.flags&128)!==0;if(l=(o&a.childLanes)!==0,l||(Qs(e,a,o,!1),l=(o&a.childLanes)!==0),d){if(l)return kv(e,a,o);a.flags|=128}if(d=a.memoizedState,d!==null&&(d.rendering=null,d.tail=null,d.lastEffect=null),L(zt,zt.current),l)break;return null;case 22:return a.lanes=0,_v(e,a,o,a.pendingProps);case 24:vr(a,Vt,e.memoizedState.cache)}return Ya(e,a,o)}function Mv(e,a,o){if(e!==null)if(e.memoizedProps!==a.pendingProps)qt=!0;else{if(!wf(e,o)&&(a.flags&128)===0)return qt=!1,S_(e,a,o);qt=(e.flags&131072)!==0}else qt=!1,rt&&(a.flags&1048576)!==0&&dg(a,li,a.index);switch(a.lanes=0,a.tag){case 16:e:{var l=a.pendingProps;if(e=us(a.elementType),a.type=e,typeof e=="function")Cd(e)?(l=hs(e,l),a.tag=1,a=Av(null,a,e,l,o)):(a.tag=0,a=hf(null,a,e,l,o));else{if(e!=null){var d=e.$$typeof;if(d===D){a.tag=11,a=wv(null,a,e,l,o);break e}else if(d===U){a.tag=14,a=Sv(null,a,e,l,o);break e}}throw a=he(e)||e,Error(s(306,a,""))}}return a;case 0:return hf(e,a,a.type,a.pendingProps,o);case 1:return l=a.type,d=hs(l,a.pendingProps),Av(e,a,l,d,o);case 3:e:{if(Q(a,a.stateNode.containerInfo),e===null)throw Error(s(387));l=a.pendingProps;var m=a.memoizedState;d=m.element,Hd(e,a),gi(a,l,null,o);var x=a.memoizedState;if(l=x.cache,vr(a,Vt,l),l!==m.cache&&Dd(a,[Vt],o,!0),pi(),l=x.element,m.isDehydrated)if(m={element:l,isDehydrated:!1,cache:x.cache},a.updateQueue.baseState=m,a.memoizedState=m,a.flags&256){a=Tv(e,a,l,o);break e}else if(l!==d){d=Qn(Error(s(424)),a),ci(d),a=Tv(e,a,l,o);break e}else{switch(e=a.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName==="HTML"?e.ownerDocument.body:e}for(St=na(e.firstChild),sn=a,rt=!0,pr=null,ea=!0,o=_g(a,null,l,o),a.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling}else{if(os(),l===d){a=Ya(e,a,o);break e}ln(e,a,l,o)}a=a.child}return a;case 26:return tc(e,a),e===null?(o=Fy(a.type,null,a.pendingProps,null))?a.memoizedState=o:rt||(o=a.type,e=a.pendingProps,l=yc(ie.current).createElement(o),l[rn]=a,l[Sn]=e,cn(l,o,e),tn(l),a.stateNode=l):a.memoizedState=Fy(a.type,e.memoizedProps,a.pendingProps,e.memoizedState),null;case 27:return Re(a),e===null&&rt&&(l=a.stateNode=Vy(a.type,a.pendingProps,ie.current),sn=a,ea=!0,d=St,Or(a.type)?(em=d,St=na(l.firstChild)):St=d),ln(e,a,a.pendingProps.children,o),tc(e,a),e===null&&(a.flags|=4194304),a.child;case 5:return e===null&&rt&&((d=l=St)&&(l=W_(l,a.type,a.pendingProps,ea),l!==null?(a.stateNode=l,sn=a,St=na(l.firstChild),ea=!1,d=!0):d=!1),d||gr(a)),Re(a),d=a.type,m=a.pendingProps,x=e!==null?e.memoizedProps:null,l=m.children,Xf(d,m)?l=null:x!==null&&Xf(d,x)&&(a.flags|=32),a.memoizedState!==null&&(d=Yd(e,a,m_,null,null,o),Li._currentValue=d),tc(e,a),ln(e,a,l,o),a.child;case 6:return e===null&&rt&&((e=o=St)&&(o=J_(o,a.pendingProps,ea),o!==null?(a.stateNode=o,sn=a,St=null,e=!0):e=!1),e||gr(a)),null;case 13:return Ov(e,a,o);case 4:return Q(a,a.stateNode.containerInfo),l=a.pendingProps,e===null?a.child=fs(a,null,l,o):ln(e,a,l,o),a.child;case 11:return wv(e,a,a.type,a.pendingProps,o);case 7:return ln(e,a,a.pendingProps,o),a.child;case 8:return ln(e,a,a.pendingProps.children,o),a.child;case 12:return ln(e,a,a.pendingProps.children,o),a.child;case 10:return l=a.pendingProps,vr(a,a.type,l.value),ln(e,a,l.children,o),a.child;case 9:return d=a.type._context,l=a.pendingProps.children,ls(a),d=on(d),l=l(d),a.flags|=1,ln(e,a,l,o),a.child;case 14:return Sv(e,a,a.type,a.pendingProps,o);case 15:return Ev(e,a,a.type,a.pendingProps,o);case 19:return kv(e,a,o);case 31:return w_(e,a,o);case 22:return _v(e,a,o,a.pendingProps);case 24:return ls(a),l=on(Vt),e===null?(d=Ud(),d===null&&(d=wt,m=zd(),d.pooledCache=m,m.refCount++,m!==null&&(d.pooledCacheLanes|=o),d=m),a.memoizedState={parent:l,cache:d},Pd(a),vr(a,Vt,d)):((e.lanes&o)!==0&&(Hd(e,a),gi(a,null,null,o),pi()),d=e.memoizedState,m=a.memoizedState,d.parent!==l?(d={parent:l,cache:l},a.memoizedState=d,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=d),vr(a,Vt,l)):(l=m.cache,vr(a,Vt,l),l!==d.cache&&Dd(a,[Vt],o,!0))),ln(e,a,a.pendingProps.children,o),a.child;case 29:throw a.pendingProps}throw Error(s(156,a.tag))}function Za(e){e.flags|=4}function Sf(e,a,o,l,d){if((a=(e.mode&32)!==0)&&(a=!1),a){if(e.flags|=16777216,(d&335544128)===d)if(e.stateNode.complete)e.flags|=8192;else if(oy())e.flags|=8192;else throw ds=Hl,Bd}else e.flags&=-16777217}function Dv(e,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Xy(a))if(oy())e.flags|=8192;else throw ds=Hl,Bd}function ac(e,a){a!==null&&(e.flags|=4),e.flags&16384&&(a=e.tag!==22?dn():536870912,e.lanes|=a,co|=a)}function Si(e,a){if(!rt)switch(e.tailMode){case"hidden":a=e.tail;for(var o=null;a!==null;)a.alternate!==null&&(o=a),a=a.sibling;o===null?e.tail=null:o.sibling=null;break;case"collapsed":o=e.tail;for(var l=null;o!==null;)o.alternate!==null&&(l=o),o=o.sibling;l===null?a||e.tail===null?e.tail=null:e.tail.sibling=null:l.sibling=null}}function Et(e){var a=e.alternate!==null&&e.alternate.child===e.child,o=0,l=0;if(a)for(var d=e.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags&65011712,l|=d.flags&65011712,d.return=e,d=d.sibling;else for(d=e.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags,l|=d.flags,d.return=e,d=d.sibling;return e.subtreeFlags|=l,e.childLanes=o,a}function E_(e,a,o){var l=a.pendingProps;switch(Td(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Et(a),null;case 1:return Et(a),null;case 3:return o=a.stateNode,l=null,e!==null&&(l=e.memoizedState.cache),a.memoizedState.cache!==l&&(a.flags|=2048),Fa(Vt),oe(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(e===null||e.child===null)&&(Ks(a)?Za(a):e===null||e.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,jd())),Et(a),null;case 26:var d=a.type,m=a.memoizedState;return e===null?(Za(a),m!==null?(Et(a),Dv(a,m)):(Et(a),Sf(a,d,null,l,o))):m?m!==e.memoizedState?(Za(a),Et(a),Dv(a,m)):(Et(a),a.flags&=-16777217):(e=e.memoizedProps,e!==l&&Za(a),Et(a),Sf(a,d,e,l,o)),null;case 27:if(et(a),o=ie.current,d=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&Za(a);else{if(!l){if(a.stateNode===null)throw Error(s(166));return Et(a),null}e=Y.current,Ks(a)?mg(a):(e=Vy(d,l,o),a.stateNode=e,Za(a))}return Et(a),null;case 5:if(et(a),d=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==l&&Za(a);else{if(!l){if(a.stateNode===null)throw Error(s(166));return Et(a),null}if(m=Y.current,Ks(a))mg(a);else{var x=yc(ie.current);switch(m){case 1:m=x.createElementNS("http://www.w3.org/2000/svg",d);break;case 2:m=x.createElementNS("http://www.w3.org/1998/Math/MathML",d);break;default:switch(d){case"svg":m=x.createElementNS("http://www.w3.org/2000/svg",d);break;case"math":m=x.createElementNS("http://www.w3.org/1998/Math/MathML",d);break;case"script":m=x.createElement("div"),m.innerHTML="<script><\/script>",m=m.removeChild(m.firstChild);break;case"select":m=typeof l.is=="string"?x.createElement("select",{is:l.is}):x.createElement("select"),l.multiple?m.multiple=!0:l.size&&(m.size=l.size);break;default:m=typeof l.is=="string"?x.createElement(d,{is:l.is}):x.createElement(d)}}m[rn]=a,m[Sn]=l;e:for(x=a.child;x!==null;){if(x.tag===5||x.tag===6)m.appendChild(x.stateNode);else if(x.tag!==4&&x.tag!==27&&x.child!==null){x.child.return=x,x=x.child;continue}if(x===a)break e;for(;x.sibling===null;){if(x.return===null||x.return===a)break e;x=x.return}x.sibling.return=x.return,x=x.sibling}a.stateNode=m;e:switch(cn(m,d,l),d){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}l&&Za(a)}}return Et(a),Sf(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,o),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==l&&Za(a);else{if(typeof l!="string"&&a.stateNode===null)throw Error(s(166));if(e=ie.current,Ks(a)){if(e=a.stateNode,o=a.memoizedProps,l=null,d=sn,d!==null)switch(d.tag){case 27:case 5:l=d.memoizedProps}e[rn]=a,e=!!(e.nodeValue===o||l!==null&&l.suppressHydrationWarning===!0||Oy(e.nodeValue,o)),e||gr(a,!0)}else e=yc(e).createTextNode(l),e[rn]=a,a.stateNode=e}return Et(a),null;case 31:if(o=a.memoizedState,e===null||e.memoizedState!==null){if(l=Ks(a),o!==null){if(e===null){if(!l)throw Error(s(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[rn]=a}else os(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Et(a),e=!1}else o=jd(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=o),e=!0;if(!e)return a.flags&256?(Ln(a),a):(Ln(a),null);if((a.flags&128)!==0)throw Error(s(558))}return Et(a),null;case 13:if(l=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(d=Ks(a),l!==null&&l.dehydrated!==null){if(e===null){if(!d)throw Error(s(318));if(d=a.memoizedState,d=d!==null?d.dehydrated:null,!d)throw Error(s(317));d[rn]=a}else os(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Et(a),d=!1}else d=jd(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=d),d=!0;if(!d)return a.flags&256?(Ln(a),a):(Ln(a),null)}return Ln(a),(a.flags&128)!==0?(a.lanes=o,a):(o=l!==null,e=e!==null&&e.memoizedState!==null,o&&(l=a.child,d=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(d=l.alternate.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==d&&(l.flags|=2048)),o!==e&&o&&(a.child.flags|=8192),ac(a,a.updateQueue),Et(a),null);case 4:return oe(),e===null&&Ff(a.stateNode.containerInfo),Et(a),null;case 10:return Fa(a.type),Et(a),null;case 19:if(X(zt),l=a.memoizedState,l===null)return Et(a),null;if(d=(a.flags&128)!==0,m=l.rendering,m===null)if(d)Si(l,!1);else{if(jt!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(m=Fl(e),m!==null){for(a.flags|=128,Si(l,!1),e=m.updateQueue,a.updateQueue=e,ac(a,e),a.subtreeFlags=0,e=o,o=a.child;o!==null;)lg(o,e),o=o.sibling;return L(zt,zt.current&1|2),rt&&Ia(a,l.treeForkCount),a.child}e=e.sibling}l.tail!==null&&V()>lc&&(a.flags|=128,d=!0,Si(l,!1),a.lanes=4194304)}else{if(!d)if(e=Fl(m),e!==null){if(a.flags|=128,d=!0,e=e.updateQueue,a.updateQueue=e,ac(a,e),Si(l,!0),l.tail===null&&l.tailMode==="hidden"&&!m.alternate&&!rt)return Et(a),null}else 2*V()-l.renderingStartTime>lc&&o!==536870912&&(a.flags|=128,d=!0,Si(l,!1),a.lanes=4194304);l.isBackwards?(m.sibling=a.child,a.child=m):(e=l.last,e!==null?e.sibling=m:a.child=m,l.last=m)}return l.tail!==null?(e=l.tail,l.rendering=e,l.tail=e.sibling,l.renderingStartTime=V(),e.sibling=null,o=zt.current,L(zt,d?o&1|2:o&1),rt&&Ia(a,l.treeForkCount),e):(Et(a),null);case 22:case 23:return Ln(a),Fd(),l=a.memoizedState!==null,e!==null?e.memoizedState!==null!==l&&(a.flags|=8192):l&&(a.flags|=8192),l?(o&536870912)!==0&&(a.flags&128)===0&&(Et(a),a.subtreeFlags&6&&(a.flags|=8192)):Et(a),o=a.updateQueue,o!==null&&ac(a,o.retryQueue),o=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(o=e.memoizedState.cachePool.pool),l=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(l=a.memoizedState.cachePool.pool),l!==o&&(a.flags|=2048),e!==null&&X(cs),null;case 24:return o=null,e!==null&&(o=e.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),Fa(Vt),Et(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function __(e,a){switch(Td(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return Fa(Vt),oe(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return et(a),null;case 31:if(a.memoizedState!==null){if(Ln(a),a.alternate===null)throw Error(s(340));os()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(Ln(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(s(340));os()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return X(zt),null;case 4:return oe(),null;case 10:return Fa(a.type),null;case 22:case 23:return Ln(a),Fd(),e!==null&&X(cs),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return Fa(Vt),null;case 25:return null;default:return null}}function zv(e,a){switch(Td(a),a.tag){case 3:Fa(Vt),oe();break;case 26:case 27:case 5:et(a);break;case 4:oe();break;case 31:a.memoizedState!==null&&Ln(a);break;case 13:Ln(a);break;case 19:X(zt);break;case 10:Fa(a.type);break;case 22:case 23:Ln(a),Fd(),e!==null&&X(cs);break;case 24:Fa(Vt)}}function Ei(e,a){try{var o=a.updateQueue,l=o!==null?o.lastEffect:null;if(l!==null){var d=l.next;o=d;do{if((o.tag&e)===e){l=void 0;var m=o.create,x=o.inst;l=m(),x.destroy=l}o=o.next}while(o!==d)}}catch(N){gt(a,a.return,N)}}function Er(e,a,o){try{var l=a.updateQueue,d=l!==null?l.lastEffect:null;if(d!==null){var m=d.next;l=m;do{if((l.tag&e)===e){var x=l.inst,N=x.destroy;if(N!==void 0){x.destroy=void 0,d=a;var M=o,q=N;try{q()}catch(re){gt(d,M,re)}}}l=l.next}while(l!==m)}}catch(re){gt(a,a.return,re)}}function Lv(e){var a=e.updateQueue;if(a!==null){var o=e.stateNode;try{Ng(a,o)}catch(l){gt(e,e.return,l)}}}function Uv(e,a,o){o.props=hs(e.type,e.memoizedProps),o.state=e.memoizedState;try{o.componentWillUnmount()}catch(l){gt(e,a,l)}}function _i(e,a){try{var o=e.ref;if(o!==null){switch(e.tag){case 26:case 27:case 5:var l=e.stateNode;break;case 30:l=e.stateNode;break;default:l=e.stateNode}typeof o=="function"?e.refCleanup=o(l):o.current=l}}catch(d){gt(e,a,d)}}function Ea(e,a){var o=e.ref,l=e.refCleanup;if(o!==null)if(typeof l=="function")try{l()}catch(d){gt(e,a,d)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(d){gt(e,a,d)}else o.current=null}function Bv(e){var a=e.type,o=e.memoizedProps,l=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&l.focus();break e;case"img":o.src?l.src=o.src:o.srcSet&&(l.srcset=o.srcSet)}}catch(d){gt(e,e.return,d)}}function Ef(e,a,o){try{var l=e.stateNode;G_(l,e.type,o,a),l[Sn]=a}catch(d){gt(e,e.return,d)}}function Pv(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Or(e.type)||e.tag===4}function _f(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Pv(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.tag===27&&Or(e.type)||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 Cf(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(e,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(e),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=Pa));else if(l!==4&&(l===27&&Or(e.type)&&(o=e.stateNode,a=null),e=e.child,e!==null))for(Cf(e,a,o),e=e.sibling;e!==null;)Cf(e,a,o),e=e.sibling}function rc(e,a,o){var l=e.tag;if(l===5||l===6)e=e.stateNode,a?o.insertBefore(e,a):o.appendChild(e);else if(l!==4&&(l===27&&Or(e.type)&&(o=e.stateNode),e=e.child,e!==null))for(rc(e,a,o),e=e.sibling;e!==null;)rc(e,a,o),e=e.sibling}function Hv(e){var a=e.stateNode,o=e.memoizedProps;try{for(var l=e.type,d=a.attributes;d.length;)a.removeAttributeNode(d[0]);cn(a,l,o),a[rn]=e,a[Sn]=o}catch(m){gt(e,e.return,m)}}var Xa=!1,Ft=!1,Nf=!1,Vv=typeof WeakSet=="function"?WeakSet:Set,nn=null;function C_(e,a){if(e=e.containerInfo,Yf=Cc,e=Jp(e),yd(e)){if("selectionStart"in e)var o={start:e.selectionStart,end:e.selectionEnd};else e:{o=(o=e.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,m=l.focusNode;l=l.focusOffset;try{o.nodeType,m.nodeType}catch{o=null;break e}var x=0,N=-1,M=-1,q=0,re=0,ue=e,Z=null;t:for(;;){for(var ee;ue!==o||d!==0&&ue.nodeType!==3||(N=x+d),ue!==m||l!==0&&ue.nodeType!==3||(M=x+l),ue.nodeType===3&&(x+=ue.nodeValue.length),(ee=ue.firstChild)!==null;)Z=ue,ue=ee;for(;;){if(ue===e)break t;if(Z===o&&++q===d&&(N=x),Z===m&&++re===l&&(M=x),(ee=ue.nextSibling)!==null)break;ue=Z,Z=ue.parentNode}ue=ee}o=N===-1||M===-1?null:{start:N,end:M}}else o=null}o=o||{start:0,end:0}}else o=null;for(Zf={focusedElem:e,selectionRange:o},Cc=!1,nn=a;nn!==null;)if(a=nn,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,nn=e;else for(;nn!==null;){switch(a=nn,m=a.alternate,e=a.flags,a.tag){case 0:if((e&4)!==0&&(e=a.updateQueue,e=e!==null?e.events:null,e!==null))for(o=0;o<e.length;o++)d=e[o],d.ref.impl=d.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&m!==null){e=void 0,o=a,d=m.memoizedProps,m=m.memoizedState,l=o.stateNode;try{var _e=hs(o.type,d);e=l.getSnapshotBeforeUpdate(_e,m),l.__reactInternalSnapshotBeforeUpdate=e}catch(Le){gt(o,o.return,Le)}}break;case 3:if((e&1024)!==0){if(e=a.stateNode.containerInfo,o=e.nodeType,o===9)Qf(e);else if(o===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Qf(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((e&1024)!==0)throw Error(s(163))}if(e=a.sibling,e!==null){e.return=a.return,nn=e;break}nn=a.return}}function Iv(e,a,o){var l=o.flags;switch(o.tag){case 0:case 11:case 15:Qa(e,o),l&4&&Ei(5,o);break;case 1:if(Qa(e,o),l&4)if(e=o.stateNode,a===null)try{e.componentDidMount()}catch(x){gt(o,o.return,x)}else{var d=hs(o.type,a.memoizedProps);a=a.memoizedState;try{e.componentDidUpdate(d,a,e.__reactInternalSnapshotBeforeUpdate)}catch(x){gt(o,o.return,x)}}l&64&&Lv(o),l&512&&_i(o,o.return);break;case 3:if(Qa(e,o),l&64&&(e=o.updateQueue,e!==null)){if(a=null,o.child!==null)switch(o.child.tag){case 27:case 5:a=o.child.stateNode;break;case 1:a=o.child.stateNode}try{Ng(e,a)}catch(x){gt(o,o.return,x)}}break;case 27:a===null&&l&4&&Hv(o);case 26:case 5:Qa(e,o),a===null&&l&4&&Bv(o),l&512&&_i(o,o.return);break;case 12:Qa(e,o);break;case 31:Qa(e,o),l&4&&$v(e,o);break;case 13:Qa(e,o),l&4&&Gv(e,o),l&64&&(e=o.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(o=D_.bind(null,o),eC(e,o))));break;case 22:if(l=o.memoizedState!==null||Xa,!l){a=a!==null&&a.memoizedState!==null||Ft,d=Xa;var m=Ft;Xa=l,(Ft=a)&&!m?Wa(e,o,(o.subtreeFlags&8772)!==0):Qa(e,o),Xa=d,Ft=m}break;case 30:break;default:Qa(e,o)}}function qv(e){var a=e.alternate;a!==null&&(e.alternate=null,qv(a)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(a=e.stateNode,a!==null&&td(a)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Ct=null,_n=!1;function Ka(e,a,o){for(o=o.child;o!==null;)Fv(e,a,o),o=o.sibling}function Fv(e,a,o){if(Dt&&typeof Dt.onCommitFiberUnmount=="function")try{Dt.onCommitFiberUnmount(mt,o)}catch{}switch(o.tag){case 26:Ft||Ea(o,a),Ka(e,a,o),o.memoizedState?o.memoizedState.count--:o.stateNode&&(o=o.stateNode,o.parentNode.removeChild(o));break;case 27:Ft||Ea(o,a);var l=Ct,d=_n;Or(o.type)&&(Ct=o.stateNode,_n=!1),Ka(e,a,o),Mi(o.stateNode),Ct=l,_n=d;break;case 5:Ft||Ea(o,a);case 6:if(l=Ct,d=_n,Ct=null,Ka(e,a,o),Ct=l,_n=d,Ct!==null)if(_n)try{(Ct.nodeType===9?Ct.body:Ct.nodeName==="HTML"?Ct.ownerDocument.body:Ct).removeChild(o.stateNode)}catch(m){gt(o,a,m)}else try{Ct.removeChild(o.stateNode)}catch(m){gt(o,a,m)}break;case 18:Ct!==null&&(_n?(e=Ct,Ly(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,o.stateNode),yo(e)):Ly(Ct,o.stateNode));break;case 4:l=Ct,d=_n,Ct=o.stateNode.containerInfo,_n=!0,Ka(e,a,o),Ct=l,_n=d;break;case 0:case 11:case 14:case 15:Er(2,o,a),Ft||Er(4,o,a),Ka(e,a,o);break;case 1:Ft||(Ea(o,a),l=o.stateNode,typeof l.componentWillUnmount=="function"&&Uv(o,a,l)),Ka(e,a,o);break;case 21:Ka(e,a,o);break;case 22:Ft=(l=Ft)||o.memoizedState!==null,Ka(e,a,o),Ft=l;break;default:Ka(e,a,o)}}function $v(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{yo(e)}catch(o){gt(a,a.return,o)}}}function Gv(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{yo(e)}catch(o){gt(a,a.return,o)}}function N_(e){switch(e.tag){case 31:case 13:case 19:var a=e.stateNode;return a===null&&(a=e.stateNode=new Vv),a;case 22:return e=e.stateNode,a=e._retryCache,a===null&&(a=e._retryCache=new Vv),a;default:throw Error(s(435,e.tag))}}function sc(e,a){var o=N_(e);a.forEach(function(l){if(!o.has(l)){o.add(l);var d=z_.bind(null,e,l);l.then(d,d)}})}function Cn(e,a){var o=a.deletions;if(o!==null)for(var l=0;l<o.length;l++){var d=o[l],m=e,x=a,N=x;e:for(;N!==null;){switch(N.tag){case 27:if(Or(N.type)){Ct=N.stateNode,_n=!1;break e}break;case 5:Ct=N.stateNode,_n=!1;break e;case 3:case 4:Ct=N.stateNode.containerInfo,_n=!0;break e}N=N.return}if(Ct===null)throw Error(s(160));Fv(m,x,d),Ct=null,_n=!1,m=d.alternate,m!==null&&(m.return=null),d.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)Yv(a,e),a=a.sibling}var da=null;function Yv(e,a){var o=e.alternate,l=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Cn(a,e),Nn(e),l&4&&(Er(3,e,e.return),Ei(3,e),Er(5,e,e.return));break;case 1:Cn(a,e),Nn(e),l&512&&(Ft||o===null||Ea(o,o.return)),l&64&&Xa&&(e=e.updateQueue,e!==null&&(l=e.callbacks,l!==null&&(o=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=o===null?l:o.concat(l))));break;case 26:var d=da;if(Cn(a,e),Nn(e),l&512&&(Ft||o===null||Ea(o,o.return)),l&4){var m=o!==null?o.memoizedState:null;if(l=e.memoizedState,o===null)if(l===null)if(e.stateNode===null){e:{l=e.type,o=e.memoizedProps,d=d.ownerDocument||d;t:switch(l){case"title":m=d.getElementsByTagName("title")[0],(!m||m[Qo]||m[rn]||m.namespaceURI==="http://www.w3.org/2000/svg"||m.hasAttribute("itemprop"))&&(m=d.createElement(l),d.head.insertBefore(m,d.querySelector("head > title"))),cn(m,l,o),m[rn]=e,tn(m),l=m;break e;case"link":var x=Yy("link","href",d).get(l+(o.href||""));if(x){for(var N=0;N<x.length;N++)if(m=x[N],m.getAttribute("href")===(o.href==null||o.href===""?null:o.href)&&m.getAttribute("rel")===(o.rel==null?null:o.rel)&&m.getAttribute("title")===(o.title==null?null:o.title)&&m.getAttribute("crossorigin")===(o.crossOrigin==null?null:o.crossOrigin)){x.splice(N,1);break t}}m=d.createElement(l),cn(m,l,o),d.head.appendChild(m);break;case"meta":if(x=Yy("meta","content",d).get(l+(o.content||""))){for(N=0;N<x.length;N++)if(m=x[N],m.getAttribute("content")===(o.content==null?null:""+o.content)&&m.getAttribute("name")===(o.name==null?null:o.name)&&m.getAttribute("property")===(o.property==null?null:o.property)&&m.getAttribute("http-equiv")===(o.httpEquiv==null?null:o.httpEquiv)&&m.getAttribute("charset")===(o.charSet==null?null:o.charSet)){x.splice(N,1);break t}}m=d.createElement(l),cn(m,l,o),d.head.appendChild(m);break;default:throw Error(s(468,l))}m[rn]=e,tn(m),l=m}e.stateNode=l}else Zy(d,e.type,e.stateNode);else e.stateNode=Gy(d,l,e.memoizedProps);else m!==l?(m===null?o.stateNode!==null&&(o=o.stateNode,o.parentNode.removeChild(o)):m.count--,l===null?Zy(d,e.type,e.stateNode):Gy(d,l,e.memoizedProps)):l===null&&e.stateNode!==null&&Ef(e,e.memoizedProps,o.memoizedProps)}break;case 27:Cn(a,e),Nn(e),l&512&&(Ft||o===null||Ea(o,o.return)),o!==null&&l&4&&Ef(e,e.memoizedProps,o.memoizedProps);break;case 5:if(Cn(a,e),Nn(e),l&512&&(Ft||o===null||Ea(o,o.return)),e.flags&32){d=e.stateNode;try{Hs(d,"")}catch(_e){gt(e,e.return,_e)}}l&4&&e.stateNode!=null&&(d=e.memoizedProps,Ef(e,d,o!==null?o.memoizedProps:d)),l&1024&&(Nf=!0);break;case 6:if(Cn(a,e),Nn(e),l&4){if(e.stateNode===null)throw Error(s(162));l=e.memoizedProps,o=e.stateNode;try{o.nodeValue=l}catch(_e){gt(e,e.return,_e)}}break;case 3:if(wc=null,d=da,da=bc(a.containerInfo),Cn(a,e),da=d,Nn(e),l&4&&o!==null&&o.memoizedState.isDehydrated)try{yo(a.containerInfo)}catch(_e){gt(e,e.return,_e)}Nf&&(Nf=!1,Zv(e));break;case 4:l=da,da=bc(e.stateNode.containerInfo),Cn(a,e),Nn(e),da=l;break;case 12:Cn(a,e),Nn(e);break;case 31:Cn(a,e),Nn(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,sc(e,l)));break;case 13:Cn(a,e),Nn(e),e.child.flags&8192&&e.memoizedState!==null!=(o!==null&&o.memoizedState!==null)&&(ic=V()),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,sc(e,l)));break;case 22:d=e.memoizedState!==null;var M=o!==null&&o.memoizedState!==null,q=Xa,re=Ft;if(Xa=q||d,Ft=re||M,Cn(a,e),Ft=re,Xa=q,Nn(e),l&8192)e:for(a=e.stateNode,a._visibility=d?a._visibility&-2:a._visibility|1,d&&(o===null||M||Xa||Ft||ps(e)),o=null,a=e;;){if(a.tag===5||a.tag===26){if(o===null){M=o=a;try{if(m=M.stateNode,d)x=m.style,typeof x.setProperty=="function"?x.setProperty("display","none","important"):x.display="none";else{N=M.stateNode;var ue=M.memoizedProps.style,Z=ue!=null&&ue.hasOwnProperty("display")?ue.display:null;N.style.display=Z==null||typeof Z=="boolean"?"":(""+Z).trim()}}catch(_e){gt(M,M.return,_e)}}}else if(a.tag===6){if(o===null){M=a;try{M.stateNode.nodeValue=d?"":M.memoizedProps}catch(_e){gt(M,M.return,_e)}}}else if(a.tag===18){if(o===null){M=a;try{var ee=M.stateNode;d?Uy(ee,!0):Uy(M.stateNode,!1)}catch(_e){gt(M,M.return,_e)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===e)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break e;for(;a.sibling===null;){if(a.return===null||a.return===e)break e;o===a&&(o=null),a=a.return}o===a&&(o=null),a.sibling.return=a.return,a=a.sibling}l&4&&(l=e.updateQueue,l!==null&&(o=l.retryQueue,o!==null&&(l.retryQueue=null,sc(e,o))));break;case 19:Cn(a,e),Nn(e),l&4&&(l=e.updateQueue,l!==null&&(e.updateQueue=null,sc(e,l)));break;case 30:break;case 21:break;default:Cn(a,e),Nn(e)}}function Nn(e){var a=e.flags;if(a&2){try{for(var o,l=e.return;l!==null;){if(Pv(l)){o=l;break}l=l.return}if(o==null)throw Error(s(160));switch(o.tag){case 27:var d=o.stateNode,m=_f(e);rc(e,m,d);break;case 5:var x=o.stateNode;o.flags&32&&(Hs(x,""),o.flags&=-33);var N=_f(e);rc(e,N,x);break;case 3:case 4:var M=o.stateNode.containerInfo,q=_f(e);Cf(e,q,M);break;default:throw Error(s(161))}}catch(re){gt(e,e.return,re)}e.flags&=-3}a&4096&&(e.flags&=-4097)}function Zv(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var a=e;Zv(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),e=e.sibling}}function Qa(e,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)Iv(e,a.alternate,a),a=a.sibling}function ps(e){for(e=e.child;e!==null;){var a=e;switch(a.tag){case 0:case 11:case 14:case 15:Er(4,a,a.return),ps(a);break;case 1:Ea(a,a.return);var o=a.stateNode;typeof o.componentWillUnmount=="function"&&Uv(a,a.return,o),ps(a);break;case 27:Mi(a.stateNode);case 26:case 5:Ea(a,a.return),ps(a);break;case 22:a.memoizedState===null&&ps(a);break;case 30:ps(a);break;default:ps(a)}e=e.sibling}}function Wa(e,a,o){for(o=o&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var l=a.alternate,d=e,m=a,x=m.flags;switch(m.tag){case 0:case 11:case 15:Wa(d,m,o),Ei(4,m);break;case 1:if(Wa(d,m,o),l=m,d=l.stateNode,typeof d.componentDidMount=="function")try{d.componentDidMount()}catch(q){gt(l,l.return,q)}if(l=m,d=l.updateQueue,d!==null){var N=l.stateNode;try{var M=d.shared.hiddenCallbacks;if(M!==null)for(d.shared.hiddenCallbacks=null,d=0;d<M.length;d++)Cg(M[d],N)}catch(q){gt(l,l.return,q)}}o&&x&64&&Lv(m),_i(m,m.return);break;case 27:Hv(m);case 26:case 5:Wa(d,m,o),o&&l===null&&x&4&&Bv(m),_i(m,m.return);break;case 12:Wa(d,m,o);break;case 31:Wa(d,m,o),o&&x&4&&$v(d,m);break;case 13:Wa(d,m,o),o&&x&4&&Gv(d,m);break;case 22:m.memoizedState===null&&Wa(d,m,o),_i(m,m.return);break;case 30:break;default:Wa(d,m,o)}a=a.sibling}}function Rf(e,a){var o=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(o=e.memoizedState.cachePool.pool),e=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(e=a.memoizedState.cachePool.pool),e!==o&&(e!=null&&e.refCount++,o!=null&&ui(o))}function Af(e,a){e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ui(e))}function fa(e,a,o,l){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)Xv(e,a,o,l),a=a.sibling}function Xv(e,a,o,l){var d=a.flags;switch(a.tag){case 0:case 11:case 15:fa(e,a,o,l),d&2048&&Ei(9,a);break;case 1:fa(e,a,o,l);break;case 3:fa(e,a,o,l),d&2048&&(e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&ui(e)));break;case 12:if(d&2048){fa(e,a,o,l),e=a.stateNode;try{var m=a.memoizedProps,x=m.id,N=m.onPostCommit;typeof N=="function"&&N(x,a.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(M){gt(a,a.return,M)}}else fa(e,a,o,l);break;case 31:fa(e,a,o,l);break;case 13:fa(e,a,o,l);break;case 23:break;case 22:m=a.stateNode,x=a.alternate,a.memoizedState!==null?m._visibility&2?fa(e,a,o,l):Ci(e,a):m._visibility&2?fa(e,a,o,l):(m._visibility|=2,oo(e,a,o,l,(a.subtreeFlags&10256)!==0||!1)),d&2048&&Rf(x,a);break;case 24:fa(e,a,o,l),d&2048&&Af(a.alternate,a);break;default:fa(e,a,o,l)}}function oo(e,a,o,l,d){for(d=d&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var m=e,x=a,N=o,M=l,q=x.flags;switch(x.tag){case 0:case 11:case 15:oo(m,x,N,M,d),Ei(8,x);break;case 23:break;case 22:var re=x.stateNode;x.memoizedState!==null?re._visibility&2?oo(m,x,N,M,d):Ci(m,x):(re._visibility|=2,oo(m,x,N,M,d)),d&&q&2048&&Rf(x.alternate,x);break;case 24:oo(m,x,N,M,d),d&&q&2048&&Af(x.alternate,x);break;default:oo(m,x,N,M,d)}a=a.sibling}}function Ci(e,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var o=e,l=a,d=l.flags;switch(l.tag){case 22:Ci(o,l),d&2048&&Rf(l.alternate,l);break;case 24:Ci(o,l),d&2048&&Af(l.alternate,l);break;default:Ci(o,l)}a=a.sibling}}var Ni=8192;function io(e,a,o){if(e.subtreeFlags&Ni)for(e=e.child;e!==null;)Kv(e,a,o),e=e.sibling}function Kv(e,a,o){switch(e.tag){case 26:io(e,a,o),e.flags&Ni&&e.memoizedState!==null&&fC(o,da,e.memoizedState,e.memoizedProps);break;case 5:io(e,a,o);break;case 3:case 4:var l=da;da=bc(e.stateNode.containerInfo),io(e,a,o),da=l;break;case 22:e.memoizedState===null&&(l=e.alternate,l!==null&&l.memoizedState!==null?(l=Ni,Ni=16777216,io(e,a,o),Ni=l):io(e,a,o));break;default:io(e,a,o)}}function Qv(e){var a=e.alternate;if(a!==null&&(e=a.child,e!==null)){a.child=null;do a=e.sibling,e.sibling=null,e=a;while(e!==null)}}function Ri(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var o=0;o<a.length;o++){var l=a[o];nn=l,Jv(l,e)}Qv(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Wv(e),e=e.sibling}function Wv(e){switch(e.tag){case 0:case 11:case 15:Ri(e),e.flags&2048&&Er(9,e,e.return);break;case 3:Ri(e);break;case 12:Ri(e);break;case 22:var a=e.stateNode;e.memoizedState!==null&&a._visibility&2&&(e.return===null||e.return.tag!==13)?(a._visibility&=-3,oc(e)):Ri(e);break;default:Ri(e)}}function oc(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var o=0;o<a.length;o++){var l=a[o];nn=l,Jv(l,e)}Qv(e)}for(e=e.child;e!==null;){switch(a=e,a.tag){case 0:case 11:case 15:Er(8,a,a.return),oc(a);break;case 22:o=a.stateNode,o._visibility&2&&(o._visibility&=-3,oc(a));break;default:oc(a)}e=e.sibling}}function Jv(e,a){for(;nn!==null;){var o=nn;switch(o.tag){case 0:case 11:case 15:Er(8,o,a);break;case 23:case 22:if(o.memoizedState!==null&&o.memoizedState.cachePool!==null){var l=o.memoizedState.cachePool.pool;l!=null&&l.refCount++}break;case 24:ui(o.memoizedState.cache)}if(l=o.child,l!==null)l.return=o,nn=l;else e:for(o=e;nn!==null;){l=nn;var d=l.sibling,m=l.return;if(qv(l),l===o){nn=null;break e}if(d!==null){d.return=m,nn=d;break e}nn=m}}}var R_={getCacheForType:function(e){var a=on(Vt),o=a.data.get(e);return o===void 0&&(o=e(),a.data.set(e,o)),o},cacheSignal:function(){return on(Vt).controller.signal}},A_=typeof WeakMap=="function"?WeakMap:Map,ft=0,wt=null,We=null,tt=0,pt=0,Un=null,_r=!1,lo=!1,Tf=!1,Ja=0,jt=0,Cr=0,gs=0,Of=0,Bn=0,co=0,Ai=null,Rn=null,jf=!1,ic=0,ey=0,lc=1/0,cc=null,Nr=null,Xt=0,Rr=null,uo=null,er=0,kf=0,Mf=null,ty=null,Ti=0,Df=null;function Pn(){return(ft&2)!==0&&tt!==0?tt&-tt:T.T!==null?Hf():Ju()}function ny(){if(Bn===0)if((tt&536870912)===0||rt){var e=ks;ks<<=1,(ks&3932160)===0&&(ks=262144),Bn=e}else Bn=536870912;return e=zn.current,e!==null&&(e.flags|=32),Bn}function An(e,a,o){(e===wt&&(pt===2||pt===9)||e.cancelPendingCommit!==null)&&(fo(e,0),Ar(e,tt,Bn,!1)),Rt(e,o),((ft&2)===0||e!==wt)&&(e===wt&&((ft&2)===0&&(gs|=o),jt===4&&Ar(e,tt,Bn,!1)),_a(e))}function ay(e,a,o){if((ft&6)!==0)throw Error(s(327));var l=!o&&(a&127)===0&&(a&e.expiredLanes)===0||_t(e,a),d=l?j_(e,a):Lf(e,a,!0),m=l;do{if(d===0){lo&&!l&&Ar(e,a,0,!1);break}else{if(o=e.current.alternate,m&&!T_(o)){d=Lf(e,a,!1),m=!1;continue}if(d===2){if(m=a,e.errorRecoveryDisabledLanes&m)var x=0;else x=e.pendingLanes&-536870913,x=x!==0?x:x&536870912?536870912:0;if(x!==0){a=x;e:{var N=e;d=Ai;var M=N.current.memoizedState.isDehydrated;if(M&&(fo(N,x).flags|=256),x=Lf(N,x,!1),x!==2){if(Tf&&!M){N.errorRecoveryDisabledLanes|=m,gs|=m,d=4;break e}m=Rn,Rn=d,m!==null&&(Rn===null?Rn=m:Rn.push.apply(Rn,m))}d=x}if(m=!1,d!==2)continue}}if(d===1){fo(e,0),Ar(e,a,0,!0);break}e:{switch(l=e,m=d,m){case 0:case 1:throw Error(s(345));case 4:if((a&4194048)!==a)break;case 6:Ar(l,a,Bn,!_r);break e;case 2:Rn=null;break;case 3:case 5:break;default:throw Error(s(329))}if((a&62914560)===a&&(d=ic+300-V(),10<d)){if(Ar(l,a,Bn,!_r),He(l,0,!0)!==0)break e;er=a,l.timeoutHandle=Dy(ry.bind(null,l,o,Rn,cc,jf,a,Bn,gs,co,_r,m,"Throttled",-0,0),d);break e}ry(l,o,Rn,cc,jf,a,Bn,gs,co,_r,m,null,-0,0)}}break}while(!0);_a(e)}function ry(e,a,o,l,d,m,x,N,M,q,re,ue,Z,ee){if(e.timeoutHandle=-1,ue=a.subtreeFlags,ue&8192||(ue&16785408)===16785408){ue={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Pa},Kv(a,m,ue);var _e=(m&62914560)===m?ic-V():(m&4194048)===m?ey-V():0;if(_e=mC(ue,_e),_e!==null){er=m,e.cancelPendingCommit=_e(fy.bind(null,e,a,m,o,l,d,x,N,M,re,ue,null,Z,ee)),Ar(e,m,x,!q);return}}fy(e,a,m,o,l,d,x,N,M)}function T_(e){for(var a=e;;){var o=a.tag;if((o===0||o===11||o===15)&&a.flags&16384&&(o=a.updateQueue,o!==null&&(o=o.stores,o!==null)))for(var l=0;l<o.length;l++){var d=o[l],m=d.getSnapshot;d=d.value;try{if(!Mn(m(),d))return!1}catch{return!1}}if(o=a.child,a.subtreeFlags&16384&&o!==null)o.return=a,a=o;else{if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Ar(e,a,o,l){a&=~Of,a&=~gs,e.suspendedLanes|=a,e.pingedLanes&=~a,l&&(e.warmLanes|=a),l=e.expirationTimes;for(var d=a;0<d;){var m=31-Ht(d),x=1<<m;l[m]=-1,d&=~x}o!==0&&Jr(e,o,a)}function uc(){return(ft&6)===0?(Oi(0),!1):!0}function zf(){if(We!==null){if(pt===0)var e=We.return;else e=We,qa=is=null,Kd(e),to=null,fi=0,e=We;for(;e!==null;)zv(e.alternate,e),e=e.return;We=null}}function fo(e,a){var o=e.timeoutHandle;o!==-1&&(e.timeoutHandle=-1,X_(o)),o=e.cancelPendingCommit,o!==null&&(e.cancelPendingCommit=null,o()),er=0,zf(),wt=e,We=o=Va(e.current,null),tt=a,pt=0,Un=null,_r=!1,lo=_t(e,a),Tf=!1,co=Bn=Of=gs=Cr=jt=0,Rn=Ai=null,jf=!1,(a&8)!==0&&(a|=a&32);var l=e.entangledLanes;if(l!==0)for(e=e.entanglements,l&=a;0<l;){var d=31-Ht(l),m=1<<d;a|=e[d],l&=~m}return Ja=a,jl(),o}function sy(e,a){$e=null,T.H=xi,a===eo||a===Pl?(a=wg(),pt=3):a===Bd?(a=wg(),pt=4):pt=a===mf?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,Un=a,We===null&&(jt=1,Jl(e,Qn(a,e.current)))}function oy(){var e=zn.current;return e===null?!0:(tt&4194048)===tt?ta===null:(tt&62914560)===tt||(tt&536870912)!==0?e===ta:!1}function iy(){var e=T.H;return T.H=xi,e===null?xi:e}function ly(){var e=T.A;return T.A=R_,e}function dc(){jt=4,_r||(tt&4194048)!==tt&&zn.current!==null||(lo=!0),(Cr&134217727)===0&&(gs&134217727)===0||wt===null||Ar(wt,tt,Bn,!1)}function Lf(e,a,o){var l=ft;ft|=2;var d=iy(),m=ly();(wt!==e||tt!==a)&&(cc=null,fo(e,a)),a=!1;var x=jt;e:do try{if(pt!==0&&We!==null){var N=We,M=Un;switch(pt){case 8:zf(),x=6;break e;case 3:case 2:case 9:case 6:zn.current===null&&(a=!0);var q=pt;if(pt=0,Un=null,mo(e,N,M,q),o&&lo){x=0;break e}break;default:q=pt,pt=0,Un=null,mo(e,N,M,q)}}O_(),x=jt;break}catch(re){sy(e,re)}while(!0);return a&&e.shellSuspendCounter++,qa=is=null,ft=l,T.H=d,T.A=m,We===null&&(wt=null,tt=0,jl()),x}function O_(){for(;We!==null;)cy(We)}function j_(e,a){var o=ft;ft|=2;var l=iy(),d=ly();wt!==e||tt!==a?(cc=null,lc=V()+500,fo(e,a)):lo=_t(e,a);e:do try{if(pt!==0&&We!==null){a=We;var m=Un;t:switch(pt){case 1:pt=0,Un=null,mo(e,a,m,1);break;case 2:case 9:if(bg(m)){pt=0,Un=null,uy(a);break}a=function(){pt!==2&&pt!==9||wt!==e||(pt=7),_a(e)},m.then(a,a);break e;case 3:pt=7;break e;case 4:pt=5;break e;case 7:bg(m)?(pt=0,Un=null,uy(a)):(pt=0,Un=null,mo(e,a,m,7));break;case 5:var x=null;switch(We.tag){case 26:x=We.memoizedState;case 5:case 27:var N=We;if(x?Xy(x):N.stateNode.complete){pt=0,Un=null;var M=N.sibling;if(M!==null)We=M;else{var q=N.return;q!==null?(We=q,fc(q)):We=null}break t}}pt=0,Un=null,mo(e,a,m,5);break;case 6:pt=0,Un=null,mo(e,a,m,6);break;case 8:zf(),jt=6;break e;default:throw Error(s(462))}}k_();break}catch(re){sy(e,re)}while(!0);return qa=is=null,T.H=l,T.A=d,ft=o,We!==null?0:(wt=null,tt=0,jl(),jt)}function k_(){for(;We!==null&&!O();)cy(We)}function cy(e){var a=Mv(e.alternate,e,Ja);e.memoizedProps=e.pendingProps,a===null?fc(e):We=a}function uy(e){var a=e,o=a.alternate;switch(a.tag){case 15:case 0:a=Rv(o,a,a.pendingProps,a.type,void 0,tt);break;case 11:a=Rv(o,a,a.pendingProps,a.type.render,a.ref,tt);break;case 5:Kd(a);default:zv(o,a),a=We=lg(a,Ja),a=Mv(o,a,Ja)}e.memoizedProps=e.pendingProps,a===null?fc(e):We=a}function mo(e,a,o,l){qa=is=null,Kd(a),to=null,fi=0;var d=a.return;try{if(x_(e,d,a,o,tt)){jt=1,Jl(e,Qn(o,e.current)),We=null;return}}catch(m){if(d!==null)throw We=d,m;jt=1,Jl(e,Qn(o,e.current)),We=null;return}a.flags&32768?(rt||l===1?e=!0:lo||(tt&536870912)!==0?e=!1:(_r=e=!0,(l===2||l===9||l===3||l===6)&&(l=zn.current,l!==null&&l.tag===13&&(l.flags|=16384))),dy(a,e)):fc(a)}function fc(e){var a=e;do{if((a.flags&32768)!==0){dy(a,_r);return}e=a.return;var o=E_(a.alternate,a,Ja);if(o!==null){We=o;return}if(a=a.sibling,a!==null){We=a;return}We=a=e}while(a!==null);jt===0&&(jt=5)}function dy(e,a){do{var o=__(e.alternate,e);if(o!==null){o.flags&=32767,We=o;return}if(o=e.return,o!==null&&(o.flags|=32768,o.subtreeFlags=0,o.deletions=null),!a&&(e=e.sibling,e!==null)){We=e;return}We=e=o}while(e!==null);jt=6,We=null}function fy(e,a,o,l,d,m,x,N,M){e.cancelPendingCommit=null;do mc();while(Xt!==0);if((ft&6)!==0)throw Error(s(327));if(a!==null){if(a===e.current)throw Error(s(177));if(m=a.lanes|a.childLanes,m|=Ed,bn(e,o,m,x,N,M),e===wt&&(We=wt=null,tt=0),uo=a,Rr=e,er=o,kf=m,Mf=d,ty=l,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,L_(Se,function(){return vy(),null})):(e.callbackNode=null,e.callbackPriority=0),l=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||l){l=T.T,T.T=null,d=K.p,K.p=2,x=ft,ft|=4;try{C_(e,a,o)}finally{ft=x,K.p=d,T.T=l}}Xt=1,my(),hy(),py()}}function my(){if(Xt===1){Xt=0;var e=Rr,a=uo,o=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||o){o=T.T,T.T=null;var l=K.p;K.p=2;var d=ft;ft|=4;try{Yv(a,e);var m=Zf,x=Jp(e.containerInfo),N=m.focusedElem,M=m.selectionRange;if(x!==N&&N&&N.ownerDocument&&Wp(N.ownerDocument.documentElement,N)){if(M!==null&&yd(N)){var q=M.start,re=M.end;if(re===void 0&&(re=q),"selectionStart"in N)N.selectionStart=q,N.selectionEnd=Math.min(re,N.value.length);else{var ue=N.ownerDocument||document,Z=ue&&ue.defaultView||window;if(Z.getSelection){var ee=Z.getSelection(),_e=N.textContent.length,Le=Math.min(M.start,_e),bt=M.end===void 0?Le:Math.min(M.end,_e);!ee.extend&&Le>bt&&(x=bt,bt=Le,Le=x);var P=Qp(N,Le),z=Qp(N,bt);if(P&&z&&(ee.rangeCount!==1||ee.anchorNode!==P.node||ee.anchorOffset!==P.offset||ee.focusNode!==z.node||ee.focusOffset!==z.offset)){var I=ue.createRange();I.setStart(P.node,P.offset),ee.removeAllRanges(),Le>bt?(ee.addRange(I),ee.extend(z.node,z.offset)):(I.setEnd(z.node,z.offset),ee.addRange(I))}}}}for(ue=[],ee=N;ee=ee.parentNode;)ee.nodeType===1&&ue.push({element:ee,left:ee.scrollLeft,top:ee.scrollTop});for(typeof N.focus=="function"&&N.focus(),N=0;N<ue.length;N++){var ce=ue[N];ce.element.scrollLeft=ce.left,ce.element.scrollTop=ce.top}}Cc=!!Yf,Zf=Yf=null}finally{ft=d,K.p=l,T.T=o}}e.current=a,Xt=2}}function hy(){if(Xt===2){Xt=0;var e=Rr,a=uo,o=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||o){o=T.T,T.T=null;var l=K.p;K.p=2;var d=ft;ft|=4;try{Iv(e,a.alternate,a)}finally{ft=d,K.p=l,T.T=o}}Xt=3}}function py(){if(Xt===4||Xt===3){Xt=0,B();var e=Rr,a=uo,o=er,l=ty;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Xt=5:(Xt=0,uo=Rr=null,gy(e,e.pendingLanes));var d=e.pendingLanes;if(d===0&&(Nr=null),ca(o),a=a.stateNode,Dt&&typeof Dt.onCommitFiberRoot=="function")try{Dt.onCommitFiberRoot(mt,a,void 0,(a.current.flags&128)===128)}catch{}if(l!==null){a=T.T,d=K.p,K.p=2,T.T=null;try{for(var m=e.onRecoverableError,x=0;x<l.length;x++){var N=l[x];m(N.value,{componentStack:N.stack})}}finally{T.T=a,K.p=d}}(er&3)!==0&&mc(),_a(e),d=e.pendingLanes,(o&261930)!==0&&(d&42)!==0?e===Df?Ti++:(Ti=0,Df=e):Ti=0,Oi(0)}}function gy(e,a){(e.pooledCacheLanes&=a)===0&&(a=e.pooledCache,a!=null&&(e.pooledCache=null,ui(a)))}function mc(){return my(),hy(),py(),vy()}function vy(){if(Xt!==5)return!1;var e=Rr,a=kf;kf=0;var o=ca(er),l=T.T,d=K.p;try{K.p=32>o?32:o,T.T=null,o=Mf,Mf=null;var m=Rr,x=er;if(Xt=0,uo=Rr=null,er=0,(ft&6)!==0)throw Error(s(331));var N=ft;if(ft|=4,Wv(m.current),Xv(m,m.current,x,o),ft=N,Oi(0,!1),Dt&&typeof Dt.onPostCommitFiberRoot=="function")try{Dt.onPostCommitFiberRoot(mt,m)}catch{}return!0}finally{K.p=d,T.T=l,gy(e,a)}}function yy(e,a,o){a=Qn(o,a),a=ff(e.stateNode,a,2),e=xr(e,a,2),e!==null&&(Rt(e,2),_a(e))}function gt(e,a,o){if(e.tag===3)yy(e,e,o);else for(;a!==null;){if(a.tag===3){yy(a,e,o);break}else if(a.tag===1){var l=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(Nr===null||!Nr.has(l))){e=Qn(o,e),o=bv(2),l=xr(a,o,2),l!==null&&(xv(o,l,a,e),Rt(l,2),_a(l));break}}a=a.return}}function Uf(e,a,o){var l=e.pingCache;if(l===null){l=e.pingCache=new A_;var d=new Set;l.set(a,d)}else d=l.get(a),d===void 0&&(d=new Set,l.set(a,d));d.has(o)||(Tf=!0,d.add(o),e=M_.bind(null,e,a,o),a.then(e,e))}function M_(e,a,o){var l=e.pingCache;l!==null&&l.delete(a),e.pingedLanes|=e.suspendedLanes&o,e.warmLanes&=~o,wt===e&&(tt&o)===o&&(jt===4||jt===3&&(tt&62914560)===tt&&300>V()-ic?(ft&2)===0&&fo(e,0):Of|=o,co===tt&&(co=0)),_a(e)}function by(e,a){a===0&&(a=dn()),e=rs(e,a),e!==null&&(Rt(e,a),_a(e))}function D_(e){var a=e.memoizedState,o=0;a!==null&&(o=a.retryLane),by(e,o)}function z_(e,a){var o=0;switch(e.tag){case 31:case 13:var l=e.stateNode,d=e.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=e.stateNode;break;case 22:l=e.stateNode._retryCache;break;default:throw Error(s(314))}l!==null&&l.delete(a),by(e,o)}function L_(e,a){return Tt(e,a)}var hc=null,ho=null,Bf=!1,pc=!1,Pf=!1,Tr=0;function _a(e){e!==ho&&e.next===null&&(ho===null?hc=ho=e:ho=ho.next=e),pc=!0,Bf||(Bf=!0,B_())}function Oi(e,a){if(!Pf&&pc){Pf=!0;do for(var o=!1,l=hc;l!==null;){if(e!==0){var d=l.pendingLanes;if(d===0)var m=0;else{var x=l.suspendedLanes,N=l.pingedLanes;m=(1<<31-Ht(42|e)+1)-1,m&=d&~(x&~N),m=m&201326741?m&201326741|1:m?m|2:0}m!==0&&(o=!0,Ey(l,m))}else m=tt,m=He(l,l===wt?m:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(m&3)===0||_t(l,m)||(o=!0,Ey(l,m));l=l.next}while(o);Pf=!1}}function U_(){xy()}function xy(){pc=Bf=!1;var e=0;Tr!==0&&Z_()&&(e=Tr);for(var a=V(),o=null,l=hc;l!==null;){var d=l.next,m=wy(l,a);m===0?(l.next=null,o===null?hc=d:o.next=d,d===null&&(ho=o)):(o=l,(e!==0||(m&3)!==0)&&(pc=!0)),l=d}Xt!==0&&Xt!==5||Oi(e),Tr!==0&&(Tr=0)}function wy(e,a){for(var o=e.suspendedLanes,l=e.pingedLanes,d=e.expirationTimes,m=e.pendingLanes&-62914561;0<m;){var x=31-Ht(m),N=1<<x,M=d[x];M===-1?((N&o)===0||(N&l)!==0)&&(d[x]=en(N,a)):M<=a&&(e.expiredLanes|=N),m&=~N}if(a=wt,o=tt,o=He(e,e===a?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l=e.callbackNode,o===0||e===a&&(pt===2||pt===9)||e.cancelPendingCommit!==null)return l!==null&&l!==null&&Zt(l),e.callbackNode=null,e.callbackPriority=0;if((o&3)===0||_t(e,o)){if(a=o&-o,a===e.callbackPriority)return a;switch(l!==null&&Zt(l),ca(o)){case 2:case 8:o=ye;break;case 32:o=Se;break;case 268435456:o=Ge;break;default:o=Se}return l=Sy.bind(null,e),o=Tt(o,l),e.callbackPriority=a,e.callbackNode=o,a}return l!==null&&l!==null&&Zt(l),e.callbackPriority=2,e.callbackNode=null,2}function Sy(e,a){if(Xt!==0&&Xt!==5)return e.callbackNode=null,e.callbackPriority=0,null;var o=e.callbackNode;if(mc()&&e.callbackNode!==o)return null;var l=tt;return l=He(e,e===wt?l:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),l===0?null:(ay(e,l,a),wy(e,V()),e.callbackNode!=null&&e.callbackNode===o?Sy.bind(null,e):null)}function Ey(e,a){if(mc())return null;ay(e,a,!0)}function B_(){K_(function(){(ft&6)!==0?Tt(ge,U_):xy()})}function Hf(){if(Tr===0){var e=Ws;e===0&&(e=Ua,Ua<<=1,(Ua&261888)===0&&(Ua=256)),Tr=e}return Tr}function _y(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:El(""+e)}function Cy(e,a){var o=a.ownerDocument.createElement("input");return o.name=a.name,o.value=a.value,e.id&&o.setAttribute("form",e.id),a.parentNode.insertBefore(o,a),e=new FormData(e),o.parentNode.removeChild(o),e}function P_(e,a,o,l,d){if(a==="submit"&&o&&o.stateNode===d){var m=_y((d[Sn]||null).action),x=l.submitter;x&&(a=(a=x[Sn]||null)?_y(a.formAction):x.getAttribute("formAction"),a!==null&&(m=a,x=null));var N=new Rl("action","action",null,l,d);e.push({event:N,listeners:[{instance:null,listener:function(){if(l.defaultPrevented){if(Tr!==0){var M=x?Cy(d,x):new FormData(d);sf(o,{pending:!0,data:M,method:d.method,action:m},null,M)}}else typeof m=="function"&&(N.preventDefault(),M=x?Cy(d,x):new FormData(d),sf(o,{pending:!0,data:M,method:d.method,action:m},m,M))},currentTarget:d}]})}}for(var Vf=0;Vf<Sd.length;Vf++){var If=Sd[Vf],H_=If.toLowerCase(),V_=If[0].toUpperCase()+If.slice(1);ua(H_,"on"+V_)}ua(ng,"onAnimationEnd"),ua(ag,"onAnimationIteration"),ua(rg,"onAnimationStart"),ua("dblclick","onDoubleClick"),ua("focusin","onFocus"),ua("focusout","onBlur"),ua(a_,"onTransitionRun"),ua(r_,"onTransitionStart"),ua(s_,"onTransitionCancel"),ua(sg,"onTransitionEnd"),Bs("onMouseEnter",["mouseout","mouseover"]),Bs("onMouseLeave",["mouseout","mouseover"]),Bs("onPointerEnter",["pointerout","pointerover"]),Bs("onPointerLeave",["pointerout","pointerover"]),es("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),es("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),es("onBeforeInput",["compositionend","keypress","textInput","paste"]),es("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),es("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),es("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var ji="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),I_=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(ji));function Ny(e,a){a=(a&4)!==0;for(var o=0;o<e.length;o++){var l=e[o],d=l.event;l=l.listeners;e:{var m=void 0;if(a)for(var x=l.length-1;0<=x;x--){var N=l[x],M=N.instance,q=N.currentTarget;if(N=N.listener,M!==m&&d.isPropagationStopped())break e;m=N,d.currentTarget=q;try{m(d)}catch(re){Ol(re)}d.currentTarget=null,m=M}else for(x=0;x<l.length;x++){if(N=l[x],M=N.instance,q=N.currentTarget,N=N.listener,M!==m&&d.isPropagationStopped())break e;m=N,d.currentTarget=q;try{m(d)}catch(re){Ol(re)}d.currentTarget=null,m=M}}}}function Je(e,a){var o=a[ed];o===void 0&&(o=a[ed]=new Set);var l=e+"__bubble";o.has(l)||(Ry(a,e,2,!1),o.add(l))}function qf(e,a,o){var l=0;a&&(l|=4),Ry(o,e,l,a)}var gc="_reactListening"+Math.random().toString(36).slice(2);function Ff(e){if(!e[gc]){e[gc]=!0,xp.forEach(function(o){o!=="selectionchange"&&(I_.has(o)||qf(o,!1,e),qf(o,!0,e))});var a=e.nodeType===9?e:e.ownerDocument;a===null||a[gc]||(a[gc]=!0,qf("selectionchange",!1,a))}}function Ry(e,a,o,l){switch(nb(a)){case 2:var d=gC;break;case 8:d=vC;break;default:d=sm}o=d.bind(null,a,o,e),d=void 0,!cd||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(d=!0),l?d!==void 0?e.addEventListener(a,o,{capture:!0,passive:d}):e.addEventListener(a,o,!0):d!==void 0?e.addEventListener(a,o,{passive:d}):e.addEventListener(a,o,!1)}function $f(e,a,o,l,d){var m=l;if((a&1)===0&&(a&2)===0&&l!==null)e:for(;;){if(l===null)return;var x=l.tag;if(x===3||x===4){var N=l.stateNode.containerInfo;if(N===d)break;if(x===4)for(x=l.return;x!==null;){var M=x.tag;if((M===3||M===4)&&x.stateNode.containerInfo===d)return;x=x.return}for(;N!==null;){if(x=zs(N),x===null)return;if(M=x.tag,M===5||M===6||M===26||M===27){l=m=x;continue e}N=N.parentNode}}l=l.return}kp(function(){var q=m,re=id(o),ue=[];e:{var Z=og.get(e);if(Z!==void 0){var ee=Rl,_e=e;switch(e){case"keypress":if(Cl(o)===0)break e;case"keydown":case"keyup":ee=zE;break;case"focusin":_e="focus",ee=md;break;case"focusout":_e="blur",ee=md;break;case"beforeblur":case"afterblur":ee=md;break;case"click":if(o.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ee=zp;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ee=EE;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ee=BE;break;case ng:case ag:case rg:ee=NE;break;case sg:ee=HE;break;case"scroll":case"scrollend":ee=wE;break;case"wheel":ee=IE;break;case"copy":case"cut":case"paste":ee=AE;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ee=Up;break;case"toggle":case"beforetoggle":ee=FE}var Le=(a&4)!==0,bt=!Le&&(e==="scroll"||e==="scrollend"),P=Le?Z!==null?Z+"Capture":null:Z;Le=[];for(var z=q,I;z!==null;){var ce=z;if(I=ce.stateNode,ce=ce.tag,ce!==5&&ce!==26&&ce!==27||I===null||P===null||(ce=Jo(z,P),ce!=null&&Le.push(ki(z,ce,I))),bt)break;z=z.return}0<Le.length&&(Z=new ee(Z,_e,null,o,re),ue.push({event:Z,listeners:Le}))}}if((a&7)===0){e:{if(Z=e==="mouseover"||e==="pointerover",ee=e==="mouseout"||e==="pointerout",Z&&o!==od&&(_e=o.relatedTarget||o.fromElement)&&(zs(_e)||_e[Ds]))break e;if((ee||Z)&&(Z=re.window===re?re:(Z=re.ownerDocument)?Z.defaultView||Z.parentWindow:window,ee?(_e=o.relatedTarget||o.toElement,ee=q,_e=_e?zs(_e):null,_e!==null&&(bt=c(_e),Le=_e.tag,_e!==bt||Le!==5&&Le!==27&&Le!==6)&&(_e=null)):(ee=null,_e=q),ee!==_e)){if(Le=zp,ce="onMouseLeave",P="onMouseEnter",z="mouse",(e==="pointerout"||e==="pointerover")&&(Le=Up,ce="onPointerLeave",P="onPointerEnter",z="pointer"),bt=ee==null?Z:Wo(ee),I=_e==null?Z:Wo(_e),Z=new Le(ce,z+"leave",ee,o,re),Z.target=bt,Z.relatedTarget=I,ce=null,zs(re)===q&&(Le=new Le(P,z+"enter",_e,o,re),Le.target=I,Le.relatedTarget=bt,ce=Le),bt=ce,ee&&_e)t:{for(Le=q_,P=ee,z=_e,I=0,ce=P;ce;ce=Le(ce))I++;ce=0;for(var De=z;De;De=Le(De))ce++;for(;0<I-ce;)P=Le(P),I--;for(;0<ce-I;)z=Le(z),ce--;for(;I--;){if(P===z||z!==null&&P===z.alternate){Le=P;break t}P=Le(P),z=Le(z)}Le=null}else Le=null;ee!==null&&Ay(ue,Z,ee,Le,!1),_e!==null&&bt!==null&&Ay(ue,bt,_e,Le,!0)}}e:{if(Z=q?Wo(q):window,ee=Z.nodeName&&Z.nodeName.toLowerCase(),ee==="select"||ee==="input"&&Z.type==="file")var lt=$p;else if(qp(Z))if(Gp)lt=e_;else{lt=WE;var Oe=QE}else ee=Z.nodeName,!ee||ee.toLowerCase()!=="input"||Z.type!=="checkbox"&&Z.type!=="radio"?q&&sd(q.elementType)&&(lt=$p):lt=JE;if(lt&&(lt=lt(e,q))){Fp(ue,lt,o,re);break e}Oe&&Oe(e,Z,q),e==="focusout"&&q&&Z.type==="number"&&q.memoizedProps.value!=null&&rd(Z,"number",Z.value)}switch(Oe=q?Wo(q):window,e){case"focusin":(qp(Oe)||Oe.contentEditable==="true")&&(Fs=Oe,bd=q,ii=null);break;case"focusout":ii=bd=Fs=null;break;case"mousedown":xd=!0;break;case"contextmenu":case"mouseup":case"dragend":xd=!1,eg(ue,o,re);break;case"selectionchange":if(n_)break;case"keydown":case"keyup":eg(ue,o,re)}var Ye;if(pd)e:{switch(e){case"compositionstart":var nt="onCompositionStart";break e;case"compositionend":nt="onCompositionEnd";break e;case"compositionupdate":nt="onCompositionUpdate";break e}nt=void 0}else qs?Vp(e,o)&&(nt="onCompositionEnd"):e==="keydown"&&o.keyCode===229&&(nt="onCompositionStart");nt&&(Bp&&o.locale!=="ko"&&(qs||nt!=="onCompositionStart"?nt==="onCompositionEnd"&&qs&&(Ye=Mp()):(mr=re,ud="value"in mr?mr.value:mr.textContent,qs=!0)),Oe=vc(q,nt),0<Oe.length&&(nt=new Lp(nt,e,null,o,re),ue.push({event:nt,listeners:Oe}),Ye?nt.data=Ye:(Ye=Ip(o),Ye!==null&&(nt.data=Ye)))),(Ye=GE?YE(e,o):ZE(e,o))&&(nt=vc(q,"onBeforeInput"),0<nt.length&&(Oe=new Lp("onBeforeInput","beforeinput",null,o,re),ue.push({event:Oe,listeners:nt}),Oe.data=Ye)),P_(ue,e,q,o,re)}Ny(ue,a)})}function ki(e,a,o){return{instance:e,listener:a,currentTarget:o}}function vc(e,a){for(var o=a+"Capture",l=[];e!==null;){var d=e,m=d.stateNode;if(d=d.tag,d!==5&&d!==26&&d!==27||m===null||(d=Jo(e,o),d!=null&&l.unshift(ki(e,d,m)),d=Jo(e,a),d!=null&&l.push(ki(e,d,m))),e.tag===3)return l;e=e.return}return[]}function q_(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Ay(e,a,o,l,d){for(var m=a._reactName,x=[];o!==null&&o!==l;){var N=o,M=N.alternate,q=N.stateNode;if(N=N.tag,M!==null&&M===l)break;N!==5&&N!==26&&N!==27||q===null||(M=q,d?(q=Jo(o,m),q!=null&&x.unshift(ki(o,q,M))):d||(q=Jo(o,m),q!=null&&x.push(ki(o,q,M)))),o=o.return}x.length!==0&&e.push({event:a,listeners:x})}var F_=/\r\n?/g,$_=/\u0000|\uFFFD/g;function Ty(e){return(typeof e=="string"?e:""+e).replace(F_,`+`).replace($_,"")}function Oy(e,a){return a=Ty(a),Ty(e)===a}function yt(e,a,o,l,d,m){switch(o){case"children":typeof l=="string"?a==="body"||a==="textarea"&&l===""||Hs(e,l):(typeof l=="number"||typeof l=="bigint")&&a!=="body"&&Hs(e,""+l);break;case"className":wl(e,"class",l);break;case"tabIndex":wl(e,"tabindex",l);break;case"dir":case"role":case"viewBox":case"width":case"height":wl(e,o,l);break;case"style":Op(e,l,m);break;case"data":if(a!=="object"){wl(e,"data",l);break}case"src":case"href":if(l===""&&(a!=="a"||o!=="href")){e.removeAttribute(o);break}if(l==null||typeof l=="function"||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=El(""+l),e.setAttribute(o,l);break;case"action":case"formAction":if(typeof l=="function"){e.setAttribute(o,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof m=="function"&&(o==="formAction"?(a!=="input"&&yt(e,a,"name",d.name,d,null),yt(e,a,"formEncType",d.formEncType,d,null),yt(e,a,"formMethod",d.formMethod,d,null),yt(e,a,"formTarget",d.formTarget,d,null)):(yt(e,a,"encType",d.encType,d,null),yt(e,a,"method",d.method,d,null),yt(e,a,"target",d.target,d,null)));if(l==null||typeof l=="symbol"||typeof l=="boolean"){e.removeAttribute(o);break}l=El(""+l),e.setAttribute(o,l);break;case"onClick":l!=null&&(e.onclick=Pa);break;case"onScroll":l!=null&&Je("scroll",e);break;case"onScrollEnd":l!=null&&Je("scrollend",e);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"multiple":e.multiple=l&&typeof l!="function"&&typeof l!="symbol";break;case"muted":e.muted=l&&typeof l!="function"&&typeof l!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(l==null||typeof l=="function"||typeof l=="boolean"||typeof l=="symbol"){e.removeAttribute("xlink:href");break}o=El(""+l),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""+l):e.removeAttribute(o);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":l&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,""):e.removeAttribute(o);break;case"capture":case"download":l===!0?e.setAttribute(o,""):l!==!1&&l!=null&&typeof l!="function"&&typeof l!="symbol"?e.setAttribute(o,l):e.removeAttribute(o);break;case"cols":case"rows":case"size":case"span":l!=null&&typeof l!="function"&&typeof l!="symbol"&&!isNaN(l)&&1<=l?e.setAttribute(o,l):e.removeAttribute(o);break;case"rowSpan":case"start":l==null||typeof l=="function"||typeof l=="symbol"||isNaN(l)?e.removeAttribute(o):e.setAttribute(o,l);break;case"popover":Je("beforetoggle",e),Je("toggle",e),xl(e,"popover",l);break;case"xlinkActuate":Ba(e,"http://www.w3.org/1999/xlink","xlink:actuate",l);break;case"xlinkArcrole":Ba(e,"http://www.w3.org/1999/xlink","xlink:arcrole",l);break;case"xlinkRole":Ba(e,"http://www.w3.org/1999/xlink","xlink:role",l);break;case"xlinkShow":Ba(e,"http://www.w3.org/1999/xlink","xlink:show",l);break;case"xlinkTitle":Ba(e,"http://www.w3.org/1999/xlink","xlink:title",l);break;case"xlinkType":Ba(e,"http://www.w3.org/1999/xlink","xlink:type",l);break;case"xmlBase":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:base",l);break;case"xmlLang":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:lang",l);break;case"xmlSpace":Ba(e,"http://www.w3.org/XML/1998/namespace","xml:space",l);break;case"is":xl(e,"is",l);break;case"innerText":case"textContent":break;default:(!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(o=bE.get(o)||o,xl(e,o,l))}}function Gf(e,a,o,l,d,m){switch(o){case"style":Op(e,l,m);break;case"dangerouslySetInnerHTML":if(l!=null){if(typeof l!="object"||!("__html"in l))throw Error(s(61));if(o=l.__html,o!=null){if(d.children!=null)throw Error(s(60));e.innerHTML=o}}break;case"children":typeof l=="string"?Hs(e,l):(typeof l=="number"||typeof l=="bigint")&&Hs(e,""+l);break;case"onScroll":l!=null&&Je("scroll",e);break;case"onScrollEnd":l!=null&&Je("scrollend",e);break;case"onClick":l!=null&&(e.onclick=Pa);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!wp.hasOwnProperty(o))e:{if(o[0]==="o"&&o[1]==="n"&&(d=o.endsWith("Capture"),a=o.slice(2,d?o.length-7:void 0),m=e[Sn]||null,m=m!=null?m[o]:null,typeof m=="function"&&e.removeEventListener(a,m,d),typeof l=="function")){typeof m!="function"&&m!==null&&(o in e?e[o]=null:e.hasAttribute(o)&&e.removeAttribute(o)),e.addEventListener(a,l,d);break e}o in e?e[o]=l:l===!0?e.setAttribute(o,""):xl(e,o,l)}}}function cn(e,a,o){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Je("error",e),Je("load",e);var l=!1,d=!1,m;for(m in o)if(o.hasOwnProperty(m)){var x=o[m];if(x!=null)switch(m){case"src":l=!0;break;case"srcSet":d=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:yt(e,a,m,x,o,null)}}d&&yt(e,a,"srcSet",o.srcSet,o,null),l&&yt(e,a,"src",o.src,o,null);return;case"input":Je("invalid",e);var N=m=x=d=null,M=null,q=null;for(l in o)if(o.hasOwnProperty(l)){var re=o[l];if(re!=null)switch(l){case"name":d=re;break;case"type":x=re;break;case"checked":M=re;break;case"defaultChecked":q=re;break;case"value":m=re;break;case"defaultValue":N=re;break;case"children":case"dangerouslySetInnerHTML":if(re!=null)throw Error(s(137,a));break;default:yt(e,a,l,re,o,null)}}Np(e,m,N,M,q,x,d,!1);return;case"select":Je("invalid",e),l=x=m=null;for(d in o)if(o.hasOwnProperty(d)&&(N=o[d],N!=null))switch(d){case"value":m=N;break;case"defaultValue":x=N;break;case"multiple":l=N;default:yt(e,a,d,N,o,null)}a=m,o=x,e.multiple=!!l,a!=null?Ps(e,!!l,a,!1):o!=null&&Ps(e,!!l,o,!0);return;case"textarea":Je("invalid",e),m=d=l=null;for(x in o)if(o.hasOwnProperty(x)&&(N=o[x],N!=null))switch(x){case"value":l=N;break;case"defaultValue":d=N;break;case"children":m=N;break;case"dangerouslySetInnerHTML":if(N!=null)throw Error(s(91));break;default:yt(e,a,x,N,o,null)}Ap(e,l,d,m);return;case"option":for(M in o)if(o.hasOwnProperty(M)&&(l=o[M],l!=null))switch(M){case"selected":e.selected=l&&typeof l!="function"&&typeof l!="symbol";break;default:yt(e,a,M,l,o,null)}return;case"dialog":Je("beforetoggle",e),Je("toggle",e),Je("cancel",e),Je("close",e);break;case"iframe":case"object":Je("load",e);break;case"video":case"audio":for(l=0;l<ji.length;l++)Je(ji[l],e);break;case"image":Je("error",e),Je("load",e);break;case"details":Je("toggle",e);break;case"embed":case"source":case"link":Je("error",e),Je("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(q in o)if(o.hasOwnProperty(q)&&(l=o[q],l!=null))switch(q){case"children":case"dangerouslySetInnerHTML":throw Error(s(137,a));default:yt(e,a,q,l,o,null)}return;default:if(sd(a)){for(re in o)o.hasOwnProperty(re)&&(l=o[re],l!==void 0&&Gf(e,a,re,l,o,void 0));return}}for(N in o)o.hasOwnProperty(N)&&(l=o[N],l!=null&&yt(e,a,N,l,o,null))}function G_(e,a,o,l){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var d=null,m=null,x=null,N=null,M=null,q=null,re=null;for(ee in o){var ue=o[ee];if(o.hasOwnProperty(ee)&&ue!=null)switch(ee){case"checked":break;case"value":break;case"defaultValue":M=ue;default:l.hasOwnProperty(ee)||yt(e,a,ee,null,l,ue)}}for(var Z in l){var ee=l[Z];if(ue=o[Z],l.hasOwnProperty(Z)&&(ee!=null||ue!=null))switch(Z){case"type":m=ee;break;case"name":d=ee;break;case"checked":q=ee;break;case"defaultChecked":re=ee;break;case"value":x=ee;break;case"defaultValue":N=ee;break;case"children":case"dangerouslySetInnerHTML":if(ee!=null)throw Error(s(137,a));break;default:ee!==ue&&yt(e,a,Z,ee,l,ue)}}ad(e,x,N,M,q,re,m,d);return;case"select":ee=x=N=Z=null;for(m in o)if(M=o[m],o.hasOwnProperty(m)&&M!=null)switch(m){case"value":break;case"multiple":ee=M;default:l.hasOwnProperty(m)||yt(e,a,m,null,l,M)}for(d in l)if(m=l[d],M=o[d],l.hasOwnProperty(d)&&(m!=null||M!=null))switch(d){case"value":Z=m;break;case"defaultValue":N=m;break;case"multiple":x=m;default:m!==M&&yt(e,a,d,m,l,M)}a=N,o=x,l=ee,Z!=null?Ps(e,!!o,Z,!1):!!l!=!!o&&(a!=null?Ps(e,!!o,a,!0):Ps(e,!!o,o?[]:"",!1));return;case"textarea":ee=Z=null;for(N in o)if(d=o[N],o.hasOwnProperty(N)&&d!=null&&!l.hasOwnProperty(N))switch(N){case"value":break;case"children":break;default:yt(e,a,N,null,l,d)}for(x in l)if(d=l[x],m=o[x],l.hasOwnProperty(x)&&(d!=null||m!=null))switch(x){case"value":Z=d;break;case"defaultValue":ee=d;break;case"children":break;case"dangerouslySetInnerHTML":if(d!=null)throw Error(s(91));break;default:d!==m&&yt(e,a,x,d,l,m)}Rp(e,Z,ee);return;case"option":for(var _e in o)if(Z=o[_e],o.hasOwnProperty(_e)&&Z!=null&&!l.hasOwnProperty(_e))switch(_e){case"selected":e.selected=!1;break;default:yt(e,a,_e,null,l,Z)}for(M in l)if(Z=l[M],ee=o[M],l.hasOwnProperty(M)&&Z!==ee&&(Z!=null||ee!=null))switch(M){case"selected":e.selected=Z&&typeof Z!="function"&&typeof Z!="symbol";break;default:yt(e,a,M,Z,l,ee)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var Le in o)Z=o[Le],o.hasOwnProperty(Le)&&Z!=null&&!l.hasOwnProperty(Le)&&yt(e,a,Le,null,l,Z);for(q in l)if(Z=l[q],ee=o[q],l.hasOwnProperty(q)&&Z!==ee&&(Z!=null||ee!=null))switch(q){case"children":case"dangerouslySetInnerHTML":if(Z!=null)throw Error(s(137,a));break;default:yt(e,a,q,Z,l,ee)}return;default:if(sd(a)){for(var bt in o)Z=o[bt],o.hasOwnProperty(bt)&&Z!==void 0&&!l.hasOwnProperty(bt)&&Gf(e,a,bt,void 0,l,Z);for(re in l)Z=l[re],ee=o[re],!l.hasOwnProperty(re)||Z===ee||Z===void 0&&ee===void 0||Gf(e,a,re,Z,l,ee);return}}for(var P in o)Z=o[P],o.hasOwnProperty(P)&&Z!=null&&!l.hasOwnProperty(P)&&yt(e,a,P,null,l,Z);for(ue in l)Z=l[ue],ee=o[ue],!l.hasOwnProperty(ue)||Z===ee||Z==null&&ee==null||yt(e,a,ue,Z,l,ee)}function jy(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Y_(){if(typeof performance.getEntriesByType=="function"){for(var e=0,a=0,o=performance.getEntriesByType("resource"),l=0;l<o.length;l++){var d=o[l],m=d.transferSize,x=d.initiatorType,N=d.duration;if(m&&N&&jy(x)){for(x=0,N=d.responseEnd,l+=1;l<o.length;l++){var M=o[l],q=M.startTime;if(q>N)break;var re=M.transferSize,ue=M.initiatorType;re&&jy(ue)&&(M=M.responseEnd,x+=re*(M<N?1:(N-q)/(M-q)))}if(--l,a+=8*(m+x)/(d.duration/1e3),e++,10<e)break}}if(0<e)return a/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var Yf=null,Zf=null;function yc(e){return e.nodeType===9?e:e.ownerDocument}function ky(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function My(e,a){if(e===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&a==="foreignObject"?0:e}function Xf(e,a){return e==="textarea"||e==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Kf=null;function Z_(){var e=window.event;return e&&e.type==="popstate"?e===Kf?!1:(Kf=e,!0):(Kf=null,!1)}var Dy=typeof setTimeout=="function"?setTimeout:void 0,X_=typeof clearTimeout=="function"?clearTimeout:void 0,zy=typeof Promise=="function"?Promise:void 0,K_=typeof queueMicrotask=="function"?queueMicrotask:typeof zy<"u"?function(e){return zy.resolve(null).then(e).catch(Q_)}:Dy;function Q_(e){setTimeout(function(){throw e})}function Or(e){return e==="head"}function Ly(e,a){var o=a,l=0;do{var d=o.nextSibling;if(e.removeChild(o),d&&d.nodeType===8)if(o=d.data,o==="/$"||o==="/&"){if(l===0){e.removeChild(d),yo(a);return}l--}else if(o==="$"||o==="$?"||o==="$~"||o==="$!"||o==="&")l++;else if(o==="html")Mi(e.ownerDocument.documentElement);else if(o==="head"){o=e.ownerDocument.head,Mi(o);for(var m=o.firstChild;m;){var x=m.nextSibling,N=m.nodeName;m[Qo]||N==="SCRIPT"||N==="STYLE"||N==="LINK"&&m.rel.toLowerCase()==="stylesheet"||o.removeChild(m),m=x}}else o==="body"&&Mi(e.ownerDocument.body);o=d}while(o);yo(a)}function Uy(e,a){var o=e;e=0;do{var l=o.nextSibling;if(o.nodeType===1?a?(o._stashedDisplay=o.style.display,o.style.display="none"):(o.style.display=o._stashedDisplay||"",o.getAttribute("style")===""&&o.removeAttribute("style")):o.nodeType===3&&(a?(o._stashedText=o.nodeValue,o.nodeValue=""):o.nodeValue=o._stashedText||""),l&&l.nodeType===8)if(o=l.data,o==="/$"){if(e===0)break;e--}else o!=="$"&&o!=="$?"&&o!=="$~"&&o!=="$!"||e++;o=l}while(o)}function Qf(e){var a=e.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var o=a;switch(a=a.nextSibling,o.nodeName){case"HTML":case"HEAD":case"BODY":Qf(o),td(o);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(o.rel.toLowerCase()==="stylesheet")continue}e.removeChild(o)}}function W_(e,a,o,l){for(;e.nodeType===1;){var d=o;if(e.nodeName.toLowerCase()!==a.toLowerCase()){if(!l&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(l){if(!e[Qo])switch(a){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(m=e.getAttribute("rel"),m==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(m!==d.rel||e.getAttribute("href")!==(d.href==null||d.href===""?null:d.href)||e.getAttribute("crossorigin")!==(d.crossOrigin==null?null:d.crossOrigin)||e.getAttribute("title")!==(d.title==null?null:d.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(m=e.getAttribute("src"),(m!==(d.src==null?null:d.src)||e.getAttribute("type")!==(d.type==null?null:d.type)||e.getAttribute("crossorigin")!==(d.crossOrigin==null?null:d.crossOrigin))&&m&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(a==="input"&&e.type==="hidden"){var m=d.name==null?null:""+d.name;if(d.type==="hidden"&&e.getAttribute("name")===m)return e}else return e;if(e=na(e.nextSibling),e===null)break}return null}function J_(e,a,o){if(a==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!o||(e=na(e.nextSibling),e===null))return null;return e}function By(e,a){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!a||(e=na(e.nextSibling),e===null))return null;return e}function Wf(e){return e.data==="$?"||e.data==="$~"}function Jf(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function eC(e,a){var o=e.ownerDocument;if(e.data==="$~")e._reactRetry=a;else if(e.data!=="$?"||o.readyState!=="loading")a();else{var l=function(){a(),o.removeEventListener("DOMContentLoaded",l)};o.addEventListener("DOMContentLoaded",l),e._reactRetry=l}}function na(e){for(;e!=null;e=e.nextSibling){var a=e.nodeType;if(a===1||a===3)break;if(a===8){if(a=e.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return e}var em=null;function Py(e){e=e.nextSibling;for(var a=0;e;){if(e.nodeType===8){var o=e.data;if(o==="/$"||o==="/&"){if(a===0)return na(e.nextSibling);a--}else o!=="$"&&o!=="$!"&&o!=="$?"&&o!=="$~"&&o!=="&"||a++}e=e.nextSibling}return null}function Hy(e){e=e.previousSibling;for(var a=0;e;){if(e.nodeType===8){var o=e.data;if(o==="$"||o==="$!"||o==="$?"||o==="$~"||o==="&"){if(a===0)return e;a--}else o!=="/$"&&o!=="/&"||a++}e=e.previousSibling}return null}function Vy(e,a,o){switch(a=yc(o),e){case"html":if(e=a.documentElement,!e)throw Error(s(452));return e;case"head":if(e=a.head,!e)throw Error(s(453));return e;case"body":if(e=a.body,!e)throw Error(s(454));return e;default:throw Error(s(451))}}function Mi(e){for(var a=e.attributes;a.length;)e.removeAttributeNode(a[0]);td(e)}var aa=new Map,Iy=new Set;function bc(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var tr=K.d;K.d={f:tC,r:nC,D:aC,C:rC,L:sC,m:oC,X:lC,S:iC,M:cC};function tC(){var e=tr.f(),a=uc();return e||a}function nC(e){var a=Ls(e);a!==null&&a.tag===5&&a.type==="form"?sv(a):tr.r(e)}var po=typeof document>"u"?null:document;function qy(e,a,o){var l=po;if(l&&typeof a=="string"&&a){var d=Xn(a);d='link[rel="'+e+'"][href="'+d+'"]',typeof o=="string"&&(d+='[crossorigin="'+o+'"]'),Iy.has(d)||(Iy.add(d),e={rel:e,crossOrigin:o,href:a},l.querySelector(d)===null&&(a=l.createElement("link"),cn(a,"link",e),tn(a),l.head.appendChild(a)))}}function aC(e){tr.D(e),qy("dns-prefetch",e,null)}function rC(e,a){tr.C(e,a),qy("preconnect",e,a)}function sC(e,a,o){tr.L(e,a,o);var l=po;if(l&&e&&a){var d='link[rel="preload"][as="'+Xn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(d+='[imagesrcset="'+Xn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(d+='[imagesizes="'+Xn(o.imageSizes)+'"]')):d+='[href="'+Xn(e)+'"]';var m=d;switch(a){case"style":m=go(e);break;case"script":m=vo(e)}aa.has(m)||(e=v({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:e,as:a},o),aa.set(m,e),l.querySelector(d)!==null||a==="style"&&l.querySelector(Di(m))||a==="script"&&l.querySelector(zi(m))||(a=l.createElement("link"),cn(a,"link",e),tn(a),l.head.appendChild(a)))}}function oC(e,a){tr.m(e,a);var o=po;if(o&&e){var l=a&&typeof a.as=="string"?a.as:"script",d='link[rel="modulepreload"][as="'+Xn(l)+'"][href="'+Xn(e)+'"]',m=d;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=vo(e)}if(!aa.has(m)&&(e=v({rel:"modulepreload",href:e},a),aa.set(m,e),o.querySelector(d)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(zi(m)))return}l=o.createElement("link"),cn(l,"link",e),tn(l),o.head.appendChild(l)}}}function iC(e,a,o){tr.S(e,a,o);var l=po;if(l&&e){var d=Us(l).hoistableStyles,m=go(e);a=a||"default";var x=d.get(m);if(!x){var N={loading:0,preload:null};if(x=l.querySelector(Di(m)))N.loading=5;else{e=v({rel:"stylesheet",href:e,"data-precedence":a},o),(o=aa.get(m))&&tm(e,o);var M=x=l.createElement("link");tn(M),cn(M,"link",e),M._p=new Promise(function(q,re){M.onload=q,M.onerror=re}),M.addEventListener("load",function(){N.loading|=1}),M.addEventListener("error",function(){N.loading|=2}),N.loading|=4,xc(x,a,l)}x={type:"stylesheet",instance:x,count:1,state:N},d.set(m,x)}}}function lC(e,a){tr.X(e,a);var o=po;if(o&&e){var l=Us(o).hoistableScripts,d=vo(e),m=l.get(d);m||(m=o.querySelector(zi(d)),m||(e=v({src:e,async:!0},a),(a=aa.get(d))&&nm(e,a),m=o.createElement("script"),tn(m),cn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function cC(e,a){tr.M(e,a);var o=po;if(o&&e){var l=Us(o).hoistableScripts,d=vo(e),m=l.get(d);m||(m=o.querySelector(zi(d)),m||(e=v({src:e,async:!0,type:"module"},a),(a=aa.get(d))&&nm(e,a),m=o.createElement("script"),tn(m),cn(m,"link",e),o.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(d,m))}}function Fy(e,a,o,l){var d=(d=ie.current)?bc(d):null;if(!d)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=go(o.href),o=Us(d).hoistableStyles,l=o.get(a),l||(l={type:"style",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){e=go(o.href);var m=Us(d).hoistableStyles,x=m.get(e);if(x||(d=d.ownerDocument||d,x={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},m.set(e,x),(m=d.querySelector(Di(e)))&&!m._p&&(x.instance=m,x.state.loading=5),aa.has(e)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},aa.set(e,o),m||uC(d,e,o,x.state))),a&&l===null)throw Error(s(528,""));return x}if(a&&l!==null)throw Error(s(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=vo(o),o=Us(d).hoistableScripts,l=o.get(a),l||(l={type:"script",instance:null,count:0,state:null},o.set(a,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function go(e){return'href="'+Xn(e)+'"'}function Di(e){return'link[rel="stylesheet"]['+e+"]"}function $y(e){return v({},e,{"data-precedence":e.precedence,precedence:null})}function uC(e,a,o,l){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?l.loading=1:(a=e.createElement("link"),l.preload=a,a.addEventListener("load",function(){return l.loading|=1}),a.addEventListener("error",function(){return l.loading|=2}),cn(a,"link",o),tn(a),e.head.appendChild(a))}function vo(e){return'[src="'+Xn(e)+'"]'}function zi(e){return"script[async]"+e}function Gy(e,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var l=e.querySelector('style[data-href~="'+Xn(o.href)+'"]');if(l)return a.instance=l,tn(l),l;var d=v({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return l=(e.ownerDocument||e).createElement("style"),tn(l),cn(l,"style",d),xc(l,o.precedence,e),a.instance=l;case"stylesheet":d=go(o.href);var m=e.querySelector(Di(d));if(m)return a.state.loading|=4,a.instance=m,tn(m),m;l=$y(o),(d=aa.get(d))&&tm(l,d),m=(e.ownerDocument||e).createElement("link"),tn(m);var x=m;return x._p=new Promise(function(N,M){x.onload=N,x.onerror=M}),cn(m,"link",l),a.state.loading|=4,xc(m,o.precedence,e),a.instance=m;case"script":return m=vo(o.src),(d=e.querySelector(zi(m)))?(a.instance=d,tn(d),d):(l=o,(d=aa.get(m))&&(l=v({},o),nm(l,d)),e=e.ownerDocument||e,d=e.createElement("script"),tn(d),cn(d,"link",l),e.head.appendChild(d),a.instance=d);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(l=a.instance,a.state.loading|=4,xc(l,o.precedence,e));return a.instance}function xc(e,a,o){for(var l=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),d=l.length?l[l.length-1]:null,m=d,x=0;x<l.length;x++){var N=l[x];if(N.dataset.precedence===a)m=N;else if(m!==d)break}m?m.parentNode.insertBefore(e,m.nextSibling):(a=o.nodeType===9?o.head:o,a.insertBefore(e,a.firstChild))}function tm(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.title==null&&(e.title=a.title)}function nm(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.integrity==null&&(e.integrity=a.integrity)}var wc=null;function Yy(e,a,o){if(wc===null){var l=new Map,d=wc=new Map;d.set(o,l)}else d=wc,l=d.get(o),l||(l=new Map,d.set(o,l));if(l.has(e))return l;for(l.set(e,null),o=o.getElementsByTagName(e),d=0;d<o.length;d++){var m=o[d];if(!(m[Qo]||m[rn]||e==="link"&&m.getAttribute("rel")==="stylesheet")&&m.namespaceURI!=="http://www.w3.org/2000/svg"){var x=m.getAttribute(a)||"";x=e+x;var N=l.get(x);N?N.push(m):l.set(x,[m])}}return l}function Zy(e,a,o){e=e.ownerDocument||e,e.head.insertBefore(o,a==="title"?e.querySelector("head > title"):null)}function dC(e,a,o){if(o===1||a.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return e=a.disabled,typeof a.precedence=="string"&&e==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Xy(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function fC(e,a,o,l){if(o.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var d=go(l.href),m=a.querySelector(Di(d));if(m){a=m._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=Sc.bind(e),a.then(e,e)),o.state.loading|=4,o.instance=m,tn(m);return}m=a.ownerDocument||a,l=$y(l),(d=aa.get(d))&&tm(l,d),m=m.createElement("link"),tn(m);var x=m;x._p=new Promise(function(N,M){x.onload=N,x.onerror=M}),cn(m,"link",l),o.instance=m}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(e.count++,o=Sc.bind(e),a.addEventListener("load",o),a.addEventListener("error",o))}}var am=0;function mC(e,a){return e.stylesheets&&e.count===0&&_c(e,e.stylesheets),0<e.count||0<e.imgCount?function(o){var l=setTimeout(function(){if(e.stylesheets&&_c(e,e.stylesheets),e.unsuspend){var m=e.unsuspend;e.unsuspend=null,m()}},6e4+a);0<e.imgBytes&&am===0&&(am=62500*Y_());var d=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&_c(e,e.stylesheets),e.unsuspend)){var m=e.unsuspend;e.unsuspend=null,m()}},(e.imgBytes>am?50:800)+a);return e.unsuspend=o,function(){e.unsuspend=null,clearTimeout(l),clearTimeout(d)}}:null}function Sc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_c(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Ec=null;function _c(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Ec=new Map,a.forEach(hC,e),Ec=null,Sc.call(e))}function hC(e,a){if(!(a.state.loading&4)){var o=Ec.get(e);if(o)var l=o.get(null);else{o=new Map,Ec.set(e,o);for(var d=e.querySelectorAll("link[data-precedence],style[data-precedence]"),m=0;m<d.length;m++){var x=d[m];(x.nodeName==="LINK"||x.getAttribute("media")!=="not all")&&(o.set(x.dataset.precedence,x),l=x)}l&&o.set(null,l)}d=a.instance,x=d.getAttribute("data-precedence"),m=o.get(x)||l,m===l&&o.set(null,d),o.set(x,d),this.count++,l=Sc.bind(this),d.addEventListener("load",l),d.addEventListener("error",l),m?m.parentNode.insertBefore(d,m.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(d,e.firstChild)),a.state.loading|=4}}var Li={$$typeof:A,Provider:null,Consumer:null,_currentValue:te,_currentValue2:te,_threadCount:0};function pC(e,a,o,l,d,m,x,N,M){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=dr(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=dr(0),this.hiddenUpdates=dr(null),this.identifierPrefix=l,this.onUncaughtError=d,this.onCaughtError=m,this.onRecoverableError=x,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=M,this.incompleteTransitions=new Map}function Ky(e,a,o,l,d,m,x,N,M,q,re,ue){return e=new pC(e,a,o,x,M,q,re,ue,N),a=1,m===!0&&(a|=24),m=Dn(3,null,null,a),e.current=m,m.stateNode=e,a=zd(),a.refCount++,e.pooledCache=a,a.refCount++,m.memoizedState={element:l,isDehydrated:o,cache:a},Pd(m),e}function Qy(e){return e?(e=Ys,e):Ys}function Wy(e,a,o,l,d,m){d=Qy(d),l.context===null?l.context=d:l.pendingContext=d,l=br(a),l.payload={element:o},m=m===void 0?null:m,m!==null&&(l.callback=m),o=xr(e,l,a),o!==null&&(An(o,e,a),hi(o,e,a))}function Jy(e,a){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var o=e.retryLane;e.retryLane=o!==0&&o<a?o:a}}function rm(e,a){Jy(e,a),(e=e.alternate)&&Jy(e,a)}function eb(e){if(e.tag===13||e.tag===31){var a=rs(e,67108864);a!==null&&An(a,e,67108864),rm(e,67108864)}}function tb(e){if(e.tag===13||e.tag===31){var a=Pn();a=Ms(a);var o=rs(e,a);o!==null&&An(o,e,a),rm(e,a)}}var Cc=!0;function gC(e,a,o,l){var d=T.T;T.T=null;var m=K.p;try{K.p=2,sm(e,a,o,l)}finally{K.p=m,T.T=d}}function vC(e,a,o,l){var d=T.T;T.T=null;var m=K.p;try{K.p=8,sm(e,a,o,l)}finally{K.p=m,T.T=d}}function sm(e,a,o,l){if(Cc){var d=om(l);if(d===null)$f(e,a,l,Nc,o),ab(e,l);else if(bC(d,e,a,o,l))l.stopPropagation();else if(ab(e,l),a&4&&-1<yC.indexOf(e)){for(;d!==null;){var m=Ls(d);if(m!==null)switch(m.tag){case 3:if(m=m.stateNode,m.current.memoizedState.isDehydrated){var x=xa(m.pendingLanes);if(x!==0){var N=m;for(N.pendingLanes|=2,N.entangledLanes|=2;x;){var M=1<<31-Ht(x);N.entanglements[1]|=M,x&=~M}_a(m),(ft&6)===0&&(lc=V()+500,Oi(0))}}break;case 31:case 13:N=rs(m,2),N!==null&&An(N,m,2),uc(),rm(m,2)}if(m=om(l),m===null&&$f(e,a,l,Nc,o),m===d)break;d=m}d!==null&&l.stopPropagation()}else $f(e,a,l,null,o)}}function om(e){return e=id(e),im(e)}var Nc=null;function im(e){if(Nc=null,e=zs(e),e!==null){var a=c(e);if(a===null)e=null;else{var o=a.tag;if(o===13){if(e=u(a),e!==null)return e;e=null}else if(o===31){if(e=f(a),e!==null)return e;e=null}else if(o===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;e=null}else a!==e&&(e=null)}}return Nc=e,null}function nb(e){switch(e){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(we()){case ge:return 2;case ye:return 8;case Se:case Ue:return 32;case Ge:return 268435456;default:return 32}default:return 32}}var lm=!1,jr=null,kr=null,Mr=null,Ui=new Map,Bi=new Map,Dr=[],yC="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function ab(e,a){switch(e){case"focusin":case"focusout":jr=null;break;case"dragenter":case"dragleave":kr=null;break;case"mouseover":case"mouseout":Mr=null;break;case"pointerover":case"pointerout":Ui.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":Bi.delete(a.pointerId)}}function Pi(e,a,o,l,d,m){return e===null||e.nativeEvent!==m?(e={blockedOn:a,domEventName:o,eventSystemFlags:l,nativeEvent:m,targetContainers:[d]},a!==null&&(a=Ls(a),a!==null&&eb(a)),e):(e.eventSystemFlags|=l,a=e.targetContainers,d!==null&&a.indexOf(d)===-1&&a.push(d),e)}function bC(e,a,o,l,d){switch(a){case"focusin":return jr=Pi(jr,e,a,o,l,d),!0;case"dragenter":return kr=Pi(kr,e,a,o,l,d),!0;case"mouseover":return Mr=Pi(Mr,e,a,o,l,d),!0;case"pointerover":var m=d.pointerId;return Ui.set(m,Pi(Ui.get(m)||null,e,a,o,l,d)),!0;case"gotpointercapture":return m=d.pointerId,Bi.set(m,Pi(Bi.get(m)||null,e,a,o,l,d)),!0}return!1}function rb(e){var a=zs(e.target);if(a!==null){var o=c(a);if(o!==null){if(a=o.tag,a===13){if(a=u(o),a!==null){e.blockedOn=a,yp(e.priority,function(){tb(o)});return}}else if(a===31){if(a=f(o),a!==null){e.blockedOn=a,yp(e.priority,function(){tb(o)});return}}else if(a===3&&o.stateNode.current.memoizedState.isDehydrated){e.blockedOn=o.tag===3?o.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Rc(e){if(e.blockedOn!==null)return!1;for(var a=e.targetContainers;0<a.length;){var o=om(e.nativeEvent);if(o===null){o=e.nativeEvent;var l=new o.constructor(o.type,o);od=l,o.target.dispatchEvent(l),od=null}else return a=Ls(o),a!==null&&eb(a),e.blockedOn=o,!1;a.shift()}return!0}function sb(e,a,o){Rc(e)&&o.delete(a)}function xC(){lm=!1,jr!==null&&Rc(jr)&&(jr=null),kr!==null&&Rc(kr)&&(kr=null),Mr!==null&&Rc(Mr)&&(Mr=null),Ui.forEach(sb),Bi.forEach(sb)}function Ac(e,a){e.blockedOn===a&&(e.blockedOn=null,lm||(lm=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,xC)))}var Tc=null;function ob(e){Tc!==e&&(Tc=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Tc===e&&(Tc=null);for(var a=0;a<e.length;a+=3){var o=e[a],l=e[a+1],d=e[a+2];if(typeof l!="function"){if(im(l||o)===null)continue;break}var m=Ls(o);m!==null&&(e.splice(a,3),a-=3,sf(m,{pending:!0,data:d,method:o.method,action:l},l,d))}}))}function yo(e){function a(M){return Ac(M,e)}jr!==null&&Ac(jr,e),kr!==null&&Ac(kr,e),Mr!==null&&Ac(Mr,e),Ui.forEach(a),Bi.forEach(a);for(var o=0;o<Dr.length;o++){var l=Dr[o];l.blockedOn===e&&(l.blockedOn=null)}for(;0<Dr.length&&(o=Dr[0],o.blockedOn===null);)rb(o),o.blockedOn===null&&Dr.shift();if(o=(e.ownerDocument||e).$$reactFormReplay,o!=null)for(l=0;l<o.length;l+=3){var d=o[l],m=o[l+1],x=d[Sn]||null;if(typeof m=="function")x||ob(o);else if(x){var N=null;if(m&&m.hasAttribute("formAction")){if(d=m,x=m[Sn]||null)N=x.formAction;else if(im(d)!==null)continue}else N=x.action;typeof N=="function"?o[l+1]=N:(o.splice(l,3),l-=3),ob(o)}}}function ib(){function e(m){m.canIntercept&&m.info==="react-transition"&&m.intercept({handler:function(){return new Promise(function(x){return d=x})},focusReset:"manual",scroll:"manual"})}function a(){d!==null&&(d(),d=null),l||setTimeout(o,20)}function o(){if(!l&&!navigation.transition){var m=navigation.currentEntry;m&&m.url!=null&&navigation.navigate(m.url,{state:m.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var l=!1,d=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(o,100),function(){l=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),d!==null&&(d(),d=null)}}}function cm(e){this._internalRoot=e}Oc.prototype.render=cm.prototype.render=function(e){var a=this._internalRoot;if(a===null)throw Error(s(409));var o=a.current,l=Pn();Wy(o,l,e,a,null,null)},Oc.prototype.unmount=cm.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var a=e.containerInfo;Wy(e.current,2,null,e,null,null),uc(),a[Ds]=null}};function Oc(e){this._internalRoot=e}Oc.prototype.unstable_scheduleHydration=function(e){if(e){var a=Ju();e={blockedOn:null,target:e,priority:a};for(var o=0;o<Dr.length&&a!==0&&a<Dr[o].priority;o++);Dr.splice(o,0,e),o===0&&rb(e)}};var lb=n.version;if(lb!=="19.2.4")throw Error(s(527,lb,"19.2.4"));K.findDOMNode=function(e){var a=e._reactInternals;if(a===void 0)throw typeof e.render=="function"?Error(s(188)):(e=Object.keys(e).join(","),Error(s(268,e)));return e=p(a),e=e!==null?y(e):null,e=e===null?null:e.stateNode,e};var wC={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:T,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var jc=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!jc.isDisabled&&jc.supportsFiber)try{mt=jc.inject(wC),Dt=jc}catch{}}return Vi.createRoot=function(e,a){if(!i(e))throw Error(s(299));var o=!1,l="",d=pv,m=gv,x=vv;return a!=null&&(a.unstable_strictMode===!0&&(o=!0),a.identifierPrefix!==void 0&&(l=a.identifierPrefix),a.onUncaughtError!==void 0&&(d=a.onUncaughtError),a.onCaughtError!==void 0&&(m=a.onCaughtError),a.onRecoverableError!==void 0&&(x=a.onRecoverableError)),a=Ky(e,1,!1,null,null,o,l,null,d,m,x,ib),e[Ds]=a.current,Ff(e),new cm(a)},Vi.hydrateRoot=function(e,a,o){if(!i(e))throw Error(s(299));var l=!1,d="",m=pv,x=gv,N=vv,M=null;return o!=null&&(o.unstable_strictMode===!0&&(l=!0),o.identifierPrefix!==void 0&&(d=o.identifierPrefix),o.onUncaughtError!==void 0&&(m=o.onUncaughtError),o.onCaughtError!==void 0&&(x=o.onCaughtError),o.onRecoverableError!==void 0&&(N=o.onRecoverableError),o.formState!==void 0&&(M=o.formState)),a=Ky(e,1,!0,a,o??null,l,d,M,m,x,N,ib),a.context=Qy(null),o=a.current,l=Pn(),l=Ms(l),d=br(l),d.callback=null,xr(o,d,l),o=l,a.current.lanes=o,Rt(a,o),_a(a),e[Ds]=a.current,Ff(e),new Oc(a)},Vi.version="19.2.4",Vi}var bb;function MC(){if(bb)return fm.exports;bb=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),fm.exports=kC(),fm.exports}var DC=MC();/**+ * react-router v7.13.2+ *+ * 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+ */var xb="popstate";function wb(t){return typeof t=="object"&&t!=null&&"pathname"in t&&"search"in t&&"hash"in t&&"state"in t&&"key"in t}function zC(t={}){function n(s,i){var p;let c=(p=i.state)==null?void 0:p.masked,{pathname:u,search:f,hash:g}=c||s.location;return Fm("",{pathname:u,search:f,hash:g},i.state&&i.state.usr||null,i.state&&i.state.key||"default",c?{pathname:s.location.pathname,search:s.location.search,hash:s.location.hash}:void 0)}function r(s,i){return typeof i=="string"?i:Ji(i)}return UC(n,r,null,t)}function Nt(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function oa(t,n){if(!t){typeof console<"u"&&console.warn(n);try{throw new Error(n)}catch{}}}function LC(){return Math.random().toString(36).substring(2,10)}function Sb(t,n){return{usr:t.state,key:t.key,idx:n,masked:t.unstable_mask?{pathname:t.pathname,search:t.search,hash:t.hash}:void 0}}function Fm(t,n,r=null,s,i){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof n=="string"?qo(n):n,state:r,key:n&&n.key||s||LC(),unstable_mask:i}}function Ji({pathname:t="/",search:n="",hash:r=""}){return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function qo(t){let n={};if(t){let r=t.indexOf("#");r>=0&&(n.hash=t.substring(r),t=t.substring(0,r));let s=t.indexOf("?");s>=0&&(n.search=t.substring(s),t=t.substring(0,s)),t&&(n.pathname=t)}return n}function UC(t,n,r,s={}){let{window:i=document.defaultView,v5Compat:c=!1}=s,u=i.history,f="POP",g=null,p=y();p==null&&(p=0,u.replaceState({...u.state,idx:p},""));function y(){return(u.state||{idx:null}).idx}function v(){f="POP";let E=y(),R=E==null?null:E-p;p=E,g&&g({action:f,location:_.location,delta:R})}function w(E,R){f="PUSH";let k=wb(E)?E:Fm(_.location,E,R);p=y()+1;let A=Sb(k,p),D=_.createHref(k.unstable_mask||k);try{u.pushState(A,"",D)}catch(H){if(H instanceof DOMException&&H.name==="DataCloneError")throw H;i.location.assign(D)}c&&g&&g({action:f,location:_.location,delta:1})}function C(E,R){f="REPLACE";let k=wb(E)?E:Fm(_.location,E,R);p=y();let A=Sb(k,p),D=_.createHref(k.unstable_mask||k);u.replaceState(A,"",D),c&&g&&g({action:f,location:_.location,delta:0})}function S(E){return BC(E)}let _={get action(){return f},get location(){return t(i,u)},listen(E){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(xb,v),g=E,()=>{i.removeEventListener(xb,v),g=null}},createHref(E){return n(i,E)},createURL:S,encodeLocation(E){let R=S(E);return{pathname:R.pathname,search:R.search,hash:R.hash}},push:w,replace:C,go(E){return u.go(E)}};return _}function BC(t,n=!1){let r="http://localhost";typeof window<"u"&&(r=window.location.origin!=="null"?window.location.origin:window.location.href),Nt(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:Ji(t);return s=s.replace(/ $/,"%20"),!n&&s.startsWith("//")&&(s=r+s),new URL(s,r)}function b0(t,n,r="/"){return PC(t,n,r,!1)}function PC(t,n,r,s){let i=typeof n=="string"?qo(n):n,c=rr(i.pathname||"/",r);if(c==null)return null;let u=x0(t);HC(u);let f=null;for(let g=0;f==null&&g<u.length;++g){let p=QC(c);f=XC(u[g],p,s)}return f}function x0(t,n=[],r=[],s="",i=!1){let c=(u,f,g=i,p)=>{let y={relativePath:p===void 0?u.path||"":p,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(y.relativePath.startsWith("/")){if(!y.relativePath.startsWith(s)&&g)return;Nt(y.relativePath.startsWith(s),`Absolute route path "${y.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),y.relativePath=y.relativePath.slice(s.length)}let v=ja([s,y.relativePath]),w=r.concat(y);u.children&&u.children.length>0&&(Nt(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${v}".`),x0(u.children,n,w,v,g)),!(u.path==null&&!u.index)&&n.push({path:v,score:YC(v,u.index),routesMeta:w})};return t.forEach((u,f)=>{var g;if(u.path===""||!((g=u.path)!=null&&g.includes("?")))c(u,f);else for(let p of w0(u.path))c(u,f,!0,p)}),n}function w0(t){let n=t.split("/");if(n.length===0)return[];let[r,...s]=n,i=r.endsWith("?"),c=r.replace(/\?$/,"");if(s.length===0)return i?[c,""]:[c];let u=w0(s.join("/")),f=[];return f.push(...u.map(g=>g===""?c:[c,g].join("/"))),i&&f.push(...u),f.map(g=>t.startsWith("/")&&g===""?"/":g)}function HC(t){t.sort((n,r)=>n.score!==r.score?r.score-n.score:ZC(n.routesMeta.map(s=>s.childrenIndex),r.routesMeta.map(s=>s.childrenIndex)))}var VC=/^:[\w-]+$/,IC=3,qC=2,FC=1,$C=10,GC=-2,Eb=t=>t==="*";function YC(t,n){let r=t.split("/"),s=r.length;return r.some(Eb)&&(s+=GC),n&&(s+=qC),r.filter(i=>!Eb(i)).reduce((i,c)=>i+(VC.test(c)?IC:c===""?FC:$C),s)}function ZC(t,n){return t.length===n.length&&t.slice(0,-1).every((s,i)=>s===n[i])?t[t.length-1]-n[n.length-1]:0}function XC(t,n,r=!1){let{routesMeta:s}=t,i={},c="/",u=[];for(let f=0;f<s.length;++f){let g=s[f],p=f===s.length-1,y=c==="/"?n:n.slice(c.length)||"/",v=eu({path:g.relativePath,caseSensitive:g.caseSensitive,end:p},y),w=g.route;if(!v&&p&&r&&!s[s.length-1].route.index&&(v=eu({path:g.relativePath,caseSensitive:g.caseSensitive,end:!1},y)),!v)return null;Object.assign(i,v.params),u.push({params:i,pathname:ja([c,v.pathname]),pathnameBase:tN(ja([c,v.pathnameBase])),route:w}),v.pathnameBase!=="/"&&(c=ja([c,v.pathnameBase]))}return u}function eu(t,n){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[r,s]=KC(t.path,t.caseSensitive,t.end),i=n.match(r);if(!i)return null;let c=i[0],u=c.replace(/(.)\/+$/,"$1"),f=i.slice(1);return{params:s.reduce((p,{paramName:y,isOptional:v},w)=>{if(y==="*"){let S=f[w]||"";u=c.slice(0,c.length-S.length).replace(/(.)\/+$/,"$1")}const C=f[w];return v&&!C?p[y]=void 0:p[y]=(C||"").replace(/%2F/g,"/"),p},{}),pathname:c,pathnameBase:u,pattern:t}}function KC(t,n=!1,r=!0){oa(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let s=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(u,f,g,p,y)=>{if(s.push({paramName:f,isOptional:g!=null}),g){let v=y.charAt(p+u.length);return v&&v!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(s.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,n?void 0:"i"),s]}function QC(t){try{return t.split("/").map(n=>decodeURIComponent(n).replace(/\//g,"%2F")).join("/")}catch(n){return oa(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${n}).`),t}}function rr(t,n){if(n==="/")return t;if(!t.toLowerCase().startsWith(n.toLowerCase()))return null;let r=n.endsWith("/")?n.length-1:n.length,s=t.charAt(r);return s&&s!=="/"?null:t.slice(r)||"/"}var WC=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function JC(t,n="/"){let{pathname:r,search:s="",hash:i=""}=typeof t=="string"?qo(t):t,c;return r?(r=r.replace(/\/\/+/g,"/"),r.startsWith("/")?c=_b(r.substring(1),"/"):c=_b(r,n)):c=n,{pathname:c,search:nN(s),hash:aN(i)}}function _b(t,n){let r=n.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function gm(t,n,r,s){return`Cannot include a '${t}' character in a manually specified \`to.${n}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${r}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function eN(t){return t.filter((n,r)=>r===0||n.route.path&&n.route.path.length>0)}function Sh(t){let n=eN(t);return n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase)}function Ru(t,n,r,s=!1){let i;typeof t=="string"?i=qo(t):(i={...t},Nt(!i.pathname||!i.pathname.includes("?"),gm("?","pathname","search",i)),Nt(!i.pathname||!i.pathname.includes("#"),gm("#","pathname","hash",i)),Nt(!i.search||!i.search.includes("#"),gm("#","search","hash",i)));let c=t===""||i.pathname==="",u=c?"/":i.pathname,f;if(u==null)f=r;else{let v=n.length-1;if(!s&&u.startsWith("..")){let w=u.split("/");for(;w[0]==="..";)w.shift(),v-=1;i.pathname=w.join("/")}f=v>=0?n[v]:"/"}let g=JC(i,f),p=u&&u!=="/"&&u.endsWith("/"),y=(c||u===".")&&r.endsWith("/");return!g.pathname.endsWith("/")&&(p||y)&&(g.pathname+="/"),g}var ja=t=>t.join("/").replace(/\/\/+/g,"/"),tN=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),nN=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,aN=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,rN=class{constructor(t,n,r,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 sN(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function oN(t){return t.map(n=>n.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var S0=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function E0(t,n){let r=t;if(typeof r!="string"||!WC.test(r))return{absoluteURL:void 0,isExternal:!1,to:r};let s=r,i=!1;if(S0)try{let c=new URL(window.location.href),u=r.startsWith("//")?new URL(c.protocol+r):new URL(r),f=rr(u.pathname,n);u.origin===c.origin&&f!=null?r=f+u.search+u.hash:i=!0}catch{oa(!1,`<Link to="${r}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:s,isExternal:i,to:r}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var _0=["POST","PUT","PATCH","DELETE"];new Set(_0);var iN=["GET",..._0];new Set(iN);var Fo=b.createContext(null);Fo.displayName="DataRouter";var Au=b.createContext(null);Au.displayName="DataRouterState";var lN=b.createContext(!1),C0=b.createContext({isTransitioning:!1});C0.displayName="ViewTransition";var cN=b.createContext(new Map);cN.displayName="Fetchers";var uN=b.createContext(null);uN.displayName="Await";var Gn=b.createContext(null);Gn.displayName="Navigation";var il=b.createContext(null);il.displayName="Location";var ia=b.createContext({outlet:null,matches:[],isDataRoute:!1});ia.displayName="Route";var Eh=b.createContext(null);Eh.displayName="RouteError";var N0="REACT_ROUTER_ERROR",dN="REDIRECT",fN="ROUTE_ERROR_RESPONSE";function mN(t){if(t.startsWith(`${N0}:${dN}:{`))try{let n=JSON.parse(t.slice(28));if(typeof n=="object"&&n&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.location=="string"&&typeof n.reloadDocument=="boolean"&&typeof n.replace=="boolean")return n}catch{}}function hN(t){if(t.startsWith(`${N0}:${fN}:{`))try{let n=JSON.parse(t.slice(40));if(typeof n=="object"&&n&&typeof n.status=="number"&&typeof n.statusText=="string")return new rN(n.status,n.statusText,n.data)}catch{}}function pN(t,{relative:n}={}){Nt($o(),"useHref() may be used only in the context of a <Router> component.");let{basename:r,navigator:s}=b.useContext(Gn),{hash:i,pathname:c,search:u}=ll(t,{relative:n}),f=c;return r!=="/"&&(f=c==="/"?r:ja([r,c])),s.createHref({pathname:f,search:u,hash:i})}function $o(){return b.useContext(il)!=null}function Da(){return Nt($o(),"useLocation() may be used only in the context of a <Router> component."),b.useContext(il).location}var R0="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function A0(t){b.useContext(Gn).static||b.useLayoutEffect(t)}function Xr(){let{isDataRoute:t}=b.useContext(ia);return t?jN():gN()}function gN(){Nt($o(),"useNavigate() may be used only in the context of a <Router> component.");let t=b.useContext(Fo),{basename:n,navigator:r}=b.useContext(Gn),{matches:s}=b.useContext(ia),{pathname:i}=Da(),c=JSON.stringify(Sh(s)),u=b.useRef(!1);return A0(()=>{u.current=!0}),b.useCallback((g,p={})=>{if(oa(u.current,R0),!u.current)return;if(typeof g=="number"){r.go(g);return}let y=Ru(g,JSON.parse(c),i,p.relative==="path");t==null&&n!=="/"&&(y.pathname=y.pathname==="/"?n:ja([n,y.pathname])),(p.replace?r.replace:r.push)(y,p.state,p)},[n,r,c,i,t])}var vN=b.createContext(null);function yN(t){let n=b.useContext(ia).outlet;return b.useMemo(()=>n&&b.createElement(vN.Provider,{value:t},n),[n,t])}function bN(){let{matches:t}=b.useContext(ia),n=t[t.length-1];return n?n.params:{}}function ll(t,{relative:n}={}){let{matches:r}=b.useContext(ia),{pathname:s}=Da(),i=JSON.stringify(Sh(r));return b.useMemo(()=>Ru(t,JSON.parse(i),s,n==="path"),[t,i,s,n])}function xN(t,n){return T0(t,n)}function T0(t,n,r){var E;Nt($o(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=b.useContext(Gn),{matches:i}=b.useContext(ia),c=i[i.length-1],u=c?c.params:{},f=c?c.pathname:"/",g=c?c.pathnameBase:"/",p=c&&c.route;{let R=p&&p.path||"";j0(f,!p||R.endsWith("*")||R.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${f}" (under <Route path="${R}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.++Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}/*`}">.`)}let y=Da(),v;if(n){let R=typeof n=="string"?qo(n):n;Nt(g==="/"||((E=R.pathname)==null?void 0:E.startsWith(g)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${g}" but pathname "${R.pathname}" was given in the \`location\` prop.`),v=R}else v=y;let w=v.pathname||"/",C=w;if(g!=="/"){let R=g.replace(/^\//,"").split("/");C="/"+w.replace(/^\//,"").split("/").slice(R.length).join("/")}let S=b0(t,{pathname:C});oa(p||S!=null,`No routes matched location "${v.pathname}${v.search}${v.hash}" `),oa(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${v.pathname}${v.search}${v.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let _=CN(S&&S.map(R=>Object.assign({},R,{params:Object.assign({},u,R.params),pathname:ja([g,s.encodeLocation?s.encodeLocation(R.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?g:ja([g,s.encodeLocation?s.encodeLocation(R.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:R.pathnameBase])})),i,r);return n&&_?b.createElement(il.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...v},navigationType:"POP"}},_):_}function wN(){let t=ON(),n=sN(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,s="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:s},c={padding:"2px 4px",backgroundColor:s},u=null;return console.error("Error handled by React Router default ErrorBoundary:",t),u=b.createElement(b.Fragment,null,b.createElement("p",null,"💿 Hey developer 👋"),b.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",b.createElement("code",{style:c},"ErrorBoundary")," or"," ",b.createElement("code",{style:c},"errorElement")," prop on your route.")),b.createElement(b.Fragment,null,b.createElement("h2",null,"Unexpected Application Error!"),b.createElement("h3",{style:{fontStyle:"italic"}},n),r?b.createElement("pre",{style:i},r):null,u)}var SN=b.createElement(wN,null),O0=class extends b.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){this.props.onError?this.props.onError(t,n):console.error("React Router caught the following error during render",t)}render(){let t=this.state.error;if(this.context&&typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){const r=hN(t.digest);r&&(t=r)}let n=t!==void 0?b.createElement(ia.Provider,{value:this.props.routeContext},b.createElement(Eh.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?b.createElement(EN,{error:t},n):n}};O0.contextType=lN;var vm=new WeakMap;function EN({children:t,error:n}){let{basename:r}=b.useContext(Gn);if(typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){let s=mN(n.digest);if(s){let i=vm.get(n);if(i)throw i;let c=E0(s.location,r);if(S0&&!vm.get(n))if(c.isExternal||s.reloadDocument)window.location.href=c.absoluteURL||c.to;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(c.to,{replace:s.replace}));throw vm.set(n,u),u}return b.createElement("meta",{httpEquiv:"refresh",content:`0;url=${c.absoluteURL||c.to}`})}}return t}function _N({routeContext:t,match:n,children:r}){let s=b.useContext(Fo);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),b.createElement(ia.Provider,{value:t},r)}function CN(t,n=[],r){let s=r==null?void 0:r.state;if(t==null){if(!s)return null;if(s.errors)t=s.matches;else if(n.length===0&&!s.initialized&&s.matches.length>0)t=s.matches;else return null}let i=t,c=s==null?void 0:s.errors;if(c!=null){let y=i.findIndex(v=>v.route.id&&(c==null?void 0:c[v.route.id])!==void 0);Nt(y>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(c).join(",")}`),i=i.slice(0,Math.min(i.length,y+1))}let u=!1,f=-1;if(r&&s){u=s.renderFallback;for(let y=0;y<i.length;y++){let v=i[y];if((v.route.HydrateFallback||v.route.hydrateFallbackElement)&&(f=y),v.route.id){let{loaderData:w,errors:C}=s,S=v.route.loader&&!w.hasOwnProperty(v.route.id)&&(!C||C[v.route.id]===void 0);if(v.route.lazy||S){r.isStatic&&(u=!0),f>=0?i=i.slice(0,f+1):i=[i[0]];break}}}}let g=r==null?void 0:r.onError,p=s&&g?(y,v)=>{var w,C;g(y,{location:s.location,params:((C=(w=s.matches)==null?void 0:w[0])==null?void 0:C.params)??{},unstable_pattern:oN(s.matches),errorInfo:v})}:void 0;return i.reduceRight((y,v,w)=>{let C,S=!1,_=null,E=null;s&&(C=c&&v.route.id?c[v.route.id]:void 0,_=v.route.errorElement||SN,u&&(f<0&&w===0?(j0("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,E=null):f===w&&(S=!0,E=v.route.hydrateFallbackElement||null)));let R=n.concat(i.slice(0,w+1)),k=()=>{let A;return C?A=_:S?A=E:v.route.Component?A=b.createElement(v.route.Component,null):v.route.element?A=v.route.element:A=y,b.createElement(_N,{match:v,routeContext:{outlet:y,matches:R,isDataRoute:s!=null},children:A})};return s&&(v.route.ErrorBoundary||v.route.errorElement||w===0)?b.createElement(O0,{location:s.location,revalidation:s.revalidation,component:_,error:C,children:k(),routeContext:{outlet:null,matches:R,isDataRoute:!0},onError:p}):k()},null)}function _h(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function NN(t){let n=b.useContext(Fo);return Nt(n,_h(t)),n}function RN(t){let n=b.useContext(Au);return Nt(n,_h(t)),n}function AN(t){let n=b.useContext(ia);return Nt(n,_h(t)),n}function Ch(t){let n=AN(t),r=n.matches[n.matches.length-1];return Nt(r.route.id,`${t} can only be used on routes that contain a unique "id"`),r.route.id}function TN(){return Ch("useRouteId")}function ON(){var s;let t=b.useContext(Eh),n=RN("useRouteError"),r=Ch("useRouteError");return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function jN(){let{router:t}=NN("useNavigate"),n=Ch("useNavigate"),r=b.useRef(!1);return A0(()=>{r.current=!0}),b.useCallback(async(i,c={})=>{oa(r.current,R0),r.current&&(typeof i=="number"?await t.navigate(i):await t.navigate(i,{fromRouteId:n,...c}))},[t,n])}var Cb={};function j0(t,n,r){!n&&!Cb[t]&&(Cb[t]=!0,oa(!1,r))}b.memo(kN);function kN({routes:t,future:n,state:r,isStatic:s,onError:i}){return T0(t,void 0,{state:r,isStatic:s,onError:i})}function ym({to:t,replace:n,state:r,relative:s}){Nt($o(),"<Navigate> may be used only in the context of a <Router> component.");let{static:i}=b.useContext(Gn);oa(!i,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:c}=b.useContext(ia),{pathname:u}=Da(),f=Xr(),g=Ru(t,Sh(c),u,s==="path"),p=JSON.stringify(g);return b.useEffect(()=>{f(JSON.parse(p),{replace:n,state:r,relative:s})},[f,p,s,n,r]),null}function MN(t){return yN(t.context)}function Hn(t){Nt(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function DN({basename:t="/",children:n=null,location:r,navigationType:s="POP",navigator:i,static:c=!1,unstable_useTransitions:u}){Nt(!$o(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let f=t.replace(/^\/*/,"/"),g=b.useMemo(()=>({basename:f,navigator:i,static:c,unstable_useTransitions:u,future:{}}),[f,i,c,u]);typeof r=="string"&&(r=qo(r));let{pathname:p="/",search:y="",hash:v="",state:w=null,key:C="default",unstable_mask:S}=r,_=b.useMemo(()=>{let E=rr(p,f);return E==null?null:{location:{pathname:E,search:y,hash:v,state:w,key:C,unstable_mask:S},navigationType:s}},[f,p,y,v,w,C,s,S]);return oa(_!=null,`<Router basename="${f}"> is not able to match the URL "${p}${y}${v}" because it does not start with the basename, so the <Router> won't render anything.`),_==null?null:b.createElement(Gn.Provider,{value:g},b.createElement(il.Provider,{children:n,value:_}))}function zN({children:t,location:n}){return xN($m(t),n)}function $m(t,n=[]){let r=[];return b.Children.forEach(t,(s,i)=>{if(!b.isValidElement(s))return;let c=[...n,i];if(s.type===b.Fragment){r.push.apply(r,$m(s.props.children,c));return}Nt(s.type===Hn,`[${typeof s.type=="string"?s.type:s.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Nt(!s.props.index||!s.props.children,"An index route cannot have child routes.");let u={id:s.props.id||c.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,middleware:s.props.middleware,loader:s.props.loader,action:s.props.action,hydrateFallbackElement:s.props.hydrateFallbackElement,HydrateFallback:s.props.HydrateFallback,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.hasErrorBoundary===!0||s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(u.children=$m(s.props.children,c)),r.push(u)}),r}var Gc="get",Yc="application/x-www-form-urlencoded";function Tu(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function LN(t){return Tu(t)&&t.tagName.toLowerCase()==="button"}function UN(t){return Tu(t)&&t.tagName.toLowerCase()==="form"}function BN(t){return Tu(t)&&t.tagName.toLowerCase()==="input"}function PN(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function HN(t,n){return t.button===0&&(!n||n==="_self")&&!PN(t)}function Gm(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((n,r)=>{let s=t[r];return n.concat(Array.isArray(s)?s.map(i=>[r,i]):[[r,s]])},[]))}function VN(t,n){let r=Gm(t);return n&&n.forEach((s,i)=>{r.has(i)||n.getAll(i).forEach(c=>{r.append(i,c)})}),r}var kc=null;function IN(){if(kc===null)try{new FormData(document.createElement("form"),0),kc=!1}catch{kc=!0}return kc}var qN=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function bm(t){return t!=null&&!qN.has(t)?(oa(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Yc}"`),null):t}function FN(t,n){let r,s,i,c,u;if(UN(t)){let f=t.getAttribute("action");s=f?rr(f,n):null,r=t.getAttribute("method")||Gc,i=bm(t.getAttribute("enctype"))||Yc,c=new FormData(t)}else if(LN(t)||BN(t)&&(t.type==="submit"||t.type==="image")){let f=t.form;if(f==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let g=t.getAttribute("formaction")||f.getAttribute("action");if(s=g?rr(g,n):null,r=t.getAttribute("formmethod")||f.getAttribute("method")||Gc,i=bm(t.getAttribute("formenctype"))||bm(f.getAttribute("enctype"))||Yc,c=new FormData(f,t),!IN()){let{name:p,type:y,value:v}=t;if(y==="image"){let w=p?`${p}.`:"";c.append(`${w}x`,"0"),c.append(`${w}y`,"0")}else p&&c.append(p,v)}}else{if(Tu(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');r=Gc,s=null,i=Yc,u=t}return c&&i==="text/plain"&&(u=c,c=void 0),{action:s,method:r.toLowerCase(),encType:i,formData:c,body:u}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Nh(t,n){if(t===!1||t===null||typeof t>"u")throw new Error(n)}function $N(t,n,r,s){let i=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return r?i.pathname.endsWith("/")?i.pathname=`${i.pathname}_.${s}`:i.pathname=`${i.pathname}.${s}`:i.pathname==="/"?i.pathname=`_root.${s}`:n&&rr(i.pathname,n)==="/"?i.pathname=`${n.replace(/\/$/,"")}/_root.${s}`:i.pathname=`${i.pathname.replace(/\/$/,"")}.${s}`,i}async function GN(t,n){if(t.id in n)return n[t.id];try{let r=await import(t.module);return n[t.id]=r,r}catch(r){return console.error(`Error loading route module \`${t.module}\`, reloading page...`),console.error(r),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function YN(t){return t==null?!1:t.href==null?t.rel==="preload"&&typeof t.imageSrcSet=="string"&&typeof t.imageSizes=="string":typeof t.rel=="string"&&typeof t.href=="string"}async function ZN(t,n,r){let s=await Promise.all(t.map(async i=>{let c=n.routes[i.route.id];if(c){let u=await GN(c,r);return u.links?u.links():[]}return[]}));return WN(s.flat(1).filter(YN).filter(i=>i.rel==="stylesheet"||i.rel==="preload").map(i=>i.rel==="stylesheet"?{...i,rel:"prefetch",as:"style"}:{...i,rel:"prefetch"}))}function Nb(t,n,r,s,i,c){let u=(g,p)=>r[p]?g.route.id!==r[p].route.id:!0,f=(g,p)=>{var y;return r[p].pathname!==g.pathname||((y=r[p].route.path)==null?void 0:y.endsWith("*"))&&r[p].params["*"]!==g.params["*"]};return c==="assets"?n.filter((g,p)=>u(g,p)||f(g,p)):c==="data"?n.filter((g,p)=>{var v;let y=s.routes[g.route.id];if(!y||!y.hasLoader)return!1;if(u(g,p)||f(g,p))return!0;if(g.route.shouldRevalidate){let w=g.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:((v=r[0])==null?void 0:v.params)||{},nextUrl:new URL(t,window.origin),nextParams:g.params,defaultShouldRevalidate:!0});if(typeof w=="boolean")return w}return!0}):[]}function XN(t,n,{includeHydrateFallback:r}={}){return KN(t.map(s=>{let i=n.routes[s.route.id];if(!i)return[];let c=[i.module];return i.clientActionModule&&(c=c.concat(i.clientActionModule)),i.clientLoaderModule&&(c=c.concat(i.clientLoaderModule)),r&&i.hydrateFallbackModule&&(c=c.concat(i.hydrateFallbackModule)),i.imports&&(c=c.concat(i.imports)),c}).flat(1))}function KN(t){return[...new Set(t)]}function QN(t){let n={},r=Object.keys(t).sort();for(let s of r)n[s]=t[s];return n}function WN(t,n){let r=new Set;return new Set(n),t.reduce((s,i)=>{let c=JSON.stringify(QN(i));return r.has(c)||(r.add(c),s.push({key:c,link:i})),s},[])}function k0(){let t=b.useContext(Fo);return Nh(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function JN(){let t=b.useContext(Au);return Nh(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var Rh=b.createContext(void 0);Rh.displayName="FrameworkContext";function M0(){let t=b.useContext(Rh);return Nh(t,"You must render this element inside a <HydratedRouter> element"),t}function e2(t,n){let r=b.useContext(Rh),[s,i]=b.useState(!1),[c,u]=b.useState(!1),{onFocus:f,onBlur:g,onMouseEnter:p,onMouseLeave:y,onTouchStart:v}=n,w=b.useRef(null);b.useEffect(()=>{if(t==="render"&&u(!0),t==="viewport"){let _=R=>{R.forEach(k=>{u(k.isIntersecting)})},E=new IntersectionObserver(_,{threshold:.5});return w.current&&E.observe(w.current),()=>{E.disconnect()}}},[t]),b.useEffect(()=>{if(s){let _=setTimeout(()=>{u(!0)},100);return()=>{clearTimeout(_)}}},[s]);let C=()=>{i(!0)},S=()=>{i(!1),u(!1)};return r?t!=="intent"?[c,w,{}]:[c,w,{onFocus:Ii(f,C),onBlur:Ii(g,S),onMouseEnter:Ii(p,C),onMouseLeave:Ii(y,S),onTouchStart:Ii(v,C)}]:[!1,w,{}]}function Ii(t,n){return r=>{t&&t(r),r.defaultPrevented||n(r)}}function t2({page:t,...n}){let{router:r}=k0(),s=b.useMemo(()=>b0(r.routes,t,r.basename),[r.routes,t,r.basename]);return s?b.createElement(a2,{page:t,matches:s,...n}):null}function n2(t){let{manifest:n,routeModules:r}=M0(),[s,i]=b.useState([]);return b.useEffect(()=>{let c=!1;return ZN(t,n,r).then(u=>{c||i(u)}),()=>{c=!0}},[t,n,r]),s}function a2({page:t,matches:n,...r}){let s=Da(),{future:i,manifest:c,routeModules:u}=M0(),{basename:f}=k0(),{loaderData:g,matches:p}=JN(),y=b.useMemo(()=>Nb(t,n,p,c,s,"data"),[t,n,p,c,s]),v=b.useMemo(()=>Nb(t,n,p,c,s,"assets"),[t,n,p,c,s]),w=b.useMemo(()=>{if(t===s.pathname+s.search+s.hash)return[];let _=new Set,E=!1;if(n.forEach(k=>{var D;let A=c.routes[k.route.id];!A||!A.hasLoader||(!y.some(H=>H.route.id===k.route.id)&&k.route.id in g&&((D=u[k.route.id])!=null&&D.shouldRevalidate)||A.hasClientLoader?E=!0:_.add(k.route.id))}),_.size===0)return[];let R=$N(t,f,i.unstable_trailingSlashAwareDataRequests,"data");return E&&_.size>0&&R.searchParams.set("_routes",n.filter(k=>_.has(k.route.id)).map(k=>k.route.id).join(",")),[R.pathname+R.search]},[f,i.unstable_trailingSlashAwareDataRequests,g,s,c,y,n,t,u]),C=b.useMemo(()=>XN(v,c),[v,c]),S=n2(v);return b.createElement(b.Fragment,null,w.map(_=>b.createElement("link",{key:_,rel:"prefetch",as:"fetch",href:_,...r})),C.map(_=>b.createElement("link",{key:_,rel:"modulepreload",href:_,...r})),S.map(({key:_,link:E})=>b.createElement("link",{key:_,nonce:r.nonce,...E,crossOrigin:E.crossOrigin??r.crossOrigin})))}function r2(...t){return n=>{t.forEach(r=>{typeof r=="function"?r(n):r!=null&&(r.current=n)})}}var s2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{s2&&(window.__reactRouterVersion="7.13.2")}catch{}function o2({basename:t,children:n,unstable_useTransitions:r,window:s}){let i=b.useRef();i.current==null&&(i.current=zC({window:s,v5Compat:!0}));let c=i.current,[u,f]=b.useState({action:c.action,location:c.location}),g=b.useCallback(p=>{r===!1?f(p):b.startTransition(()=>f(p))},[r]);return b.useLayoutEffect(()=>c.listen(g),[c,g]),b.createElement(DN,{basename:t,children:n,location:u.location,navigationType:u.action,navigator:c,unstable_useTransitions:r})}var D0=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,z0=b.forwardRef(function({onClick:n,discover:r="render",prefetch:s="none",relative:i,reloadDocument:c,replace:u,unstable_mask:f,state:g,target:p,to:y,preventScrollReset:v,viewTransition:w,unstable_defaultShouldRevalidate:C,...S},_){let{basename:E,navigator:R,unstable_useTransitions:k}=b.useContext(Gn),A=typeof y=="string"&&D0.test(y),D=E0(y,E);y=D.to;let H=pN(y,{relative:i}),$=Da(),U=null;if(f){let ve=Ru(f,[],$.unstable_mask?$.unstable_mask.pathname:"/",!0);E!=="/"&&(ve.pathname=ve.pathname==="/"?E:ja([E,ve.pathname])),U=R.createHref(ve)}let[F,de,fe]=e2(s,S),me=c2(y,{replace:u,unstable_mask:f,state:g,target:p,preventScrollReset:v,relative:i,viewTransition:w,unstable_defaultShouldRevalidate:C,unstable_useTransitions:k});function se(ve){n&&n(ve),ve.defaultPrevented||me(ve)}let G=!(D.isExternal||c),he=b.createElement("a",{...S,...fe,href:(G?U:void 0)||D.absoluteURL||H,onClick:G?se:n,ref:r2(_,de),target:p,"data-discover":!A&&r==="render"?"true":void 0});return F&&!A?b.createElement(b.Fragment,null,he,b.createElement(t2,{page:H})):he});z0.displayName="Link";var L0=b.forwardRef(function({"aria-current":n="page",caseSensitive:r=!1,className:s="",end:i=!1,style:c,to:u,viewTransition:f,children:g,...p},y){let v=ll(u,{relative:p.relative}),w=Da(),C=b.useContext(Au),{navigator:S,basename:_}=b.useContext(Gn),E=C!=null&&p2(v)&&f===!0,R=S.encodeLocation?S.encodeLocation(v).pathname:v.pathname,k=w.pathname,A=C&&C.navigation&&C.navigation.location?C.navigation.location.pathname:null;r||(k=k.toLowerCase(),A=A?A.toLowerCase():null,R=R.toLowerCase()),A&&_&&(A=rr(A,_)||A);const D=R!=="/"&&R.endsWith("/")?R.length-1:R.length;let H=k===R||!i&&k.startsWith(R)&&k.charAt(D)==="/",$=A!=null&&(A===R||!i&&A.startsWith(R)&&A.charAt(R.length)==="/"),U={isActive:H,isPending:$,isTransitioning:E},F=H?n:void 0,de;typeof s=="function"?de=s(U):de=[s,H?"active":null,$?"pending":null,E?"transitioning":null].filter(Boolean).join(" ");let fe=typeof c=="function"?c(U):c;return b.createElement(z0,{...p,"aria-current":F,className:de,ref:y,style:fe,to:u,viewTransition:f},typeof g=="function"?g(U):g)});L0.displayName="NavLink";var i2=b.forwardRef(({discover:t="render",fetcherKey:n,navigate:r,reloadDocument:s,replace:i,state:c,method:u=Gc,action:f,onSubmit:g,relative:p,preventScrollReset:y,viewTransition:v,unstable_defaultShouldRevalidate:w,...C},S)=>{let{unstable_useTransitions:_}=b.useContext(Gn),E=m2(),R=h2(f,{relative:p}),k=u.toLowerCase()==="get"?"get":"post",A=typeof f=="string"&&D0.test(f),D=H=>{if(g&&g(H),H.defaultPrevented)return;H.preventDefault();let $=H.nativeEvent.submitter,U=($==null?void 0:$.getAttribute("formmethod"))||u,F=()=>E($||H.currentTarget,{fetcherKey:n,method:U,navigate:r,replace:i,state:c,relative:p,preventScrollReset:y,viewTransition:v,unstable_defaultShouldRevalidate:w});_&&r!==!1?b.startTransition(()=>F()):F()};return b.createElement("form",{ref:S,method:k,action:R,onSubmit:s?g:D,...C,"data-discover":!A&&t==="render"?"true":void 0})});i2.displayName="Form";function l2(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function U0(t){let n=b.useContext(Fo);return Nt(n,l2(t)),n}function c2(t,{target:n,replace:r,unstable_mask:s,state:i,preventScrollReset:c,relative:u,viewTransition:f,unstable_defaultShouldRevalidate:g,unstable_useTransitions:p}={}){let y=Xr(),v=Da(),w=ll(t,{relative:u});return b.useCallback(C=>{if(HN(C,n)){C.preventDefault();let S=r!==void 0?r:Ji(v)===Ji(w),_=()=>y(t,{replace:S,unstable_mask:s,state:i,preventScrollReset:c,relative:u,viewTransition:f,unstable_defaultShouldRevalidate:g});p?b.startTransition(()=>_()):_()}},[v,y,w,r,s,i,n,t,c,u,f,g,p])}function u2(t){oa(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let n=b.useRef(Gm(t)),r=b.useRef(!1),s=Da(),i=b.useMemo(()=>VN(s.search,r.current?null:n.current),[s.search]),c=Xr(),u=b.useCallback((f,g)=>{const p=Gm(typeof f=="function"?f(new URLSearchParams(i)):f);r.current=!0,c("?"+p,g)},[c,i]);return[i,u]}var d2=0,f2=()=>`__${String(++d2)}__`;function m2(){let{router:t}=U0("useSubmit"),{basename:n}=b.useContext(Gn),r=TN(),s=t.fetch,i=t.navigate;return b.useCallback(async(c,u={})=>{let{action:f,method:g,encType:p,formData:y,body:v}=FN(c,n);if(u.navigate===!1){let w=u.fetcherKey||f2();await s(w,r,u.action||f,{unstable_defaultShouldRevalidate:u.unstable_defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:y,body:v,formMethod:u.method||g,formEncType:u.encType||p,flushSync:u.flushSync})}else await i(u.action||f,{unstable_defaultShouldRevalidate:u.unstable_defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:y,body:v,formMethod:u.method||g,formEncType:u.encType||p,replace:u.replace,state:u.state,fromRouteId:r,flushSync:u.flushSync,viewTransition:u.viewTransition})},[s,i,n,r])}function h2(t,{relative:n}={}){let{basename:r}=b.useContext(Gn),s=b.useContext(ia);Nt(s,"useFormAction must be used inside a RouteContext");let[i]=s.matches.slice(-1),c={...ll(t||".",{relative:n})},u=Da();if(t==null){c.search=u.search;let f=new URLSearchParams(c.search),g=f.getAll("index");if(g.some(y=>y==="")){f.delete("index"),g.filter(v=>v).forEach(v=>f.append("index",v));let y=f.toString();c.search=y?`?${y}`:""}}return(!t||t===".")&&i.route.index&&(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),r!=="/"&&(c.pathname=c.pathname==="/"?r:ja([r,c.pathname])),Ji(c)}function p2(t,{relative:n}={}){let r=b.useContext(C0);Nt(r!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:s}=U0("useViewTransitionState"),i=ll(t,{relative:n});if(!r.isTransitioning)return!1;let c=rr(r.currentLocation.pathname,s)||r.currentLocation.pathname,u=rr(r.nextLocation.pathname,s)||r.nextLocation.pathname;return eu(i.pathname,u)!=null||eu(i.pathname,c)!=null}var Ah=y0();const B0=v0(Ah);function g2(t){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}const v2=t=>{switch(t){case"success":return x2;case"info":return S2;case"warning":return w2;case"error":return E2;default:return null}},y2=Array(12).fill(0),b2=({visible:t,className:n})=>ae.createElement("div",{className:["sonner-loading-wrapper",n].filter(Boolean).join(" "),"data-visible":t},ae.createElement("div",{className:"sonner-spinner"},y2.map((r,s)=>ae.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),x2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),w2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),S2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),E2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ae.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),_2=ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ae.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ae.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),C2=()=>{const[t,n]=ae.useState(document.hidden);return ae.useEffect(()=>{const r=()=>{n(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t};let Ym=1;class N2{constructor(){this.subscribe=n=>(this.subscribers.push(n),()=>{const r=this.subscribers.indexOf(n);this.subscribers.splice(r,1)}),this.publish=n=>{this.subscribers.forEach(r=>r(n))},this.addToast=n=>{this.publish(n),this.toasts=[...this.toasts,n]},this.create=n=>{var r;const{message:s,...i}=n,c=typeof(n==null?void 0:n.id)=="number"||((r=n.id)==null?void 0:r.length)>0?n.id:Ym++,u=this.toasts.find(g=>g.id===c),f=n.dismissible===void 0?!0:n.dismissible;return this.dismissedToasts.has(c)&&this.dismissedToasts.delete(c),u?this.toasts=this.toasts.map(g=>g.id===c?(this.publish({...g,...n,id:c,title:s}),{...g,...n,id:c,dismissible:f,title:s}):g):this.addToast({title:s,...i,dismissible:f,id:c}),c},this.dismiss=n=>(n?(this.dismissedToasts.add(n),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:n,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(s=>s({id:r.id,dismiss:!0}))}),n),this.message=(n,r)=>this.create({...r,message:n}),this.error=(n,r)=>this.create({...r,message:n,type:"error"}),this.success=(n,r)=>this.create({...r,type:"success",message:n}),this.info=(n,r)=>this.create({...r,type:"info",message:n}),this.warning=(n,r)=>this.create({...r,type:"warning",message:n}),this.loading=(n,r)=>this.create({...r,type:"loading",message:n}),this.promise=(n,r)=>{if(!r)return;let s;r.loading!==void 0&&(s=this.create({...r,promise:n,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const i=Promise.resolve(n instanceof Function?n():n);let c=s!==void 0,u;const f=i.then(async p=>{if(u=["resolve",p],ae.isValidElement(p))c=!1,this.create({id:s,type:"default",message:p});else if(A2(p)&&!p.ok){c=!1;const v=typeof r.error=="function"?await r.error(`HTTP error! status: ${p.status}`):r.error,w=typeof r.description=="function"?await r.description(`HTTP error! status: ${p.status}`):r.description,S=typeof v=="object"&&!ae.isValidElement(v)?v:{message:v};this.create({id:s,type:"error",description:w,...S})}else if(p instanceof Error){c=!1;const v=typeof r.error=="function"?await r.error(p):r.error,w=typeof r.description=="function"?await r.description(p):r.description,S=typeof v=="object"&&!ae.isValidElement(v)?v:{message:v};this.create({id:s,type:"error",description:w,...S})}else if(r.success!==void 0){c=!1;const v=typeof r.success=="function"?await r.success(p):r.success,w=typeof r.description=="function"?await r.description(p):r.description,S=typeof v=="object"&&!ae.isValidElement(v)?v:{message:v};this.create({id:s,type:"success",description:w,...S})}}).catch(async p=>{if(u=["reject",p],r.error!==void 0){c=!1;const y=typeof r.error=="function"?await r.error(p):r.error,v=typeof r.description=="function"?await r.description(p):r.description,C=typeof y=="object"&&!ae.isValidElement(y)?y:{message:y};this.create({id:s,type:"error",description:v,...C})}}).finally(()=>{c&&(this.dismiss(s),s=void 0),r.finally==null||r.finally.call(r)}),g=()=>new Promise((p,y)=>f.then(()=>u[0]==="reject"?y(u[1]):p(u[1])).catch(y));return typeof s!="string"&&typeof s!="number"?{unwrap:g}:Object.assign(s,{unwrap:g})},this.custom=(n,r)=>{const s=(r==null?void 0:r.id)||Ym++;return this.create({jsx:n(s),id:s,...r}),s},this.getActiveToasts=()=>this.toasts.filter(n=>!this.dismissedToasts.has(n.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Tn=new N2,R2=(t,n)=>{const r=(n==null?void 0:n.id)||Ym++;return Tn.addToast({title:t,...n,id:r}),r},A2=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",T2=R2,O2=()=>Tn.toasts,j2=()=>Tn.getActiveToasts(),Ze=Object.assign(T2,{success:Tn.success,info:Tn.info,warning:Tn.warning,error:Tn.error,custom:Tn.custom,message:Tn.message,promise:Tn.promise,dismiss:Tn.dismiss,loading:Tn.loading},{getHistory:O2,getToasts:j2});g2("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Mc(t){return t.label!==void 0}const k2=3,M2="24px",D2="16px",Rb=4e3,z2=356,L2=14,U2=45,B2=200;function Ca(...t){return t.filter(Boolean).join(" ")}function P2(t){const[n,r]=t.split("-"),s=[];return n&&s.push(n),r&&s.push(r),s}const H2=t=>{var n,r,s,i,c,u,f,g,p;const{invert:y,toast:v,unstyled:w,interacting:C,setHeights:S,visibleToasts:_,heights:E,index:R,toasts:k,expanded:A,removeToast:D,defaultRichColors:H,closeButton:$,style:U,cancelButtonStyle:F,actionButtonStyle:de,className:fe="",descriptionClassName:me="",duration:se,position:G,gap:he,expandByDefault:ve,classNames:T,icons:K,closeButtonAriaLabel:te="Close toast"}=t,[le,ne]=ae.useState(null),[j,X]=ae.useState(null),[L,Y]=ae.useState(!1),[J,ie]=ae.useState(!1),[pe,Q]=ae.useState(!1),[oe,Re]=ae.useState(!1),[et,Me]=ae.useState(!1),[ze,be]=ae.useState(0),[je,at]=ae.useState(0),ht=ae.useRef(v.duration||se||Rb),Qe=ae.useRef(null),Pe=ae.useRef(null),Tt=R===0,Zt=R+1<=_,O=v.type,B=v.dismissible!==!1,V=v.className||"",we=v.descriptionClassName||"",ge=ae.useMemo(()=>E.findIndex(He=>He.toastId===v.id)||0,[E,v.id]),ye=ae.useMemo(()=>{var He;return(He=v.closeButton)!=null?He:$},[v.closeButton,$]),Se=ae.useMemo(()=>v.duration||se||Rb,[v.duration,se]),Ue=ae.useRef(0),Ge=ae.useRef(0),Pt=ae.useRef(0),Mt=ae.useRef(null),[mt,Dt]=G.split("-"),an=ae.useMemo(()=>E.reduce((He,_t,en)=>en>=ge?He:He+_t.height,0),[E,ge]),Ht=C2(),Ko=v.invert||y,ur=O==="loading";Ge.current=ae.useMemo(()=>ge*he+an,[ge,an]),ae.useEffect(()=>{ht.current=Se},[Se]),ae.useEffect(()=>{Y(!0)},[]),ae.useEffect(()=>{const He=Pe.current;if(He){const _t=He.getBoundingClientRect().height;return at(_t),S(en=>[{toastId:v.id,height:_t,position:v.position},...en]),()=>S(en=>en.filter(dn=>dn.toastId!==v.id))}},[S,v.id]),ae.useLayoutEffect(()=>{if(!L)return;const He=Pe.current,_t=He.style.height;He.style.height="auto";const en=He.getBoundingClientRect().height;He.style.height=_t,at(en),S(dn=>dn.find(Rt=>Rt.toastId===v.id)?dn.map(Rt=>Rt.toastId===v.id?{...Rt,height:en}:Rt):[{toastId:v.id,height:en,position:v.position},...dn])},[L,v.title,v.description,S,v.id,v.jsx,v.action,v.cancel]);const Yn=ae.useCallback(()=>{ie(!0),be(Ge.current),S(He=>He.filter(_t=>_t.toastId!==v.id)),setTimeout(()=>{D(v)},B2)},[v,D,S,Ge]);ae.useEffect(()=>{if(v.promise&&O==="loading"||v.duration===1/0||v.type==="loading")return;let He;return A||C||Ht?(()=>{if(Pt.current<Ue.current){const dn=new Date().getTime()-Ue.current;ht.current=ht.current-dn}Pt.current=new Date().getTime()})():(()=>{ht.current!==1/0&&(Ue.current=new Date().getTime(),He=setTimeout(()=>{v.onAutoClose==null||v.onAutoClose.call(v,v),Yn()},ht.current))})(),()=>clearTimeout(He)},[A,C,v,O,Ht,Yn]),ae.useEffect(()=>{v.delete&&(Yn(),v.onDismiss==null||v.onDismiss.call(v,v))},[Yn,v.delete]);function Ua(){var He;if(K!=null&&K.loading){var _t;return ae.createElement("div",{className:Ca(T==null?void 0:T.loader,v==null||(_t=v.classNames)==null?void 0:_t.loader,"sonner-loader"),"data-visible":O==="loading"},K.loading)}return ae.createElement(b2,{className:Ca(T==null?void 0:T.loader,v==null||(He=v.classNames)==null?void 0:He.loader),visible:O==="loading"})}const ks=v.icon||(K==null?void 0:K[O])||v2(O);var Wr,xa;return ae.createElement("li",{tabIndex:0,ref:Pe,className:Ca(fe,V,T==null?void 0:T.toast,v==null||(n=v.classNames)==null?void 0:n.toast,T==null?void 0:T.default,T==null?void 0:T[O],v==null||(r=v.classNames)==null?void 0:r[O]),"data-sonner-toast":"","data-rich-colors":(Wr=v.richColors)!=null?Wr:H,"data-styled":!(v.jsx||v.unstyled||w),"data-mounted":L,"data-promise":!!v.promise,"data-swiped":et,"data-removed":J,"data-visible":Zt,"data-y-position":mt,"data-x-position":Dt,"data-index":R,"data-front":Tt,"data-swiping":pe,"data-dismissible":B,"data-type":O,"data-invert":Ko,"data-swipe-out":oe,"data-swipe-direction":j,"data-expanded":!!(A||ve&&L),"data-testid":v.testId,style:{"--index":R,"--toasts-before":R,"--z-index":k.length-R,"--offset":`${J?ze:Ge.current}px`,"--initial-height":ve?"auto":`${je}px`,...U,...v.style},onDragEnd:()=>{Q(!1),ne(null),Mt.current=null},onPointerDown:He=>{He.button!==2&&(ur||!B||(Qe.current=new Date,be(Ge.current),He.target.setPointerCapture(He.pointerId),He.target.tagName!=="BUTTON"&&(Q(!0),Mt.current={x:He.clientX,y:He.clientY})))},onPointerUp:()=>{var He,_t,en;if(oe||!B)return;Mt.current=null;const dn=Number(((He=Pe.current)==null?void 0:He.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),dr=Number(((_t=Pe.current)==null?void 0:_t.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Rt=new Date().getTime()-((en=Qe.current)==null?void 0:en.getTime()),bn=le==="x"?dn:dr,Jr=Math.abs(bn)/Rt;if(Math.abs(bn)>=U2||Jr>.11){be(Ge.current),v.onDismiss==null||v.onDismiss.call(v,v),X(le==="x"?dn>0?"right":"left":dr>0?"down":"up"),Yn(),Re(!0);return}else{var xn,wn;(xn=Pe.current)==null||xn.style.setProperty("--swipe-amount-x","0px"),(wn=Pe.current)==null||wn.style.setProperty("--swipe-amount-y","0px")}Me(!1),Q(!1),ne(null)},onPointerMove:He=>{var _t,en,dn;if(!Mt.current||!B||((_t=window.getSelection())==null?void 0:_t.toString().length)>0)return;const Rt=He.clientY-Mt.current.y,bn=He.clientX-Mt.current.x;var Jr;const xn=(Jr=t.swipeDirections)!=null?Jr:P2(G);!le&&(Math.abs(bn)>1||Math.abs(Rt)>1)&&ne(Math.abs(bn)>Math.abs(Rt)?"x":"y");let wn={x:0,y:0};const Ms=ca=>1/(1.5+Math.abs(ca)/20);if(le==="y"){if(xn.includes("top")||xn.includes("bottom"))if(xn.includes("top")&&Rt<0||xn.includes("bottom")&&Rt>0)wn.y=Rt;else{const ca=Rt*Ms(Rt);wn.y=Math.abs(ca)<Math.abs(Rt)?ca:Rt}}else if(le==="x"&&(xn.includes("left")||xn.includes("right")))if(xn.includes("left")&&bn<0||xn.includes("right")&&bn>0)wn.x=bn;else{const ca=bn*Ms(bn);wn.x=Math.abs(ca)<Math.abs(bn)?ca:bn}(Math.abs(wn.x)>0||Math.abs(wn.y)>0)&&Me(!0),(en=Pe.current)==null||en.style.setProperty("--swipe-amount-x",`${wn.x}px`),(dn=Pe.current)==null||dn.style.setProperty("--swipe-amount-y",`${wn.y}px`)}},ye&&!v.jsx&&O!=="loading"?ae.createElement("button",{"aria-label":te,"data-disabled":ur,"data-close-button":!0,onClick:ur||!B?()=>{}:()=>{Yn(),v.onDismiss==null||v.onDismiss.call(v,v)},className:Ca(T==null?void 0:T.closeButton,v==null||(s=v.classNames)==null?void 0:s.closeButton)},(xa=K==null?void 0:K.close)!=null?xa:_2):null,(O||v.icon||v.promise)&&v.icon!==null&&((K==null?void 0:K[O])!==null||v.icon)?ae.createElement("div",{"data-icon":"",className:Ca(T==null?void 0:T.icon,v==null||(i=v.classNames)==null?void 0:i.icon)},v.promise||v.type==="loading"&&!v.icon?v.icon||Ua():null,v.type!=="loading"?ks:null):null,ae.createElement("div",{"data-content":"",className:Ca(T==null?void 0:T.content,v==null||(c=v.classNames)==null?void 0:c.content)},ae.createElement("div",{"data-title":"",className:Ca(T==null?void 0:T.title,v==null||(u=v.classNames)==null?void 0:u.title)},v.jsx?v.jsx:typeof v.title=="function"?v.title():v.title),v.description?ae.createElement("div",{"data-description":"",className:Ca(me,we,T==null?void 0:T.description,v==null||(f=v.classNames)==null?void 0:f.description)},typeof v.description=="function"?v.description():v.description):null),ae.isValidElement(v.cancel)?v.cancel:v.cancel&&Mc(v.cancel)?ae.createElement("button",{"data-button":!0,"data-cancel":!0,style:v.cancelButtonStyle||F,onClick:He=>{Mc(v.cancel)&&B&&(v.cancel.onClick==null||v.cancel.onClick.call(v.cancel,He),Yn())},className:Ca(T==null?void 0:T.cancelButton,v==null||(g=v.classNames)==null?void 0:g.cancelButton)},v.cancel.label):null,ae.isValidElement(v.action)?v.action:v.action&&Mc(v.action)?ae.createElement("button",{"data-button":!0,"data-action":!0,style:v.actionButtonStyle||de,onClick:He=>{Mc(v.action)&&(v.action.onClick==null||v.action.onClick.call(v.action,He),!He.defaultPrevented&&Yn())},className:Ca(T==null?void 0:T.actionButton,v==null||(p=v.classNames)==null?void 0:p.actionButton)},v.action.label):null)};function Ab(){if(typeof window>"u"||typeof document>"u")return"ltr";const t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function V2(t,n){const r={};return[t,n].forEach((s,i)=>{const c=i===1,u=c?"--mobile-offset":"--offset",f=c?D2:M2;function g(p){["top","right","bottom","left"].forEach(y=>{r[`${u}-${y}`]=typeof p=="number"?`${p}px`:p})}typeof s=="number"||typeof s=="string"?g(s):typeof s=="object"?["top","right","bottom","left"].forEach(p=>{s[p]===void 0?r[`${u}-${p}`]=f:r[`${u}-${p}`]=typeof s[p]=="number"?`${s[p]}px`:s[p]}):g(f)}),r}const I2=ae.forwardRef(function(n,r){const{id:s,invert:i,position:c="bottom-right",hotkey:u=["altKey","KeyT"],expand:f,closeButton:g,className:p,offset:y,mobileOffset:v,theme:w="light",richColors:C,duration:S,style:_,visibleToasts:E=k2,toastOptions:R,dir:k=Ab(),gap:A=L2,icons:D,containerAriaLabel:H="Notifications"}=n,[$,U]=ae.useState([]),F=ae.useMemo(()=>s?$.filter(L=>L.toasterId===s):$.filter(L=>!L.toasterId),[$,s]),de=ae.useMemo(()=>Array.from(new Set([c].concat(F.filter(L=>L.position).map(L=>L.position)))),[F,c]),[fe,me]=ae.useState([]),[se,G]=ae.useState(!1),[he,ve]=ae.useState(!1),[T,K]=ae.useState(w!=="system"?w:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),te=ae.useRef(null),le=u.join("+").replace(/Key/g,"").replace(/Digit/g,""),ne=ae.useRef(null),j=ae.useRef(!1),X=ae.useCallback(L=>{U(Y=>{var J;return(J=Y.find(ie=>ie.id===L.id))!=null&&J.delete||Tn.dismiss(L.id),Y.filter(({id:ie})=>ie!==L.id)})},[]);return ae.useEffect(()=>Tn.subscribe(L=>{if(L.dismiss){requestAnimationFrame(()=>{U(Y=>Y.map(J=>J.id===L.id?{...J,delete:!0}:J))});return}setTimeout(()=>{B0.flushSync(()=>{U(Y=>{const J=Y.findIndex(ie=>ie.id===L.id);return J!==-1?[...Y.slice(0,J),{...Y[J],...L},...Y.slice(J+1)]:[L,...Y]})})})}),[$]),ae.useEffect(()=>{if(w!=="system"){K(w);return}if(w==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?K("dark"):K("light")),typeof window>"u")return;const L=window.matchMedia("(prefers-color-scheme: dark)");try{L.addEventListener("change",({matches:Y})=>{K(Y?"dark":"light")})}catch{L.addListener(({matches:J})=>{try{K(J?"dark":"light")}catch(ie){console.error(ie)}})}},[w]),ae.useEffect(()=>{$.length<=1&&G(!1)},[$]),ae.useEffect(()=>{const L=Y=>{var J;if(u.every(Q=>Y[Q]||Y.code===Q)){var pe;G(!0),(pe=te.current)==null||pe.focus()}Y.code==="Escape"&&(document.activeElement===te.current||(J=te.current)!=null&&J.contains(document.activeElement))&&G(!1)};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[u]),ae.useEffect(()=>{if(te.current)return()=>{ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null,j.current=!1)}},[te.current]),ae.createElement("section",{ref:r,"aria-label":`${H} ${le}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},de.map((L,Y)=>{var J;const[ie,pe]=L.split("-");return F.length?ae.createElement("ol",{key:L,dir:k==="auto"?Ab():k,tabIndex:-1,ref:te,className:p,"data-sonner-toaster":!0,"data-sonner-theme":T,"data-y-position":ie,"data-x-position":pe,style:{"--front-toast-height":`${((J=fe[0])==null?void 0:J.height)||0}px`,"--width":`${z2}px`,"--gap":`${A}px`,..._,...V2(y,v)},onBlur:Q=>{j.current&&!Q.currentTarget.contains(Q.relatedTarget)&&(j.current=!1,ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null))},onFocus:Q=>{Q.target instanceof HTMLElement&&Q.target.dataset.dismissible==="false"||j.current||(j.current=!0,ne.current=Q.relatedTarget)},onMouseEnter:()=>G(!0),onMouseMove:()=>G(!0),onMouseLeave:()=>{he||G(!1)},onDragEnd:()=>G(!1),onPointerDown:Q=>{Q.target instanceof HTMLElement&&Q.target.dataset.dismissible==="false"||ve(!0)},onPointerUp:()=>ve(!1)},F.filter(Q=>!Q.position&&Y===0||Q.position===L).map((Q,oe)=>{var Re,et;return ae.createElement(H2,{key:Q.id,icons:D,index:oe,toast:Q,defaultRichColors:C,duration:(Re=R==null?void 0:R.duration)!=null?Re:S,className:R==null?void 0:R.className,descriptionClassName:R==null?void 0:R.descriptionClassName,invert:i,visibleToasts:E,closeButton:(et=R==null?void 0:R.closeButton)!=null?et:g,interacting:he,position:L,style:R==null?void 0:R.style,unstyled:R==null?void 0:R.unstyled,classNames:R==null?void 0:R.classNames,cancelButtonStyle:R==null?void 0:R.cancelButtonStyle,actionButtonStyle:R==null?void 0:R.actionButtonStyle,closeButtonAriaLabel:R==null?void 0:R.closeButtonAriaLabel,removeToast:X,toasts:F.filter(Me=>Me.position==Q.position),heights:fe.filter(Me=>Me.position==Q.position),setHeights:me,expandByDefault:f,gap:A,expanded:se,swipeDirections:n.swipeDirections})})):null}))});/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const q2=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),F2=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),Tb=t=>{const n=F2(t);return n.charAt(0).toUpperCase()+n.slice(1)},P0=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),$2=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */var G2={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.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Y2=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...G2,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:P0("lucide",i),...!c&&!$2(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,y])=>b.createElement(p,y)),...Array.isArray(c)?c:[c]]));/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const st=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(Y2,{ref:c,iconNode:n,className:P0(`lucide-${q2(Tb(t))}`,`lucide-${t}`,s),...i}));return r.displayName=Tb(t),r};/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Z2=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ob=st("arrow-left",Z2);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const X2=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],K2=st("arrow-right",X2);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const Q2=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Zm=st("chevron-down",Q2);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const W2=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],jb=st("chevron-right",W2);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const J2=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],eR=st("chevron-up",J2);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const tR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],nR=st("circle-alert",tR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const aR=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],rR=st("circle-check-big",aR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const sR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],kb=st("circle-check",sR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const oR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],iR=st("circle-x",oR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const lR=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],cR=st("ellipsis-vertical",lR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const uR=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],dR=st("eye-off",uR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const fR=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],mR=st("eye",fR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const hR=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],pR=st("funnel",hR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const gR=[["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"}]],vR=st("globe",gR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const yR=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],bR=st("layers",yR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const xR=[["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"}]],wR=st("layout-dashboard",xR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const SR=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],H0=st("loader-circle",SR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const ER=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],_R=st("log-out",ER);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const CR=[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]],NR=st("message-square",CR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const RR=[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]],AR=st("moon",RR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const TR=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Xm=st("plus",TR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const OR=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],jR=st("power-off",OR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const kR=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],V0=st("power",kR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const MR=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],Mb=st("qr-code",MR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const DR=[["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"}]],Db=st("refresh-cw",DR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const zR=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],zb=st("save",zR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const LR=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],UR=st("search",LR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const BR=[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],PR=st("settings",BR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const HR=[["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"}]],VR=st("shield",HR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const IR=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],qR=st("smartphone",IR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const FR=[["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"}]],$R=st("sun",FR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const GR=[["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"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]],Th=st("trash-2",GR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const YR=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],ZR=st("triangle-alert",YR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const XR=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],el=st("x",XR);/**+ * @license lucide-react v0.525.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const KR=[["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"}]],QR=st("zap",KR);class WR extends b.Component{constructor(r){super(r);cb(this,"handleReset",()=>{this.setState({hasError:!1,error:null,errorInfo:null})});this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r,errorInfo:null}}componentDidCatch(r,s){console.error("ErrorBoundary caught an error:",r,s),this.setState({error:r,errorInfo:s})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:h.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-50 px-4",children:h.jsxs("div",{className:"w-full max-w-md rounded-lg bg-white p-8 shadow-lg",children:[h.jsx("div",{className:"mb-4 flex items-center justify-center",children:h.jsx("div",{className:"rounded-full bg-red-100 p-3",children:h.jsx(ZR,{className:"h-8 w-8 text-red-600"})})}),h.jsx("h1",{className:"mb-2 text-center text-2xl font-bold text-gray-900",children:"Algo deu errado"}),h.jsx("p",{className:"mb-6 text-center text-gray-600",children:"Ocorreu um erro inesperado na aplicação."}),this.state.error&&h.jsxs("div",{className:"mb-6 rounded-md bg-red-50 p-4",children:[h.jsx("p",{className:"text-sm font-medium text-red-800",children:this.state.error.message}),!1]}),h.jsxs("div",{className:"flex gap-3",children:[h.jsx("button",{onClick:this.handleReset,className:"flex-1 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Tentar novamente"}),h.jsx("button",{onClick:()=>window.location.href="/",className:"flex-1 rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2",children:"Voltar ao início"})]})]})}):this.props.children}}function I0(t){var n,r,s="";if(typeof t=="string"||typeof t=="number")s+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(n=0;n<i;n++)t[n]&&(r=I0(t[n]))&&(s&&(s+=" "),s+=r)}else for(r in t)t[r]&&(s&&(s+=" "),s+=r);return s}function Oh(){for(var t,n,r=0,s="",i=arguments.length;r<i;r++)(t=arguments[r])&&(n=I0(t))&&(s&&(s+=" "),s+=n);return s}const JR=(t,n)=>{const r=new Array(t.length+n.length);for(let s=0;s<t.length;s++)r[s]=t[s];for(let s=0;s<n.length;s++)r[t.length+s]=n[s];return r},eA=(t,n)=>({classGroupId:t,validator:n}),q0=(t=new Map,n=null,r)=>({nextPart:t,validators:n,classGroupId:r}),tu="-",Lb=[],tA="arbitrary..",nA=t=>{const n=rA(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=t;return{getClassGroupId:u=>{if(u.startsWith("[")&&u.endsWith("]"))return aA(u);const f=u.split(tu),g=f[0]===""&&f.length>1?1:0;return F0(f,g,n)},getConflictingClassGroupIds:(u,f)=>{if(f){const g=s[u],p=r[u];return g?p?JR(p,g):g:p||Lb}return r[u]||Lb}}},F0=(t,n,r)=>{if(t.length-n===0)return r.classGroupId;const i=t[n],c=r.nextPart.get(i);if(c){const p=F0(t,n+1,c);if(p)return p}const u=r.validators;if(u===null)return;const f=n===0?t.join(tu):t.slice(n).join(tu),g=u.length;for(let p=0;p<g;p++){const y=u[p];if(y.validator(f))return y.classGroupId}},aA=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const n=t.slice(1,-1),r=n.indexOf(":"),s=n.slice(0,r);return s?tA+s:void 0})(),rA=t=>{const{theme:n,classGroups:r}=t;return sA(r,n)},sA=(t,n)=>{const r=q0();for(const s in t){const i=t[s];jh(i,r,s,n)}return r},jh=(t,n,r,s)=>{const i=t.length;for(let c=0;c<i;c++){const u=t[c];oA(u,n,r,s)}},oA=(t,n,r,s)=>{if(typeof t=="string"){iA(t,n,r);return}if(typeof t=="function"){lA(t,n,r,s);return}cA(t,n,r,s)},iA=(t,n,r)=>{const s=t===""?n:$0(n,t);s.classGroupId=r},lA=(t,n,r,s)=>{if(uA(t)){jh(t(s),n,r,s);return}n.validators===null&&(n.validators=[]),n.validators.push(eA(r,t))},cA=(t,n,r,s)=>{const i=Object.entries(t),c=i.length;for(let u=0;u<c;u++){const[f,g]=i[u];jh(g,$0(n,f),r,s)}},$0=(t,n)=>{let r=t;const s=n.split(tu),i=s.length;for(let c=0;c<i;c++){const u=s[c];let f=r.nextPart.get(u);f||(f=q0(),r.nextPart.set(u,f)),r=f}return r},uA=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,dA=t=>{if(t<1)return{get:()=>{},set:()=>{}};let n=0,r=Object.create(null),s=Object.create(null);const i=(c,u)=>{r[c]=u,n++,n>t&&(n=0,s=r,r=Object.create(null))};return{get(c){let u=r[c];if(u!==void 0)return u;if((u=s[c])!==void 0)return i(c,u),u},set(c,u){c in r?r[c]=u:i(c,u)}}},Km="!",Ub=":",fA=[],Bb=(t,n,r,s,i)=>({modifiers:t,hasImportantModifier:n,baseClassName:r,maybePostfixModifierPosition:s,isExternal:i}),mA=t=>{const{prefix:n,experimentalParseClassName:r}=t;let s=i=>{const c=[];let u=0,f=0,g=0,p;const y=i.length;for(let _=0;_<y;_++){const E=i[_];if(u===0&&f===0){if(E===Ub){c.push(i.slice(g,_)),g=_+1;continue}if(E==="/"){p=_;continue}}E==="["?u++:E==="]"?u--:E==="("?f++:E===")"&&f--}const v=c.length===0?i:i.slice(g);let w=v,C=!1;v.endsWith(Km)?(w=v.slice(0,-1),C=!0):v.startsWith(Km)&&(w=v.slice(1),C=!0);const S=p&&p>g?p-g:void 0;return Bb(c,C,w,S)};if(n){const i=n+Ub,c=s;s=u=>u.startsWith(i)?c(u.slice(i.length)):Bb(fA,!1,u,void 0,!0)}if(r){const i=s;s=c=>r({className:c,parseClassName:i})}return s},hA=t=>{const n=new Map;return t.orderSensitiveModifiers.forEach((r,s)=>{n.set(r,1e6+s)}),r=>{const s=[];let i=[];for(let c=0;c<r.length;c++){const u=r[c],f=u[0]==="[",g=n.has(u);f||g?(i.length>0&&(i.sort(),s.push(...i),i=[]),s.push(u)):i.push(u)}return i.length>0&&(i.sort(),s.push(...i)),s}},pA=t=>({cache:dA(t.cacheSize),parseClassName:mA(t),sortModifiers:hA(t),...nA(t)}),gA=/\s+/,vA=(t,n)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:i,sortModifiers:c}=n,u=[],f=t.trim().split(gA);let g="";for(let p=f.length-1;p>=0;p-=1){const y=f[p],{isExternal:v,modifiers:w,hasImportantModifier:C,baseClassName:S,maybePostfixModifierPosition:_}=r(y);if(v){g=y+(g.length>0?" "+g:g);continue}let E=!!_,R=s(E?S.substring(0,_):S);if(!R){if(!E){g=y+(g.length>0?" "+g:g);continue}if(R=s(S),!R){g=y+(g.length>0?" "+g:g);continue}E=!1}const k=w.length===0?"":w.length===1?w[0]:c(w).join(":"),A=C?k+Km:k,D=A+R;if(u.indexOf(D)>-1)continue;u.push(D);const H=i(R,E);for(let $=0;$<H.length;++$){const U=H[$];u.push(A+U)}g=y+(g.length>0?" "+g:g)}return g},yA=(...t)=>{let n=0,r,s,i="";for(;n<t.length;)(r=t[n++])&&(s=G0(r))&&(i&&(i+=" "),i+=s);return i},G0=t=>{if(typeof t=="string")return t;let n,r="";for(let s=0;s<t.length;s++)t[s]&&(n=G0(t[s]))&&(r&&(r+=" "),r+=n);return r},bA=(t,...n)=>{let r,s,i,c;const u=g=>{const p=n.reduce((y,v)=>v(y),t());return r=pA(p),s=r.cache.get,i=r.cache.set,c=f,f(g)},f=g=>{const p=s(g);if(p)return p;const y=vA(g,r);return i(g,y),y};return c=u,(...g)=>c(yA(...g))},xA=[],Kt=t=>{const n=r=>r[t]||xA;return n.isThemeGetter=!0,n},Y0=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Z0=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wA=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,SA=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,EA=/\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$/,_A=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,CA=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,NA=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Lr=t=>wA.test(t),Xe=t=>!!t&&!Number.isNaN(Number(t)),Ur=t=>!!t&&Number.isInteger(Number(t)),xm=t=>t.endsWith("%")&&Xe(t.slice(0,-1)),nr=t=>SA.test(t),X0=()=>!0,RA=t=>EA.test(t)&&!_A.test(t),kh=()=>!1,AA=t=>CA.test(t),TA=t=>NA.test(t),OA=t=>!Ne(t)&&!Ae(t),jA=t=>Kr(t,W0,kh),Ne=t=>Y0.test(t),vs=t=>Kr(t,J0,RA),Pb=t=>Kr(t,PA,Xe),kA=t=>Kr(t,t1,X0),MA=t=>Kr(t,e1,kh),Hb=t=>Kr(t,K0,kh),DA=t=>Kr(t,Q0,TA),Dc=t=>Kr(t,n1,AA),Ae=t=>Z0.test(t),qi=t=>As(t,J0),zA=t=>As(t,e1),Vb=t=>As(t,K0),LA=t=>As(t,W0),UA=t=>As(t,Q0),zc=t=>As(t,n1,!0),BA=t=>As(t,t1,!0),Kr=(t,n,r)=>{const s=Y0.exec(t);return s?s[1]?n(s[1]):r(s[2]):!1},As=(t,n,r=!1)=>{const s=Z0.exec(t);return s?s[1]?n(s[1]):r:!1},K0=t=>t==="position"||t==="percentage",Q0=t=>t==="image"||t==="url",W0=t=>t==="length"||t==="size"||t==="bg-size",J0=t=>t==="length",PA=t=>t==="number",e1=t=>t==="family-name",t1=t=>t==="number"||t==="weight",n1=t=>t==="shadow",HA=()=>{const t=Kt("color"),n=Kt("font"),r=Kt("text"),s=Kt("font-weight"),i=Kt("tracking"),c=Kt("leading"),u=Kt("breakpoint"),f=Kt("container"),g=Kt("spacing"),p=Kt("radius"),y=Kt("shadow"),v=Kt("inset-shadow"),w=Kt("text-shadow"),C=Kt("drop-shadow"),S=Kt("blur"),_=Kt("perspective"),E=Kt("aspect"),R=Kt("ease"),k=Kt("animate"),A=()=>["auto","avoid","all","avoid-page","page","left","right","column"],D=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],H=()=>[...D(),Ae,Ne],$=()=>["auto","hidden","clip","visible","scroll"],U=()=>["auto","contain","none"],F=()=>[Ae,Ne,g],de=()=>[Lr,"full","auto",...F()],fe=()=>[Ur,"none","subgrid",Ae,Ne],me=()=>["auto",{span:["full",Ur,Ae,Ne]},Ur,Ae,Ne],se=()=>[Ur,"auto",Ae,Ne],G=()=>["auto","min","max","fr",Ae,Ne],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],ve=()=>["start","end","center","stretch","center-safe","end-safe"],T=()=>["auto",...F()],K=()=>[Lr,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...F()],te=()=>[Lr,"screen","full","dvw","lvw","svw","min","max","fit",...F()],le=()=>[Lr,"screen","full","lh","dvh","lvh","svh","min","max","fit",...F()],ne=()=>[t,Ae,Ne],j=()=>[...D(),Vb,Hb,{position:[Ae,Ne]}],X=()=>["no-repeat",{repeat:["","x","y","space","round"]}],L=()=>["auto","cover","contain",LA,jA,{size:[Ae,Ne]}],Y=()=>[xm,qi,vs],J=()=>["","none","full",p,Ae,Ne],ie=()=>["",Xe,qi,vs],pe=()=>["solid","dashed","dotted","double"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>[Xe,xm,Vb,Hb],Re=()=>["","none",S,Ae,Ne],et=()=>["none",Xe,Ae,Ne],Me=()=>["none",Xe,Ae,Ne],ze=()=>[Xe,Ae,Ne],be=()=>[Lr,"full",...F()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[nr],breakpoint:[nr],color:[X0],container:[nr],"drop-shadow":[nr],ease:["in","out","in-out"],font:[OA],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[nr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[nr],shadow:[nr],spacing:["px",Xe],text:[nr],"text-shadow":[nr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Lr,Ne,Ae,E]}],container:["container"],columns:[{columns:[Xe,Ne,Ae,f]}],"break-after":[{"break-after":A()}],"break-before":[{"break-before":A()}],"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"],sr:["sr-only","not-sr-only"],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:H()}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:de()}],"inset-x":[{"inset-x":de()}],"inset-y":[{"inset-y":de()}],start:[{"inset-s":de(),start:de()}],end:[{"inset-e":de(),end:de()}],"inset-bs":[{"inset-bs":de()}],"inset-be":[{"inset-be":de()}],top:[{top:de()}],right:[{right:de()}],bottom:[{bottom:de()}],left:[{left:de()}],visibility:["visible","invisible","collapse"],z:[{z:[Ur,"auto",Ae,Ne]}],basis:[{basis:[Lr,"full","auto",f,...F()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xe,Lr,"auto","initial","none",Ne]}],grow:[{grow:["",Xe,Ae,Ne]}],shrink:[{shrink:["",Xe,Ae,Ne]}],order:[{order:[Ur,"first","last","none",Ae,Ne]}],"grid-cols":[{"grid-cols":fe()}],"col-start-end":[{col:me()}],"col-start":[{"col-start":se()}],"col-end":[{"col-end":se()}],"grid-rows":[{"grid-rows":fe()}],"row-start-end":[{row:me()}],"row-start":[{"row-start":se()}],"row-end":[{"row-end":se()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:F()}],"gap-x":[{"gap-x":F()}],"gap-y":[{"gap-y":F()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...ve(),"normal"]}],"justify-self":[{"justify-self":["auto",...ve()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...ve(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...ve(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...ve(),"baseline"]}],"place-self":[{"place-self":["auto",...ve()]}],p:[{p:F()}],px:[{px:F()}],py:[{py:F()}],ps:[{ps:F()}],pe:[{pe:F()}],pbs:[{pbs:F()}],pbe:[{pbe:F()}],pt:[{pt:F()}],pr:[{pr:F()}],pb:[{pb:F()}],pl:[{pl:F()}],m:[{m:T()}],mx:[{mx:T()}],my:[{my:T()}],ms:[{ms:T()}],me:[{me:T()}],mbs:[{mbs:T()}],mbe:[{mbe:T()}],mt:[{mt:T()}],mr:[{mr:T()}],mb:[{mb:T()}],ml:[{ml:T()}],"space-x":[{"space-x":F()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":F()}],"space-y-reverse":["space-y-reverse"],size:[{size:K()}],"inline-size":[{inline:["auto",...te()]}],"min-inline-size":[{"min-inline":["auto",...te()]}],"max-inline-size":[{"max-inline":["none",...te()]}],"block-size":[{block:["auto",...le()]}],"min-block-size":[{"min-block":["auto",...le()]}],"max-block-size":[{"max-block":["none",...le()]}],w:[{w:[f,"screen",...K()]}],"min-w":[{"min-w":[f,"screen","none",...K()]}],"max-w":[{"max-w":[f,"screen","none","prose",{screen:[u]},...K()]}],h:[{h:["screen","lh",...K()]}],"min-h":[{"min-h":["screen","lh","none",...K()]}],"max-h":[{"max-h":["screen","lh",...K()]}],"font-size":[{text:["base",r,qi,vs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,BA,kA]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",xm,Ne]}],"font-family":[{font:[zA,MA,n]}],"font-features":[{"font-features":[Ne]}],"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-fractions"],tracking:[{tracking:[i,Ae,Ne]}],"line-clamp":[{"line-clamp":[Xe,"none",Ae,Pb]}],leading:[{leading:[c,...F()]}],"list-image":[{"list-image":["none",Ae,Ne]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ae,Ne]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ne()}],"text-color":[{text:ne()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...pe(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xe,"from-font","auto",Ae,vs]}],"text-decoration-color":[{decoration:ne()}],"underline-offset":[{"underline-offset":[Xe,"auto",Ae,Ne]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:F()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ae,Ne]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ae,Ne]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:j()}],"bg-repeat":[{bg:X()}],"bg-size":[{bg:L()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ur,Ae,Ne],radial:["",Ae,Ne],conic:[Ur,Ae,Ne]},UA,DA]}],"bg-color":[{bg:ne()}],"gradient-from-pos":[{from:Y()}],"gradient-via-pos":[{via:Y()}],"gradient-to-pos":[{to:Y()}],"gradient-from":[{from:ne()}],"gradient-via":[{via:ne()}],"gradient-to":[{to:ne()}],rounded:[{rounded:J()}],"rounded-s":[{"rounded-s":J()}],"rounded-e":[{"rounded-e":J()}],"rounded-t":[{"rounded-t":J()}],"rounded-r":[{"rounded-r":J()}],"rounded-b":[{"rounded-b":J()}],"rounded-l":[{"rounded-l":J()}],"rounded-ss":[{"rounded-ss":J()}],"rounded-se":[{"rounded-se":J()}],"rounded-ee":[{"rounded-ee":J()}],"rounded-es":[{"rounded-es":J()}],"rounded-tl":[{"rounded-tl":J()}],"rounded-tr":[{"rounded-tr":J()}],"rounded-br":[{"rounded-br":J()}],"rounded-bl":[{"rounded-bl":J()}],"border-w":[{border:ie()}],"border-w-x":[{"border-x":ie()}],"border-w-y":[{"border-y":ie()}],"border-w-s":[{"border-s":ie()}],"border-w-e":[{"border-e":ie()}],"border-w-bs":[{"border-bs":ie()}],"border-w-be":[{"border-be":ie()}],"border-w-t":[{"border-t":ie()}],"border-w-r":[{"border-r":ie()}],"border-w-b":[{"border-b":ie()}],"border-w-l":[{"border-l":ie()}],"divide-x":[{"divide-x":ie()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ie()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...pe(),"hidden","none"]}],"divide-style":[{divide:[...pe(),"hidden","none"]}],"border-color":[{border:ne()}],"border-color-x":[{"border-x":ne()}],"border-color-y":[{"border-y":ne()}],"border-color-s":[{"border-s":ne()}],"border-color-e":[{"border-e":ne()}],"border-color-bs":[{"border-bs":ne()}],"border-color-be":[{"border-be":ne()}],"border-color-t":[{"border-t":ne()}],"border-color-r":[{"border-r":ne()}],"border-color-b":[{"border-b":ne()}],"border-color-l":[{"border-l":ne()}],"divide-color":[{divide:ne()}],"outline-style":[{outline:[...pe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xe,Ae,Ne]}],"outline-w":[{outline:["",Xe,qi,vs]}],"outline-color":[{outline:ne()}],shadow:[{shadow:["","none",y,zc,Dc]}],"shadow-color":[{shadow:ne()}],"inset-shadow":[{"inset-shadow":["none",v,zc,Dc]}],"inset-shadow-color":[{"inset-shadow":ne()}],"ring-w":[{ring:ie()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ne()}],"ring-offset-w":[{"ring-offset":[Xe,vs]}],"ring-offset-color":[{"ring-offset":ne()}],"inset-ring-w":[{"inset-ring":ie()}],"inset-ring-color":[{"inset-ring":ne()}],"text-shadow":[{"text-shadow":["none",w,zc,Dc]}],"text-shadow-color":[{"text-shadow":ne()}],opacity:[{opacity:[Xe,Ae,Ne]}],"mix-blend":[{"mix-blend":[...Q(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Q()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Xe]}],"mask-image-linear-from-pos":[{"mask-linear-from":oe()}],"mask-image-linear-to-pos":[{"mask-linear-to":oe()}],"mask-image-linear-from-color":[{"mask-linear-from":ne()}],"mask-image-linear-to-color":[{"mask-linear-to":ne()}],"mask-image-t-from-pos":[{"mask-t-from":oe()}],"mask-image-t-to-pos":[{"mask-t-to":oe()}],"mask-image-t-from-color":[{"mask-t-from":ne()}],"mask-image-t-to-color":[{"mask-t-to":ne()}],"mask-image-r-from-pos":[{"mask-r-from":oe()}],"mask-image-r-to-pos":[{"mask-r-to":oe()}],"mask-image-r-from-color":[{"mask-r-from":ne()}],"mask-image-r-to-color":[{"mask-r-to":ne()}],"mask-image-b-from-pos":[{"mask-b-from":oe()}],"mask-image-b-to-pos":[{"mask-b-to":oe()}],"mask-image-b-from-color":[{"mask-b-from":ne()}],"mask-image-b-to-color":[{"mask-b-to":ne()}],"mask-image-l-from-pos":[{"mask-l-from":oe()}],"mask-image-l-to-pos":[{"mask-l-to":oe()}],"mask-image-l-from-color":[{"mask-l-from":ne()}],"mask-image-l-to-color":[{"mask-l-to":ne()}],"mask-image-x-from-pos":[{"mask-x-from":oe()}],"mask-image-x-to-pos":[{"mask-x-to":oe()}],"mask-image-x-from-color":[{"mask-x-from":ne()}],"mask-image-x-to-color":[{"mask-x-to":ne()}],"mask-image-y-from-pos":[{"mask-y-from":oe()}],"mask-image-y-to-pos":[{"mask-y-to":oe()}],"mask-image-y-from-color":[{"mask-y-from":ne()}],"mask-image-y-to-color":[{"mask-y-to":ne()}],"mask-image-radial":[{"mask-radial":[Ae,Ne]}],"mask-image-radial-from-pos":[{"mask-radial-from":oe()}],"mask-image-radial-to-pos":[{"mask-radial-to":oe()}],"mask-image-radial-from-color":[{"mask-radial-from":ne()}],"mask-image-radial-to-color":[{"mask-radial-to":ne()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":D()}],"mask-image-conic-pos":[{"mask-conic":[Xe]}],"mask-image-conic-from-pos":[{"mask-conic-from":oe()}],"mask-image-conic-to-pos":[{"mask-conic-to":oe()}],"mask-image-conic-from-color":[{"mask-conic-from":ne()}],"mask-image-conic-to-color":[{"mask-conic-to":ne()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:j()}],"mask-repeat":[{mask:X()}],"mask-size":[{mask:L()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ae,Ne]}],filter:[{filter:["","none",Ae,Ne]}],blur:[{blur:Re()}],brightness:[{brightness:[Xe,Ae,Ne]}],contrast:[{contrast:[Xe,Ae,Ne]}],"drop-shadow":[{"drop-shadow":["","none",C,zc,Dc]}],"drop-shadow-color":[{"drop-shadow":ne()}],grayscale:[{grayscale:["",Xe,Ae,Ne]}],"hue-rotate":[{"hue-rotate":[Xe,Ae,Ne]}],invert:[{invert:["",Xe,Ae,Ne]}],saturate:[{saturate:[Xe,Ae,Ne]}],sepia:[{sepia:["",Xe,Ae,Ne]}],"backdrop-filter":[{"backdrop-filter":["","none",Ae,Ne]}],"backdrop-blur":[{"backdrop-blur":Re()}],"backdrop-brightness":[{"backdrop-brightness":[Xe,Ae,Ne]}],"backdrop-contrast":[{"backdrop-contrast":[Xe,Ae,Ne]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xe,Ae,Ne]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xe,Ae,Ne]}],"backdrop-invert":[{"backdrop-invert":["",Xe,Ae,Ne]}],"backdrop-opacity":[{"backdrop-opacity":[Xe,Ae,Ne]}],"backdrop-saturate":[{"backdrop-saturate":[Xe,Ae,Ne]}],"backdrop-sepia":[{"backdrop-sepia":["",Xe,Ae,Ne]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":F()}],"border-spacing-x":[{"border-spacing-x":F()}],"border-spacing-y":[{"border-spacing-y":F()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ae,Ne]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xe,"initial",Ae,Ne]}],ease:[{ease:["linear","initial",R,Ae,Ne]}],delay:[{delay:[Xe,Ae,Ne]}],animate:[{animate:["none",k,Ae,Ne]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[_,Ae,Ne]}],"perspective-origin":[{"perspective-origin":H()}],rotate:[{rotate:et()}],"rotate-x":[{"rotate-x":et()}],"rotate-y":[{"rotate-y":et()}],"rotate-z":[{"rotate-z":et()}],scale:[{scale:Me()}],"scale-x":[{"scale-x":Me()}],"scale-y":[{"scale-y":Me()}],"scale-z":[{"scale-z":Me()}],"scale-3d":["scale-3d"],skew:[{skew:ze()}],"skew-x":[{"skew-x":ze()}],"skew-y":[{"skew-y":ze()}],transform:[{transform:[Ae,Ne,"","none","gpu","cpu"]}],"transform-origin":[{origin:H()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:be()}],"translate-x":[{"translate-x":be()}],"translate-y":[{"translate-y":be()}],"translate-z":[{"translate-z":be()}],"translate-none":["translate-none"],accent:[{accent:ne()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ne()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",Ae,Ne]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":F()}],"scroll-mx":[{"scroll-mx":F()}],"scroll-my":[{"scroll-my":F()}],"scroll-ms":[{"scroll-ms":F()}],"scroll-me":[{"scroll-me":F()}],"scroll-mbs":[{"scroll-mbs":F()}],"scroll-mbe":[{"scroll-mbe":F()}],"scroll-mt":[{"scroll-mt":F()}],"scroll-mr":[{"scroll-mr":F()}],"scroll-mb":[{"scroll-mb":F()}],"scroll-ml":[{"scroll-ml":F()}],"scroll-p":[{"scroll-p":F()}],"scroll-px":[{"scroll-px":F()}],"scroll-py":[{"scroll-py":F()}],"scroll-ps":[{"scroll-ps":F()}],"scroll-pe":[{"scroll-pe":F()}],"scroll-pbs":[{"scroll-pbs":F()}],"scroll-pbe":[{"scroll-pbe":F()}],"scroll-pt":[{"scroll-pt":F()}],"scroll-pr":[{"scroll-pr":F()}],"scroll-pb":[{"scroll-pb":F()}],"scroll-pl":[{"scroll-pl":F()}],"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",Ae,Ne]}],fill:[{fill:["none",...ne()]}],"stroke-w":[{stroke:[Xe,qi,vs,Pb]}],stroke:[{stroke:["none",...ne()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","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","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","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-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","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-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","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-pbs","scroll-pbe","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"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},a1=bA(HA);function Qm(...t){return a1(Oh(t))}const VA=[{to:"/manager",label:"Dashboard",icon:wR},{to:"/manager/instances",label:"Instâncias",icon:qR}];function IA(){const t=new Date().getFullYear();return h.jsxs("div",{className:"hidden md:flex bg-sidebar text-sidebar-foreground flex-col w-56 border-r border-sidebar-border",children:[h.jsx("div",{className:"h-16 flex items-center px-4 border-b border-sidebar-border",children:h.jsx("h2",{className:"text-lg font-bold text-primary",children:"Evolution GO"})}),h.jsx("nav",{className:"space-y-1.5 flex-1 px-2 py-4",children:VA.map(n=>h.jsx(L0,{to:n.to,end:n.to==="/manager",className:({isActive:r})=>Qm("flex items-center gap-3 px-3 py-2.5 rounded-md transition-all",r?"bg-primary/10 text-primary":"text-muted-foreground hover:text-foreground hover:bg-accent"),children:({isActive:r})=>h.jsxs(h.Fragment,{children:[h.jsx(n.icon,{className:Qm("flex-shrink-0 h-5 w-5",r&&"text-primary")}),h.jsx("span",{className:"font-medium",children:n.label})]})},n.to))}),h.jsxs("div",{className:"mt-auto p-4 border-t border-sidebar-border",children:[h.jsx("div",{className:"text-sm text-primary font-medium",children:"Evolution GO"}),h.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["© ",t," All rights reserved"]})]})]})}const Ib=t=>{let n;const r=new Set,s=(p,y)=>{const v=typeof p=="function"?p(n):p;if(!Object.is(v,n)){const w=n;n=y??(typeof v!="object"||v===null)?v:Object.assign({},n,v),r.forEach(C=>C(n,w))}},i=()=>n,f={setState:s,getState:i,getInitialState:()=>g,subscribe:p=>(r.add(p),()=>r.delete(p))},g=n=t(s,i,f);return f},qA=(t=>t?Ib(t):Ib),FA=t=>t;function $A(t,n=FA){const r=ae.useSyncExternalStore(t.subscribe,ae.useCallback(()=>n(t.getState()),[t,n]),ae.useCallback(()=>n(t.getInitialState()),[t,n]));return ae.useDebugValue(r),r}const GA=t=>{const n=qA(t),r=s=>$A(n,s);return Object.assign(r,n),r},r1=(t=>GA);function YA(t,n){let r;try{r=t()}catch{return}return{getItem:i=>{var c;const u=g=>g===null?null:JSON.parse(g,void 0),f=(c=r.getItem(i))!=null?c:null;return f instanceof Promise?f.then(u):u(f)},setItem:(i,c)=>r.setItem(i,JSON.stringify(c,void 0)),removeItem:i=>r.removeItem(i)}}const Wm=t=>n=>{try{const r=t(n);return r instanceof Promise?r:{then(s){return Wm(s)(r)},catch(s){return this}}}catch(r){return{then(s){return this},catch(s){return Wm(s)(r)}}}},ZA=(t,n)=>(r,s,i)=>{let c={storage:YA(()=>window.localStorage),partialize:E=>E,version:0,merge:(E,R)=>({...R,...E}),...n},u=!1,f=0;const g=new Set,p=new Set;let y=c.storage;if(!y)return t((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${c.name}', the given storage is currently unavailable.`),r(...E)},s,i);const v=()=>{const E=c.partialize({...s()});return y.setItem(c.name,{state:E,version:c.version})},w=i.setState;i.setState=(E,R)=>(w(E,R),v());const C=t((...E)=>(r(...E),v()),s,i);i.getInitialState=()=>C;let S;const _=()=>{var E,R;if(!y)return;const k=++f;u=!1,g.forEach(D=>{var H;return D((H=s())!=null?H:C)});const A=((R=c.onRehydrateStorage)==null?void 0:R.call(c,(E=s())!=null?E:C))||void 0;return Wm(y.getItem.bind(y))(c.name).then(D=>{if(D)if(typeof D.version=="number"&&D.version!==c.version){if(c.migrate){const H=c.migrate(D.state,D.version);return H instanceof Promise?H.then($=>[!0,$]):[!0,H]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,D.state];return[!1,void 0]}).then(D=>{var H;if(k!==f)return;const[$,U]=D;if(S=c.merge(U,(H=s())!=null?H:C),r(S,!0),$)return v()}).then(()=>{k===f&&(A==null||A(s(),void 0),S=s(),u=!0,p.forEach(D=>D(S)))}).catch(D=>{k===f&&(A==null||A(void 0,D))})};return i.persist={setOptions:E=>{c={...c,...E},E.storage&&(y=E.storage)},clearStorage:()=>{y==null||y.removeItem(c.name)},getOptions:()=>c,rehydrate:()=>_(),hasHydrated:()=>u,onHydrate:E=>(g.add(E),()=>{g.delete(E)}),onFinishHydration:E=>(p.add(E),()=>{p.delete(E)})},c.skipHydration||_(),S||C},XA=ZA;function s1(t,n){return function(){return t.apply(n,arguments)}}const{toString:KA}=Object.prototype,{getPrototypeOf:Mh}=Object,{iterator:Ou,toStringTag:o1}=Symbol,ju=(t=>n=>{const r=KA.call(n);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),ya=t=>(t=t.toLowerCase(),n=>ju(n)===t),ku=t=>n=>typeof n===t,{isArray:Go}=Array,Mo=ku("undefined");function cl(t){return t!==null&&!Mo(t)&&t.constructor!==null&&!Mo(t.constructor)&&jn(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const i1=ya("ArrayBuffer");function QA(t){let n;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?n=ArrayBuffer.isView(t):n=t&&t.buffer&&i1(t.buffer),n}const WA=ku("string"),jn=ku("function"),l1=ku("number"),ul=t=>t!==null&&typeof t=="object",JA=t=>t===!0||t===!1,Zc=t=>{if(ju(t)!=="object")return!1;const n=Mh(t);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(o1 in t)&&!(Ou in t)},eT=t=>{if(!ul(t)||cl(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},tT=ya("Date"),nT=ya("File"),aT=t=>!!(t&&typeof t.uri<"u"),rT=t=>t&&typeof t.getParts<"u",sT=ya("Blob"),oT=ya("FileList"),iT=t=>ul(t)&&jn(t.pipe);function lT(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const qb=lT(),Fb=typeof qb.FormData<"u"?qb.FormData:void 0,cT=t=>{let n;return t&&(Fb&&t instanceof Fb||jn(t.append)&&((n=ju(t))==="formdata"||n==="object"&&jn(t.toString)&&t.toString()==="[object FormData]"))},uT=ya("URLSearchParams"),[dT,fT,mT,hT]=["ReadableStream","Request","Response","Headers"].map(ya),pT=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function dl(t,n,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let s,i;if(typeof t!="object"&&(t=[t]),Go(t))for(s=0,i=t.length;s<i;s++)n.call(null,t[s],s,t);else{if(cl(t))return;const c=r?Object.getOwnPropertyNames(t):Object.keys(t),u=c.length;let f;for(s=0;s<u;s++)f=c[s],n.call(null,t[f],f,t)}}function c1(t,n){if(cl(t))return null;n=n.toLowerCase();const r=Object.keys(t);let s=r.length,i;for(;s-- >0;)if(i=r[s],n===i.toLowerCase())return i;return null}const xs=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,u1=t=>!Mo(t)&&t!==xs;function Jm(){const{caseless:t,skipUndefined:n}=u1(this)&&this||{},r={},s=(i,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const u=t&&c1(r,c)||c;Zc(r[u])&&Zc(i)?r[u]=Jm(r[u],i):Zc(i)?r[u]=Jm({},i):Go(i)?r[u]=i.slice():(!n||!Mo(i))&&(r[u]=i)};for(let i=0,c=arguments.length;i<c;i++)arguments[i]&&dl(arguments[i],s);return r}const gT=(t,n,r,{allOwnKeys:s}={})=>(dl(n,(i,c)=>{r&&jn(i)?Object.defineProperty(t,c,{value:s1(i,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,c,{value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),t),vT=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),yT=(t,n,r,s)=>{t.prototype=Object.create(n.prototype,s),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:n.prototype}),r&&Object.assign(t.prototype,r)},bT=(t,n,r,s)=>{let i,c,u;const f={};if(n=n||{},t==null)return n;do{for(i=Object.getOwnPropertyNames(t),c=i.length;c-- >0;)u=i[c],(!s||s(u,t,n))&&!f[u]&&(n[u]=t[u],f[u]=!0);t=r!==!1&&Mh(t)}while(t&&(!r||r(t,n))&&t!==Object.prototype);return n},xT=(t,n,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=n.length;const s=t.indexOf(n,r);return s!==-1&&s===r},wT=t=>{if(!t)return null;if(Go(t))return t;let n=t.length;if(!l1(n))return null;const r=new Array(n);for(;n-- >0;)r[n]=t[n];return r},ST=(t=>n=>t&&n instanceof t)(typeof Uint8Array<"u"&&Mh(Uint8Array)),ET=(t,n)=>{const s=(t&&t[Ou]).call(t);let i;for(;(i=s.next())&&!i.done;){const c=i.value;n.call(t,c[0],c[1])}},_T=(t,n)=>{let r;const s=[];for(;(r=t.exec(n))!==null;)s.push(r);return s},CT=ya("HTMLFormElement"),NT=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,s,i){return s.toUpperCase()+i}),$b=(({hasOwnProperty:t})=>(n,r)=>t.call(n,r))(Object.prototype),RT=ya("RegExp"),d1=(t,n)=>{const r=Object.getOwnPropertyDescriptors(t),s={};dl(r,(i,c)=>{let u;(u=n(i,c,t))!==!1&&(s[c]=u||i)}),Object.defineProperties(t,s)},AT=t=>{d1(t,(n,r)=>{if(jn(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const s=t[r];if(jn(s)){if(n.enumerable=!1,"writable"in n){n.writable=!1;return}n.set||(n.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},TT=(t,n)=>{const r={},s=i=>{i.forEach(c=>{r[c]=!0})};return Go(t)?s(t):s(String(t).split(n)),r},OT=()=>{},jT=(t,n)=>t!=null&&Number.isFinite(t=+t)?t:n;function kT(t){return!!(t&&jn(t.append)&&t[o1]==="FormData"&&t[Ou])}const MT=t=>{const n=new Array(10),r=(s,i)=>{if(ul(s)){if(n.indexOf(s)>=0)return;if(cl(s))return s;if(!("toJSON"in s)){n[i]=s;const c=Go(s)?[]:{};return dl(s,(u,f)=>{const g=r(u,i+1);!Mo(g)&&(c[f]=g)}),n[i]=void 0,c}}return s};return r(t,0)},DT=ya("AsyncFunction"),zT=t=>t&&(ul(t)||jn(t))&&jn(t.then)&&jn(t.catch),f1=((t,n)=>t?setImmediate:n?((r,s)=>(xs.addEventListener("message",({source:i,data:c})=>{i===xs&&c===r&&s.length&&s.shift()()},!1),i=>{s.push(i),xs.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",jn(xs.postMessage)),LT=typeof queueMicrotask<"u"?queueMicrotask.bind(xs):typeof process<"u"&&process.nextTick||f1,UT=t=>t!=null&&jn(t[Ou]),W={isArray:Go,isArrayBuffer:i1,isBuffer:cl,isFormData:cT,isArrayBufferView:QA,isString:WA,isNumber:l1,isBoolean:JA,isObject:ul,isPlainObject:Zc,isEmptyObject:eT,isReadableStream:dT,isRequest:fT,isResponse:mT,isHeaders:hT,isUndefined:Mo,isDate:tT,isFile:nT,isReactNativeBlob:aT,isReactNative:rT,isBlob:sT,isRegExp:RT,isFunction:jn,isStream:iT,isURLSearchParams:uT,isTypedArray:ST,isFileList:oT,forEach:dl,merge:Jm,extend:gT,trim:pT,stripBOM:vT,inherits:yT,toFlatObject:bT,kindOf:ju,kindOfTest:ya,endsWith:xT,toArray:wT,forEachEntry:ET,matchAll:_T,isHTMLForm:CT,hasOwnProperty:$b,hasOwnProp:$b,reduceDescriptors:d1,freezeMethods:AT,toObjectSet:TT,toCamelCase:NT,noop:OT,toFiniteNumber:jT,findKey:c1,global:xs,isContextDefined:u1,isSpecCompliantForm:kT,toJSONObject:MT,isAsyncFn:DT,isThenable:zT,setImmediate:f1,asap:LT,isIterable:UT};let Be=class m1 extends Error{static from(n,r,s,i,c,u){const f=new m1(n.message,r||n.code,s,i,c);return f.cause=n,f.name=n.name,n.status!=null&&f.status==null&&(f.status=n.status),u&&Object.assign(f,u),f}constructor(n,r,s,i,c){super(n),Object.defineProperty(this,"message",{value:n,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,r&&(this.code=r),s&&(this.config=s),i&&(this.request=i),c&&(this.response=c,this.status=c.status)}toJSON(){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:W.toJSONObject(this.config),code:this.code,status:this.status}}};Be.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";Be.ERR_BAD_OPTION="ERR_BAD_OPTION";Be.ECONNABORTED="ECONNABORTED";Be.ETIMEDOUT="ETIMEDOUT";Be.ERR_NETWORK="ERR_NETWORK";Be.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";Be.ERR_DEPRECATED="ERR_DEPRECATED";Be.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";Be.ERR_BAD_REQUEST="ERR_BAD_REQUEST";Be.ERR_CANCELED="ERR_CANCELED";Be.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";Be.ERR_INVALID_URL="ERR_INVALID_URL";const BT=null;function eh(t){return W.isPlainObject(t)||W.isArray(t)}function h1(t){return W.endsWith(t,"[]")?t.slice(0,-2):t}function wm(t,n,r){return t?t.concat(n).map(function(i,c){return i=h1(i),!r&&c?"["+i+"]":i}).join(r?".":""):n}function PT(t){return W.isArray(t)&&!t.some(eh)}const HT=W.toFlatObject(W,{},null,function(n){return/^is[A-Z]/.test(n)});function Mu(t,n,r){if(!W.isObject(t))throw new TypeError("target must be an object");n=n||new FormData,r=W.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,E){return!W.isUndefined(E[_])});const s=r.metaTokens,i=r.visitor||y,c=r.dots,u=r.indexes,g=(r.Blob||typeof Blob<"u"&&Blob)&&W.isSpecCompliantForm(n);if(!W.isFunction(i))throw new TypeError("visitor must be a function");function p(S){if(S===null)return"";if(W.isDate(S))return S.toISOString();if(W.isBoolean(S))return S.toString();if(!g&&W.isBlob(S))throw new Be("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(S)||W.isTypedArray(S)?g&&typeof Blob=="function"?new Blob([S]):Buffer.from(S):S}function y(S,_,E){let R=S;if(W.isReactNative(n)&&W.isReactNativeBlob(S))return n.append(wm(E,_,c),p(S)),!1;if(S&&!E&&typeof S=="object"){if(W.endsWith(_,"{}"))_=s?_:_.slice(0,-2),S=JSON.stringify(S);else if(W.isArray(S)&&PT(S)||(W.isFileList(S)||W.endsWith(_,"[]"))&&(R=W.toArray(S)))return _=h1(_),R.forEach(function(A,D){!(W.isUndefined(A)||A===null)&&n.append(u===!0?wm([_],D,c):u===null?_:_+"[]",p(A))}),!1}return eh(S)?!0:(n.append(wm(E,_,c),p(S)),!1)}const v=[],w=Object.assign(HT,{defaultVisitor:y,convertValue:p,isVisitable:eh});function C(S,_){if(!W.isUndefined(S)){if(v.indexOf(S)!==-1)throw Error("Circular reference detected in "+_.join("."));v.push(S),W.forEach(S,function(R,k){(!(W.isUndefined(R)||R===null)&&i.call(n,R,W.isString(k)?k.trim():k,_,w))===!0&&C(R,_?_.concat(k):[k])}),v.pop()}}if(!W.isObject(t))throw new TypeError("data must be an object");return C(t),n}function Gb(t){const n={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return n[s]})}function Dh(t,n){this._pairs=[],t&&Mu(t,this,n)}const p1=Dh.prototype;p1.append=function(n,r){this._pairs.push([n,r])};p1.toString=function(n){const r=n?function(s){return n.call(this,s,Gb)}:Gb;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function VT(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function g1(t,n,r){if(!n)return t;const s=r&&r.encode||VT,i=W.isFunction(r)?{serialize:r}:r,c=i&&i.serialize;let u;if(c?u=c(n,i):u=W.isURLSearchParams(n)?n.toString():new Dh(n,i).toString(s),u){const f=t.indexOf("#");f!==-1&&(t=t.slice(0,f)),t+=(t.indexOf("?")===-1?"?":"&")+u}return t}class Yb{constructor(){this.handlers=[]}use(n,r,s){return this.handlers.push({fulfilled:n,rejected:r,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(n){this.handlers[n]&&(this.handlers[n]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(n){W.forEach(this.handlers,function(s){s!==null&&n(s)})}}const zh={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},IT=typeof URLSearchParams<"u"?URLSearchParams:Dh,qT=typeof FormData<"u"?FormData:null,FT=typeof Blob<"u"?Blob:null,$T={isBrowser:!0,classes:{URLSearchParams:IT,FormData:qT,Blob:FT},protocols:["http","https","file","blob","url","data"]},Lh=typeof window<"u"&&typeof document<"u",th=typeof navigator=="object"&&navigator||void 0,GT=Lh&&(!th||["ReactNative","NativeScript","NS"].indexOf(th.product)<0),YT=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ZT=Lh&&window.location.href||"http://localhost",XT=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Lh,hasStandardBrowserEnv:GT,hasStandardBrowserWebWorkerEnv:YT,navigator:th,origin:ZT},Symbol.toStringTag,{value:"Module"})),mn={...XT,...$T};function KT(t,n){return Mu(t,new mn.classes.URLSearchParams,{visitor:function(r,s,i,c){return mn.isNode&&W.isBuffer(r)?(this.append(s,r.toString("base64")),!1):c.defaultVisitor.apply(this,arguments)},...n})}function QT(t){return W.matchAll(/\w+|\[(\w*)]/g,t).map(n=>n[0]==="[]"?"":n[1]||n[0])}function WT(t){const n={},r=Object.keys(t);let s;const i=r.length;let c;for(s=0;s<i;s++)c=r[s],n[c]=t[c];return n}function v1(t){function n(r,s,i,c){let u=r[c++];if(u==="__proto__")return!0;const f=Number.isFinite(+u),g=c>=r.length;return u=!u&&W.isArray(i)?i.length:u,g?(W.hasOwnProp(i,u)?i[u]=[i[u],s]:i[u]=s,!f):((!i[u]||!W.isObject(i[u]))&&(i[u]=[]),n(r,s,i[u],c)&&W.isArray(i[u])&&(i[u]=WT(i[u])),!f)}if(W.isFormData(t)&&W.isFunction(t.entries)){const r={};return W.forEachEntry(t,(s,i)=>{n(QT(s),i,r,0)}),r}return null}function JT(t,n,r){if(W.isString(t))try{return(n||JSON.parse)(t),W.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(r||JSON.stringify)(t)}const fl={transitional:zh,adapter:["xhr","http","fetch"],transformRequest:[function(n,r){const s=r.getContentType()||"",i=s.indexOf("application/json")>-1,c=W.isObject(n);if(c&&W.isHTMLForm(n)&&(n=new FormData(n)),W.isFormData(n))return i?JSON.stringify(v1(n)):n;if(W.isArrayBuffer(n)||W.isBuffer(n)||W.isStream(n)||W.isFile(n)||W.isBlob(n)||W.isReadableStream(n))return n;if(W.isArrayBufferView(n))return n.buffer;if(W.isURLSearchParams(n))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),n.toString();let f;if(c){if(s.indexOf("application/x-www-form-urlencoded")>-1)return KT(n,this.formSerializer).toString();if((f=W.isFileList(n))||s.indexOf("multipart/form-data")>-1){const g=this.env&&this.env.FormData;return Mu(f?{"files[]":n}:n,g&&new g,this.formSerializer)}}return c||i?(r.setContentType("application/json",!1),JT(n)):n}],transformResponse:[function(n){const r=this.transitional||fl.transitional,s=r&&r.forcedJSONParsing,i=this.responseType==="json";if(W.isResponse(n)||W.isReadableStream(n))return n;if(n&&W.isString(n)&&(s&&!this.responseType||i)){const u=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(n,this.parseReviver)}catch(f){if(u)throw f.name==="SyntaxError"?Be.from(f,Be.ERR_BAD_RESPONSE,this,null,this.response):f}}return n}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:mn.classes.FormData,Blob:mn.classes.Blob},validateStatus:function(n){return n>=200&&n<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};W.forEach(["delete","get","head","post","put","patch"],t=>{fl.headers[t]={}});const eO=W.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"]),tO=t=>{const n={};let r,s,i;return t&&t.split(`+`).forEach(function(u){i=u.indexOf(":"),r=u.substring(0,i).trim().toLowerCase(),s=u.substring(i+1).trim(),!(!r||n[r]&&eO[r])&&(r==="set-cookie"?n[r]?n[r].push(s):n[r]=[s]:n[r]=n[r]?n[r]+", "+s:s)}),n},Zb=Symbol("internals");function Fi(t){return t&&String(t).trim().toLowerCase()}function Xc(t){return t===!1||t==null?t:W.isArray(t)?t.map(Xc):String(t)}function nO(t){const n=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=r.exec(t);)n[s[1]]=s[2];return n}const aO=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Sm(t,n,r,s,i){if(W.isFunction(s))return s.call(this,n,r);if(i&&(n=r),!!W.isString(n)){if(W.isString(s))return n.indexOf(s)!==-1;if(W.isRegExp(s))return s.test(n)}}function rO(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(n,r,s)=>r.toUpperCase()+s)}function sO(t,n){const r=W.toCamelCase(" "+n);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+r,{value:function(i,c,u){return this[s].call(this,n,i,c,u)},configurable:!0})})}let kn=class{constructor(n){n&&this.set(n)}set(n,r,s){const i=this;function c(f,g,p){const y=Fi(g);if(!y)throw new Error("header name must be a non-empty string");const v=W.findKey(i,y);(!v||i[v]===void 0||p===!0||p===void 0&&i[v]!==!1)&&(i[v||g]=Xc(f))}const u=(f,g)=>W.forEach(f,(p,y)=>c(p,y,g));if(W.isPlainObject(n)||n instanceof this.constructor)u(n,r);else if(W.isString(n)&&(n=n.trim())&&!aO(n))u(tO(n),r);else if(W.isObject(n)&&W.isIterable(n)){let f={},g,p;for(const y of n){if(!W.isArray(y))throw TypeError("Object iterator must return a key-value pair");f[p=y[0]]=(g=f[p])?W.isArray(g)?[...g,y[1]]:[g,y[1]]:y[1]}u(f,r)}else n!=null&&c(r,n,s);return this}get(n,r){if(n=Fi(n),n){const s=W.findKey(this,n);if(s){const i=this[s];if(!r)return i;if(r===!0)return nO(i);if(W.isFunction(r))return r.call(this,i,s);if(W.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(n,r){if(n=Fi(n),n){const s=W.findKey(this,n);return!!(s&&this[s]!==void 0&&(!r||Sm(this,this[s],s,r)))}return!1}delete(n,r){const s=this;let i=!1;function c(u){if(u=Fi(u),u){const f=W.findKey(s,u);f&&(!r||Sm(s,s[f],f,r))&&(delete s[f],i=!0)}}return W.isArray(n)?n.forEach(c):c(n),i}clear(n){const r=Object.keys(this);let s=r.length,i=!1;for(;s--;){const c=r[s];(!n||Sm(this,this[c],c,n,!0))&&(delete this[c],i=!0)}return i}normalize(n){const r=this,s={};return W.forEach(this,(i,c)=>{const u=W.findKey(s,c);if(u){r[u]=Xc(i),delete r[c];return}const f=n?rO(c):String(c).trim();f!==c&&delete r[c],r[f]=Xc(i),s[f]=!0}),this}concat(...n){return this.constructor.concat(this,...n)}toJSON(n){const r=Object.create(null);return W.forEach(this,(s,i)=>{s!=null&&s!==!1&&(r[i]=n&&W.isArray(s)?s.join(", "):s)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([n,r])=>n+": "+r).join(`+`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(n){return n instanceof this?n:new this(n)}static concat(n,...r){const s=new this(n);return r.forEach(i=>s.set(i)),s}static accessor(n){const s=(this[Zb]=this[Zb]={accessors:{}}).accessors,i=this.prototype;function c(u){const f=Fi(u);s[f]||(sO(i,u),s[f]=!0)}return W.isArray(n)?n.forEach(c):c(n),this}};kn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);W.reduceDescriptors(kn.prototype,({value:t},n)=>{let r=n[0].toUpperCase()+n.slice(1);return{get:()=>t,set(s){this[r]=s}}});W.freezeMethods(kn);function Em(t,n){const r=this||fl,s=n||r,i=kn.from(s.headers);let c=s.data;return W.forEach(t,function(f){c=f.call(r,c,i.normalize(),n?n.status:void 0)}),i.normalize(),c}function y1(t){return!!(t&&t.__CANCEL__)}let ml=class extends Be{constructor(n,r,s){super(n??"canceled",Be.ERR_CANCELED,r,s),this.name="CanceledError",this.__CANCEL__=!0}};function b1(t,n,r){const s=r.config.validateStatus;!r.status||!s||s(r.status)?t(r):n(new Be("Request failed with status code "+r.status,[Be.ERR_BAD_REQUEST,Be.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function oO(t){const n=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return n&&n[1]||""}function iO(t,n){t=t||10;const r=new Array(t),s=new Array(t);let i=0,c=0,u;return n=n!==void 0?n:1e3,function(g){const p=Date.now(),y=s[c];u||(u=p),r[i]=g,s[i]=p;let v=c,w=0;for(;v!==i;)w+=r[v++],v=v%t;if(i=(i+1)%t,i===c&&(c=(c+1)%t),p-u<n)return;const C=y&&p-y;return C?Math.round(w*1e3/C):void 0}}function lO(t,n){let r=0,s=1e3/n,i,c;const u=(p,y=Date.now())=>{r=y,i=null,c&&(clearTimeout(c),c=null),t(...p)};return[(...p)=>{const y=Date.now(),v=y-r;v>=s?u(p,y):(i=p,c||(c=setTimeout(()=>{c=null,u(i)},s-v)))},()=>i&&u(i)]}const nu=(t,n,r=3)=>{let s=0;const i=iO(50,250);return lO(c=>{const u=c.loaded,f=c.lengthComputable?c.total:void 0,g=u-s,p=i(g),y=u<=f;s=u;const v={loaded:u,total:f,progress:f?u/f:void 0,bytes:g,rate:p||void 0,estimated:p&&f&&y?(f-u)/p:void 0,event:c,lengthComputable:f!=null,[n?"download":"upload"]:!0};t(v)},r)},Xb=(t,n)=>{const r=t!=null;return[s=>n[0]({lengthComputable:r,total:t,loaded:s}),n[1]]},Kb=t=>(...n)=>W.asap(()=>t(...n)),cO=mn.hasStandardBrowserEnv?((t,n)=>r=>(r=new URL(r,mn.origin),t.protocol===r.protocol&&t.host===r.host&&(n||t.port===r.port)))(new URL(mn.origin),mn.navigator&&/(msie|trident)/i.test(mn.navigator.userAgent)):()=>!0,uO=mn.hasStandardBrowserEnv?{write(t,n,r,s,i,c,u){if(typeof document>"u")return;const f=[`${t}=${encodeURIComponent(n)}`];W.isNumber(r)&&f.push(`expires=${new Date(r).toUTCString()}`),W.isString(s)&&f.push(`path=${s}`),W.isString(i)&&f.push(`domain=${i}`),c===!0&&f.push("secure"),W.isString(u)&&f.push(`SameSite=${u}`),document.cookie=f.join("; ")},read(t){if(typeof document>"u")return null;const n=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return n?decodeURIComponent(n[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function dO(t){return typeof t!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function fO(t,n){return n?t.replace(/\/?\/$/,"")+"/"+n.replace(/^\/+/,""):t}function x1(t,n,r){let s=!dO(n);return t&&(s||r==!1)?fO(t,n):n}const Qb=t=>t instanceof kn?{...t}:t;function Es(t,n){n=n||{};const r={};function s(p,y,v,w){return W.isPlainObject(p)&&W.isPlainObject(y)?W.merge.call({caseless:w},p,y):W.isPlainObject(y)?W.merge({},y):W.isArray(y)?y.slice():y}function i(p,y,v,w){if(W.isUndefined(y)){if(!W.isUndefined(p))return s(void 0,p,v,w)}else return s(p,y,v,w)}function c(p,y){if(!W.isUndefined(y))return s(void 0,y)}function u(p,y){if(W.isUndefined(y)){if(!W.isUndefined(p))return s(void 0,p)}else return s(void 0,y)}function f(p,y,v){if(v in n)return s(p,y);if(v in t)return s(void 0,p)}const g={url:c,method:c,data:c,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,responseEncoding:u,validateStatus:f,headers:(p,y,v)=>i(Qb(p),Qb(y),v,!0)};return W.forEach(Object.keys({...t,...n}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=W.hasOwnProp(g,y)?g[y]:i,w=v(t[y],n[y],y);W.isUndefined(w)&&v!==f||(r[y]=w)}),r}const w1=t=>{const n=Es({},t);let{data:r,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:c,headers:u,auth:f}=n;if(n.headers=u=kn.from(u),n.url=g1(x1(n.baseURL,n.url,n.allowAbsoluteUrls),t.params,t.paramsSerializer),f&&u.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?unescape(encodeURIComponent(f.password)):""))),W.isFormData(r)){if(mn.hasStandardBrowserEnv||mn.hasStandardBrowserWebWorkerEnv)u.setContentType(void 0);else if(W.isFunction(r.getHeaders)){const g=r.getHeaders(),p=["content-type","content-length"];Object.entries(g).forEach(([y,v])=>{p.includes(y.toLowerCase())&&u.set(y,v)})}}if(mn.hasStandardBrowserEnv&&(s&&W.isFunction(s)&&(s=s(n)),s||s!==!1&&cO(n.url))){const g=i&&c&&uO.read(c);g&&u.set(i,g)}return n},mO=typeof XMLHttpRequest<"u",hO=mO&&function(t){return new Promise(function(r,s){const i=w1(t);let c=i.data;const u=kn.from(i.headers).normalize();let{responseType:f,onUploadProgress:g,onDownloadProgress:p}=i,y,v,w,C,S;function _(){C&&C(),S&&S(),i.cancelToken&&i.cancelToken.unsubscribe(y),i.signal&&i.signal.removeEventListener("abort",y)}let E=new XMLHttpRequest;E.open(i.method.toUpperCase(),i.url,!0),E.timeout=i.timeout;function R(){if(!E)return;const A=kn.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),H={data:!f||f==="text"||f==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:A,config:t,request:E};b1(function(U){r(U),_()},function(U){s(U),_()},H),E=null}"onloadend"in E?E.onloadend=R:E.onreadystatechange=function(){!E||E.readyState!==4||E.status===0&&!(E.responseURL&&E.responseURL.indexOf("file:")===0)||setTimeout(R)},E.onabort=function(){E&&(s(new Be("Request aborted",Be.ECONNABORTED,t,E)),E=null)},E.onerror=function(D){const H=D&&D.message?D.message:"Network Error",$=new Be(H,Be.ERR_NETWORK,t,E);$.event=D||null,s($),E=null},E.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const H=i.transitional||zh;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),s(new Be(D,H.clarifyTimeoutError?Be.ETIMEDOUT:Be.ECONNABORTED,t,E)),E=null},c===void 0&&u.setContentType(null),"setRequestHeader"in E&&W.forEach(u.toJSON(),function(D,H){E.setRequestHeader(H,D)}),W.isUndefined(i.withCredentials)||(E.withCredentials=!!i.withCredentials),f&&f!=="json"&&(E.responseType=i.responseType),p&&([w,S]=nu(p,!0),E.addEventListener("progress",w)),g&&E.upload&&([v,C]=nu(g),E.upload.addEventListener("progress",v),E.upload.addEventListener("loadend",C)),(i.cancelToken||i.signal)&&(y=A=>{E&&(s(!A||A.type?new ml(null,t,E):A),E.abort(),E=null)},i.cancelToken&&i.cancelToken.subscribe(y),i.signal&&(i.signal.aborted?y():i.signal.addEventListener("abort",y)));const k=oO(i.url);if(k&&mn.protocols.indexOf(k)===-1){s(new Be("Unsupported protocol "+k+":",Be.ERR_BAD_REQUEST,t));return}E.send(c||null)})},pO=(t,n)=>{const{length:r}=t=t?t.filter(Boolean):[];if(n||r){let s=new AbortController,i;const c=function(p){if(!i){i=!0,f();const y=p instanceof Error?p:this.reason;s.abort(y instanceof Be?y:new ml(y instanceof Error?y.message:y))}};let u=n&&setTimeout(()=>{u=null,c(new Be(`timeout of ${n}ms exceeded`,Be.ETIMEDOUT))},n);const f=()=>{t&&(u&&clearTimeout(u),u=null,t.forEach(p=>{p.unsubscribe?p.unsubscribe(c):p.removeEventListener("abort",c)}),t=null)};t.forEach(p=>p.addEventListener("abort",c));const{signal:g}=s;return g.unsubscribe=()=>W.asap(f),g}},gO=function*(t,n){let r=t.byteLength;if(r<n){yield t;return}let s=0,i;for(;s<r;)i=s+n,yield t.slice(s,i),s=i},vO=async function*(t,n){for await(const r of yO(t))yield*gO(r,n)},yO=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const n=t.getReader();try{for(;;){const{done:r,value:s}=await n.read();if(r)break;yield s}}finally{await n.cancel()}},Wb=(t,n,r,s)=>{const i=vO(t,n);let c=0,u,f=g=>{u||(u=!0,s&&s(g))};return new ReadableStream({async pull(g){try{const{done:p,value:y}=await i.next();if(p){f(),g.close();return}let v=y.byteLength;if(r){let w=c+=v;r(w)}g.enqueue(new Uint8Array(y))}catch(p){throw f(p),p}},cancel(g){return f(g),i.return()}},{highWaterMark:2})},Jb=64*1024,{isFunction:Lc}=W,bO=(({Request:t,Response:n})=>({Request:t,Response:n}))(W.global),{ReadableStream:ex,TextEncoder:tx}=W.global,nx=(t,...n)=>{try{return!!t(...n)}catch{return!1}},xO=t=>{t=W.merge.call({skipUndefined:!0},bO,t);const{fetch:n,Request:r,Response:s}=t,i=n?Lc(n):typeof fetch=="function",c=Lc(r),u=Lc(s);if(!i)return!1;const f=i&&Lc(ex),g=i&&(typeof tx=="function"?(S=>_=>S.encode(_))(new tx):async S=>new Uint8Array(await new r(S).arrayBuffer())),p=c&&f&&nx(()=>{let S=!1;const _=new r(mn.origin,{body:new ex,method:"POST",get duplex(){return S=!0,"half"}}).headers.has("Content-Type");return S&&!_}),y=u&&f&&nx(()=>W.isReadableStream(new s("").body)),v={stream:y&&(S=>S.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(S=>{!v[S]&&(v[S]=(_,E)=>{let R=_&&_[S];if(R)return R.call(_);throw new Be(`Response type '${S}' is not supported`,Be.ERR_NOT_SUPPORT,E)})});const w=async S=>{if(S==null)return 0;if(W.isBlob(S))return S.size;if(W.isSpecCompliantForm(S))return(await new r(mn.origin,{method:"POST",body:S}).arrayBuffer()).byteLength;if(W.isArrayBufferView(S)||W.isArrayBuffer(S))return S.byteLength;if(W.isURLSearchParams(S)&&(S=S+""),W.isString(S))return(await g(S)).byteLength},C=async(S,_)=>{const E=W.toFiniteNumber(S.getContentLength());return E??w(_)};return async S=>{let{url:_,method:E,data:R,signal:k,cancelToken:A,timeout:D,onDownloadProgress:H,onUploadProgress:$,responseType:U,headers:F,withCredentials:de="same-origin",fetchOptions:fe}=w1(S),me=n||fetch;U=U?(U+"").toLowerCase():"text";let se=pO([k,A&&A.toAbortSignal()],D),G=null;const he=se&&se.unsubscribe&&(()=>{se.unsubscribe()});let ve;try{if($&&p&&E!=="get"&&E!=="head"&&(ve=await C(F,R))!==0){let j=new r(_,{method:"POST",body:R,duplex:"half"}),X;if(W.isFormData(R)&&(X=j.headers.get("content-type"))&&F.setContentType(X),j.body){const[L,Y]=Xb(ve,nu(Kb($)));R=Wb(j.body,Jb,L,Y)}}W.isString(de)||(de=de?"include":"omit");const T=c&&"credentials"in r.prototype,K={...fe,signal:se,method:E.toUpperCase(),headers:F.normalize().toJSON(),body:R,duplex:"half",credentials:T?de:void 0};G=c&&new r(_,K);let te=await(c?me(G,fe):me(_,K));const le=y&&(U==="stream"||U==="response");if(y&&(H||le&&he)){const j={};["status","statusText","headers"].forEach(J=>{j[J]=te[J]});const X=W.toFiniteNumber(te.headers.get("content-length")),[L,Y]=H&&Xb(X,nu(Kb(H),!0))||[];te=new s(Wb(te.body,Jb,L,()=>{Y&&Y(),he&&he()}),j)}U=U||"text";let ne=await v[W.findKey(v,U)||"text"](te,S);return!le&&he&&he(),await new Promise((j,X)=>{b1(j,X,{data:ne,headers:kn.from(te.headers),status:te.status,statusText:te.statusText,config:S,request:G})})}catch(T){throw he&&he(),T&&T.name==="TypeError"&&/Load failed|fetch/i.test(T.message)?Object.assign(new Be("Network Error",Be.ERR_NETWORK,S,G,T&&T.response),{cause:T.cause||T}):Be.from(T,T&&T.code,S,G,T&&T.response)}}},wO=new Map,S1=t=>{let n=t&&t.env||{};const{fetch:r,Request:s,Response:i}=n,c=[s,i,r];let u=c.length,f=u,g,p,y=wO;for(;f--;)g=c[f],p=y.get(g),p===void 0&&y.set(g,p=f?new Map:xO(n)),y=p;return p};S1();const Uh={http:BT,xhr:hO,fetch:{get:S1}};W.forEach(Uh,(t,n)=>{if(t){try{Object.defineProperty(t,"name",{value:n})}catch{}Object.defineProperty(t,"adapterName",{value:n})}});const ax=t=>`- ${t}`,SO=t=>W.isFunction(t)||t===null||t===!1;function EO(t,n){t=W.isArray(t)?t:[t];const{length:r}=t;let s,i;const c={};for(let u=0;u<r;u++){s=t[u];let f;if(i=s,!SO(s)&&(i=Uh[(f=String(s)).toLowerCase()],i===void 0))throw new Be(`Unknown adapter '${f}'`);if(i&&(W.isFunction(i)||(i=i.get(n))))break;c[f||"#"+u]=i}if(!i){const u=Object.entries(c).map(([g,p])=>`adapter ${g} `+(p===!1?"is not supported by the environment":"is not available in the build"));let f=r?u.length>1?`since :+`+u.map(ax).join(`+`):" "+ax(u[0]):"as no adapter specified";throw new Be("There is no suitable adapter to dispatch the request "+f,"ERR_NOT_SUPPORT")}return i}const E1={getAdapter:EO,adapters:Uh};function _m(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ml(null,t)}function rx(t){return _m(t),t.headers=kn.from(t.headers),t.data=Em.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),E1.getAdapter(t.adapter||fl.adapter,t)(t).then(function(s){return _m(t),s.data=Em.call(t,t.transformResponse,s),s.headers=kn.from(s.headers),s},function(s){return y1(s)||(_m(t),s&&s.response&&(s.response.data=Em.call(t,t.transformResponse,s.response),s.response.headers=kn.from(s.response.headers))),Promise.reject(s)})}const _1="1.13.6",Du={};["object","boolean","number","function","string","symbol"].forEach((t,n)=>{Du[t]=function(s){return typeof s===t||"a"+(n<1?"n ":" ")+t}});const sx={};Du.transitional=function(n,r,s){function i(c,u){return"[Axios v"+_1+"] Transitional option '"+c+"'"+u+(s?". "+s:"")}return(c,u,f)=>{if(n===!1)throw new Be(i(u," has been removed"+(r?" in "+r:"")),Be.ERR_DEPRECATED);return r&&!sx[u]&&(sx[u]=!0,console.warn(i(u," has been deprecated since v"+r+" and will be removed in the near future"))),n?n(c,u,f):!0}};Du.spelling=function(n){return(r,s)=>(console.warn(`${s} is likely a misspelling of ${n}`),!0)};function _O(t,n,r){if(typeof t!="object")throw new Be("options must be an object",Be.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let i=s.length;for(;i-- >0;){const c=s[i],u=n[c];if(u){const f=t[c],g=f===void 0||u(f,c,t);if(g!==!0)throw new Be("option "+c+" must be "+g,Be.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Be("Unknown option "+c,Be.ERR_BAD_OPTION)}}const Kc={assertOptions:_O,validators:Du},ra=Kc.validators;let Ss=class{constructor(n){this.defaults=n||{},this.interceptors={request:new Yb,response:new Yb}}async request(n,r){try{return await this._request(n,r)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const c=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?c&&!String(s.stack).endsWith(c.replace(/^.+\n.+\n/,""))&&(s.stack+=`+`+c):s.stack=c}catch{}}throw s}}_request(n,r){typeof n=="string"?(r=r||{},r.url=n):r=n||{},r=Es(this.defaults,r);const{transitional:s,paramsSerializer:i,headers:c}=r;s!==void 0&&Kc.assertOptions(s,{silentJSONParsing:ra.transitional(ra.boolean),forcedJSONParsing:ra.transitional(ra.boolean),clarifyTimeoutError:ra.transitional(ra.boolean),legacyInterceptorReqResOrdering:ra.transitional(ra.boolean)},!1),i!=null&&(W.isFunction(i)?r.paramsSerializer={serialize:i}:Kc.assertOptions(i,{encode:ra.function,serialize:ra.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Kc.assertOptions(r,{baseUrl:ra.spelling("baseURL"),withXsrfToken:ra.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let u=c&&W.merge(c.common,c[r.method]);c&&W.forEach(["delete","get","head","post","put","patch","common"],S=>{delete c[S]}),r.headers=kn.concat(u,c);const f=[];let g=!0;this.interceptors.request.forEach(function(_){if(typeof _.runWhen=="function"&&_.runWhen(r)===!1)return;g=g&&_.synchronous;const E=r.transitional||zh;E&&E.legacyInterceptorReqResOrdering?f.unshift(_.fulfilled,_.rejected):f.push(_.fulfilled,_.rejected)});const p=[];this.interceptors.response.forEach(function(_){p.push(_.fulfilled,_.rejected)});let y,v=0,w;if(!g){const S=[rx.bind(this),void 0];for(S.unshift(...f),S.push(...p),w=S.length,y=Promise.resolve(r);v<w;)y=y.then(S[v++],S[v++]);return y}w=f.length;let C=r;for(;v<w;){const S=f[v++],_=f[v++];try{C=S(C)}catch(E){_.call(this,E);break}}try{y=rx.call(this,C)}catch(S){return Promise.reject(S)}for(v=0,w=p.length;v<w;)y=y.then(p[v++],p[v++]);return y}getUri(n){n=Es(this.defaults,n);const r=x1(n.baseURL,n.url,n.allowAbsoluteUrls);return g1(r,n.params,n.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(n){Ss.prototype[n]=function(r,s){return this.request(Es(s||{},{method:n,url:r,data:(s||{}).data}))}});W.forEach(["post","put","patch"],function(n){function r(s){return function(c,u,f){return this.request(Es(f||{},{method:n,headers:s?{"Content-Type":"multipart/form-data"}:{},url:c,data:u}))}}Ss.prototype[n]=r(),Ss.prototype[n+"Form"]=r(!0)});let CO=class C1{constructor(n){if(typeof n!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(c){r=c});const s=this;this.promise.then(i=>{if(!s._listeners)return;let c=s._listeners.length;for(;c-- >0;)s._listeners[c](i);s._listeners=null}),this.promise.then=i=>{let c;const u=new Promise(f=>{s.subscribe(f),c=f}).then(i);return u.cancel=function(){s.unsubscribe(c)},u},n(function(c,u,f){s.reason||(s.reason=new ml(c,u,f),r(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(n){if(this.reason){n(this.reason);return}this._listeners?this._listeners.push(n):this._listeners=[n]}unsubscribe(n){if(!this._listeners)return;const r=this._listeners.indexOf(n);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const n=new AbortController,r=s=>{n.abort(s)};return this.subscribe(r),n.signal.unsubscribe=()=>this.unsubscribe(r),n.signal}static source(){let n;return{token:new C1(function(i){n=i}),cancel:n}}};function NO(t){return function(r){return t.apply(null,r)}}function RO(t){return W.isObject(t)&&t.isAxiosError===!0}const nh={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(nh).forEach(([t,n])=>{nh[n]=t});function N1(t){const n=new Ss(t),r=s1(Ss.prototype.request,n);return W.extend(r,Ss.prototype,n,{allOwnKeys:!0}),W.extend(r,n,null,{allOwnKeys:!0}),r.create=function(i){return N1(Es(t,i))},r}const Bt=N1(fl);Bt.Axios=Ss;Bt.CanceledError=ml;Bt.CancelToken=CO;Bt.isCancel=y1;Bt.VERSION=_1;Bt.toFormData=Mu;Bt.AxiosError=Be;Bt.Cancel=Bt.CanceledError;Bt.all=function(n){return Promise.all(n)};Bt.spread=NO;Bt.isAxiosError=RO;Bt.mergeConfig=Es;Bt.AxiosHeaders=kn;Bt.formToJSON=t=>v1(W.isHTMLForm(t)?new FormData(t):t);Bt.getAdapter=E1.getAdapter;Bt.HttpStatusCode=nh;Bt.default=Bt;const{Axios:$5,AxiosError:G5,CanceledError:Y5,isCancel:Z5,CancelToken:X5,VERSION:K5,all:Q5,Cancel:W5,isAxiosError:J5,spread:eL,toFormData:tL,AxiosHeaders:nL,HttpStatusCode:aL,formToJSON:rL,getAdapter:sL,mergeConfig:oL}=Bt,hn=Bt.create({timeout:3e4,headers:{"Content-Type":"application/json"}});hn.interceptors.request.use(t=>{const n=localStorage.getItem("evolution-auth");if(n)try{const r=JSON.parse(n),{apiUrl:s,apiKey:i}=r.state||r;s&&!t.baseURL&&(t.baseURL=s),i&&!t.headers.has("apikey")&&t.headers.set("apikey",i)}catch(r){console.error("Error parsing auth data:",r)}return t},t=>Promise.reject(t));hn.interceptors.response.use(t=>t,t=>{var r,s,i,c,u;if(((r=t.response)==null?void 0:r.status)===401)return console.error("Unauthorized - clearing auth data"),localStorage.removeItem("evolution-auth"),window.location.href="/manager/login",Promise.reject(t);if(((s=t.response)==null?void 0:s.status)===403){const f=(i=t.response)==null?void 0:i.data;if((f==null?void 0:f.code)==="LICENSE_INVALID"||(f==null?void 0:f.code)==="LICENSE_EXPIRED"){console.error("License invalid - redirecting to login");const g=localStorage.getItem("evolution-auth");if(g)try{const p=JSON.parse(g),y=p.state||p;y.licenseState="unlicensed",p.state&&(p.state=y),localStorage.setItem("evolution-auth",JSON.stringify(p))}catch{}return window.location.href="/manager/login",Promise.reject(t)}}if(!t.response)return console.error("Network error:",t.message),Promise.reject({message:"Erro de conexão. Verifique sua internet e tente novamente.",originalError:t});const n=(c=t.response)!=null&&c.data?t.response.data.error||t.response.data.message||"Erro desconhecido":t.message;return console.error("API Error:",n),Promise.reject({message:n,status:(u=t.response)==null?void 0:u.status,originalError:t})});async function AO(t,n){const r=t?`${t}/license/status`:"/license/status",s={};return n&&(s.apikey=n),(await hn.get(r,{headers:s})).data}async function TO(t,n,r){const s=n?`${n}/license/register`:"/license/register",i={};return r&&(i.apikey=r),(await hn.get(s,{headers:i,params:{redirect_uri:t}})).data}async function OO(t,n,r){const s=n?`${n}/license/activate`:"/license/activate",i={};return r&&(i.apikey=r),(await hn.get(s,{headers:i,params:{code:t}})).data}const jO=r1()(XA(t=>({apiUrl:typeof window<"u"?window.location.origin:"http://localhost:8082",apiKey:"",isAuthenticated:!1,licenseState:"unchecked",login:async(n,r)=>{var s;try{const i=n.replace(/\/$/,"");if(((s=(await hn.get("/server/ok",{baseURL:i,headers:{apikey:r,"Cache-Control":"no-cache"},params:{t:Date.now()}})).data)==null?void 0:s.status)==="ok")t({apiUrl:i,apiKey:r,isAuthenticated:!0});else throw new Error("Falha ao conectar com a API")}catch(i){throw console.error("Login error:",i),new Error("Não foi possível conectar. Verifique a URL e API Key.")}},logout:()=>{localStorage.removeItem("evolution-auth"),t({apiUrl:typeof window<"u"?window.location.origin:"http://localhost:8082",apiKey:"",isAuthenticated:!1,licenseState:"unchecked"}),window.location.href="/manager/login"},setApiUrl:n=>{t({apiUrl:n.replace(/\/$/,"")})},setApiKey:n=>{t({apiKey:n})},setLicenseState:n=>{t({licenseState:n})},checkLicense:async(n,r)=>{try{const i=(await AO(n,r)).status==="active"?"licensed":"unlicensed";return t({licenseState:i}),i}catch(s){return console.error("License check error:",s),t({licenseState:"unlicensed"}),"unlicensed"}}}),{name:"evolution-auth",partialize:t=>({apiUrl:t.apiUrl,apiKey:t.apiKey,isAuthenticated:t.isAuthenticated,licenseState:t.licenseState})}));function zu(){const t=jO();return{isAuthenticated:t.isAuthenticated,apiUrl:t.apiUrl,apiKey:t.apiKey,licenseState:t.licenseState,login:t.login,logout:t.logout,setApiUrl:t.setApiUrl,setApiKey:t.setApiKey,setLicenseState:t.setLicenseState,checkLicense:t.checkLicense}}const R1=b.createContext(void 0);function kO({children:t}){const[n,r]=b.useState(()=>{if(typeof window>"u")return"light";const c=localStorage.getItem("evolution-theme");return c||(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")});b.useEffect(()=>{const c=window.document.documentElement;n==="dark"?c.classList.add("dark"):c.classList.remove("dark"),localStorage.setItem("evolution-theme",n)},[n]),b.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{localStorage.getItem("evolution-theme")||r(c.matches?"dark":"light")};return c.addEventListener("change",u),()=>c.removeEventListener("change",u)},[]);const s=()=>{r(c=>c==="light"?"dark":"light")},i=b.useMemo(()=>({theme:n,toggleTheme:s}),[n]);return h.jsx(R1.Provider,{value:i,children:t})}function MO(){const t=b.useContext(R1);if(t===void 0)throw new Error("useDarkMode deve ser usado dentro de um DarkModeProvider");return t}function DO(){const{logout:t}=zu(),{theme:n,toggleTheme:r}=MO(),s=()=>{t()};return h.jsxs("header",{className:"flex h-16 items-center justify-between border-b border-sidebar-border bg-sidebar px-0 py-3 shadow-sm",children:[h.jsx("div",{className:"w-56 flex items-center px-4"}),h.jsxs("div",{className:"flex items-center gap-2 px-4",children:[h.jsx("button",{onClick:r,className:"flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-200 dark:hover:bg-sidebar-accent",title:n==="dark"?"Modo claro":"Modo escuro",children:n==="dark"?h.jsx($R,{className:"h-4 w-4"}):h.jsx(AR,{className:"h-4 w-4"})}),h.jsxs("button",{onClick:s,className:"flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-200 dark:hover:bg-sidebar-accent",children:[h.jsx(_R,{className:"h-4 w-4"}),"Sair"]})]})]})}function zO({children:t}){return h.jsxs("div",{className:"flex h-screen bg-background",children:[h.jsx(IA,{}),h.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[h.jsx(DO,{}),h.jsx("main",{className:"flex-1 overflow-y-auto",children:t||h.jsx(MN,{})})]})]})}function LO(t,n){const r=b.createContext(n),s=c=>{const{children:u,...f}=c,g=b.useMemo(()=>f,Object.values(f));return h.jsx(r.Provider,{value:g,children:u})};s.displayName=t+"Provider";function i(c){const u=b.useContext(r);if(u)return u;if(n!==void 0)return n;throw new Error(`\`${c}\` must be used within \`${t}\``)}return[s,i]}function Ts(t,n=[]){let r=[];function s(c,u){const f=b.createContext(u),g=r.length;r=[...r,u];const p=v=>{var R;const{scope:w,children:C,...S}=v,_=((R=w==null?void 0:w[t])==null?void 0:R[g])||f,E=b.useMemo(()=>S,Object.values(S));return h.jsx(_.Provider,{value:E,children:C})};p.displayName=c+"Provider";function y(v,w){var _;const C=((_=w==null?void 0:w[t])==null?void 0:_[g])||f,S=b.useContext(C);if(S)return S;if(u!==void 0)return u;throw new Error(`\`${v}\` must be used within \`${c}\``)}return[p,y]}const i=()=>{const c=r.map(u=>b.createContext(u));return function(f){const g=(f==null?void 0:f[t])||c;return b.useMemo(()=>({[`__scope${t}`]:{...f,[t]:g}}),[f,g])}};return i.scopeName=t,[s,UO(i,...n)]}function UO(...t){const n=t[0];if(t.length===1)return n;const r=()=>{const s=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(c){const u=s.reduce((f,{useScope:g,scopeName:p})=>{const v=g(c)[`__scope${p}`];return{...f,...v}},{});return b.useMemo(()=>({[`__scope${n.scopeName}`]:u}),[u])}};return r.scopeName=n.scopeName,r}function ox(t,n){if(typeof t=="function")return t(n);t!=null&&(t.current=n)}function hl(...t){return n=>{let r=!1;const s=t.map(i=>{const c=ox(i,n);return!r&&typeof c=="function"&&(r=!0),c});if(r)return()=>{for(let i=0;i<s.length;i++){const c=s[i];typeof c=="function"?c():ox(t[i],null)}}}}function Wt(...t){return b.useCallback(hl(...t),t)}function Do(t){const n=BO(t),r=b.forwardRef((s,i)=>{const{children:c,...u}=s,f=b.Children.toArray(c),g=f.find(HO);if(g){const p=g.props.children,y=f.map(v=>v===g?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:v);return h.jsx(n,{...u,ref:i,children:b.isValidElement(p)?b.cloneElement(p,void 0,y):null})}return h.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}function BO(t){const n=b.forwardRef((r,s)=>{const{children:i,...c}=r;if(b.isValidElement(i)){const u=IO(i),f=VO(c,i.props);return i.type!==b.Fragment&&(f.ref=s?hl(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var PO=Symbol("radix.slottable");function HO(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===PO}function VO(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function IO(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function A1(t){const n=t+"CollectionProvider",[r,s]=Ts(n),[i,c]=r(n,{collectionRef:{current:null},itemMap:new Map}),u=_=>{const{scope:E,children:R}=_,k=ae.useRef(null),A=ae.useRef(new Map).current;return h.jsx(i,{scope:E,itemMap:A,collectionRef:k,children:R})};u.displayName=n;const f=t+"CollectionSlot",g=Do(f),p=ae.forwardRef((_,E)=>{const{scope:R,children:k}=_,A=c(f,R),D=Wt(E,A.collectionRef);return h.jsx(g,{ref:D,children:k})});p.displayName=f;const y=t+"CollectionItemSlot",v="data-radix-collection-item",w=Do(y),C=ae.forwardRef((_,E)=>{const{scope:R,children:k,...A}=_,D=ae.useRef(null),H=Wt(E,D),$=c(y,R);return ae.useEffect(()=>($.itemMap.set(D,{ref:D,...A}),()=>void $.itemMap.delete(D))),h.jsx(w,{[v]:"",ref:H,children:k})});C.displayName=y;function S(_){const E=c(t+"CollectionConsumer",_);return ae.useCallback(()=>{const k=E.collectionRef.current;if(!k)return[];const A=Array.from(k.querySelectorAll(`[${v}]`));return Array.from(E.itemMap.values()).sort(($,U)=>A.indexOf($.ref.current)-A.indexOf(U.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:u,Slot:p,ItemSlot:C},S,s]}function qe(t,n,{checkForDefaultPrevented:r=!0}={}){return function(i){if(t==null||t(i),r===!1||!i.defaultPrevented)return n==null?void 0:n(i)}}var Fr=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},qO=Nu[" useInsertionEffect ".trim().toString()]||Fr;function Bh({prop:t,defaultProp:n,onChange:r=()=>{},caller:s}){const[i,c,u]=FO({defaultProp:n,onChange:r}),f=t!==void 0,g=f?t:i;{const y=b.useRef(t!==void 0);b.useEffect(()=>{const v=y.current;v!==f&&console.warn(`${s} is changing from ${v?"controlled":"uncontrolled"} to ${f?"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.`),y.current=f},[f,s])}const p=b.useCallback(y=>{var v;if(f){const w=$O(y)?y(t):y;w!==t&&((v=u.current)==null||v.call(u,w))}else c(y)},[f,t,c,u]);return[g,p]}function FO({defaultProp:t,onChange:n}){const[r,s]=b.useState(t),i=b.useRef(r),c=b.useRef(n);return qO(()=>{c.current=n},[n]),b.useEffect(()=>{var u;i.current!==r&&((u=c.current)==null||u.call(c,r),i.current=r)},[r,i]),[r,s,c]}function $O(t){return typeof t=="function"}var GO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],kt=GO.reduce((t,n)=>{const r=Do(`Primitive.${n}`),s=b.forwardRef((i,c)=>{const{asChild:u,...f}=i,g=u?r:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{});function T1(t,n){t&&Ah.flushSync(()=>t.dispatchEvent(n))}function YO(t,n){return b.useReducer((r,s)=>n[r][s]??r,t)}var za=t=>{const{present:n,children:r}=t,s=ZO(n),i=typeof r=="function"?r({present:s.isPresent}):b.Children.only(r),c=Wt(s.ref,XO(i));return typeof r=="function"||s.isPresent?b.cloneElement(i,{ref:c}):null};za.displayName="Presence";function ZO(t){const[n,r]=b.useState(),s=b.useRef(null),i=b.useRef(t),c=b.useRef("none"),u=t?"mounted":"unmounted",[f,g]=YO(u,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{const p=Uc(s.current);c.current=f==="mounted"?p:"none"},[f]),Fr(()=>{const p=s.current,y=i.current;if(y!==t){const w=c.current,C=Uc(p);t?g("MOUNT"):C==="none"||(p==null?void 0:p.display)==="none"?g("UNMOUNT"):g(y&&w!==C?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,g]),Fr(()=>{if(n){let p;const y=n.ownerDocument.defaultView??window,v=C=>{const _=Uc(s.current).includes(CSS.escape(C.animationName));if(C.target===n&&_&&(g("ANIMATION_END"),!i.current)){const E=n.style.animationFillMode;n.style.animationFillMode="forwards",p=y.setTimeout(()=>{n.style.animationFillMode==="forwards"&&(n.style.animationFillMode=E)})}},w=C=>{C.target===n&&(c.current=Uc(s.current))};return n.addEventListener("animationstart",w),n.addEventListener("animationcancel",v),n.addEventListener("animationend",v),()=>{y.clearTimeout(p),n.removeEventListener("animationstart",w),n.removeEventListener("animationcancel",v),n.removeEventListener("animationend",v)}}else g("ANIMATION_END")},[n,g]),{isPresent:["mounted","unmountSuspended"].includes(f),ref:b.useCallback(p=>{s.current=p?getComputedStyle(p):null,r(p)},[])}}function Uc(t){return(t==null?void 0:t.animationName)||"none"}function XO(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var KO=Nu[" useId ".trim().toString()]||(()=>{}),QO=0;function To(t){const[n,r]=b.useState(KO());return Fr(()=>{r(s=>s??String(QO++))},[t]),t||(n?`radix-${n}`:"")}var WO=b.createContext(void 0);function O1(t){const n=b.useContext(WO);return t||n||"ltr"}/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const JO=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ej=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase()),ix=t=>{const n=ej(t);return n.charAt(0).toUpperCase()+n.slice(1)},j1=(...t)=>t.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim(),tj=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0};/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */var nj={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.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const aj=b.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:u,...f},g)=>b.createElement("svg",{ref:g,...nj,width:n,height:n,stroke:t,strokeWidth:s?Number(r)*24/Number(n):r,className:j1("lucide",i),...!c&&!tj(f)&&{"aria-hidden":"true"},...f},[...u.map(([p,y])=>b.createElement(p,y)),...Array.isArray(c)?c:[c]]));/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const rj=(t,n)=>{const r=b.forwardRef(({className:s,...i},c)=>b.createElement(aj,{ref:c,iconNode:n,className:j1(`lucide-${JO(ix(t))}`,`lucide-${t}`,s),...i}));return r.displayName=ix(t),r};/**+ * @license lucide-react v0.522.0 - ISC+ *+ * This source code is licensed under the ISC license.+ * See the LICENSE file in the root directory of this source tree.+ */const sj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],oj=rj("x",sj),lx=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,cx=Oh,Ph=(t,n)=>r=>{var s;if((n==null?void 0:n.variants)==null)return cx(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:c}=n,u=Object.keys(i).map(p=>{const y=r==null?void 0:r[p],v=c==null?void 0:c[p];if(y===null)return null;const w=lx(y)||lx(v);return i[p][w]}),f=r&&Object.entries(r).reduce((p,y)=>{let[v,w]=y;return w===void 0||(p[v]=w),p},{}),g=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((p,y)=>{let{class:v,className:w,...C}=y;return Object.entries(C).every(S=>{let[_,E]=S;return Array.isArray(E)?E.includes({...c,...f}[_]):{...c,...f}[_]===E})?[...p,v,w]:p},[]);return cx(t,u,g,r==null?void 0:r.class,r==null?void 0:r.className)};function sr(t){const n=b.useRef(t);return b.useEffect(()=>{n.current=t}),b.useMemo(()=>(...r)=>{var s;return(s=n.current)==null?void 0:s.call(n,...r)},[])}function ij(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t);b.useEffect(()=>{const s=i=>{i.key==="Escape"&&r(i)};return n.addEventListener("keydown",s,{capture:!0}),()=>n.removeEventListener("keydown",s,{capture:!0})},[r,n])}var lj="DismissableLayer",ah="dismissableLayer.update",cj="dismissableLayer.pointerDownOutside",uj="dismissableLayer.focusOutside",ux,k1=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Lu=b.forwardRef((t,n)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:c,onInteractOutside:u,onDismiss:f,...g}=t,p=b.useContext(k1),[y,v]=b.useState(null),w=(y==null?void 0:y.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,C]=b.useState({}),S=Wt(n,U=>v(U)),_=Array.from(p.layers),[E]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),R=_.indexOf(E),k=y?_.indexOf(y):-1,A=p.layersWithOutsidePointerEventsDisabled.size>0,D=k>=R,H=mj(U=>{const F=U.target,de=[...p.branches].some(fe=>fe.contains(F));!D||de||(i==null||i(U),u==null||u(U),U.defaultPrevented||f==null||f())},w),$=hj(U=>{const F=U.target;[...p.branches].some(fe=>fe.contains(F))||(c==null||c(U),u==null||u(U),U.defaultPrevented||f==null||f())},w);return ij(U=>{k===p.layers.size-1&&(s==null||s(U),!U.defaultPrevented&&f&&(U.preventDefault(),f()))},w),b.useEffect(()=>{if(y)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(ux=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),dx(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(w.body.style.pointerEvents=ux)}},[y,w,r,p]),b.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),dx())},[y,p]),b.useEffect(()=>{const U=()=>C({});return document.addEventListener(ah,U),()=>document.removeEventListener(ah,U)},[]),h.jsx(kt.div,{...g,ref:S,style:{pointerEvents:A?D?"auto":"none":void 0,...t.style},onFocusCapture:qe(t.onFocusCapture,$.onFocusCapture),onBlurCapture:qe(t.onBlurCapture,$.onBlurCapture),onPointerDownCapture:qe(t.onPointerDownCapture,H.onPointerDownCapture)})});Lu.displayName=lj;var dj="DismissableLayerBranch",fj=b.forwardRef((t,n)=>{const r=b.useContext(k1),s=b.useRef(null),i=Wt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return r.branches.add(c),()=>{r.branches.delete(c)}},[r.branches]),h.jsx(kt.div,{...t,ref:i})});fj.displayName=dj;function mj(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t),s=b.useRef(!1),i=b.useRef(()=>{});return b.useEffect(()=>{const c=f=>{if(f.target&&!s.current){let g=function(){M1(cj,r,p,{discrete:!0})};const p={originalEvent:f};f.pointerType==="touch"?(n.removeEventListener("click",i.current),i.current=g,n.addEventListener("click",i.current,{once:!0})):g()}else n.removeEventListener("click",i.current);s.current=!1},u=window.setTimeout(()=>{n.addEventListener("pointerdown",c)},0);return()=>{window.clearTimeout(u),n.removeEventListener("pointerdown",c),n.removeEventListener("click",i.current)}},[n,r]),{onPointerDownCapture:()=>s.current=!0}}function hj(t,n=globalThis==null?void 0:globalThis.document){const r=sr(t),s=b.useRef(!1);return b.useEffect(()=>{const i=c=>{c.target&&!s.current&&M1(uj,r,{originalEvent:c},{discrete:!1})};return n.addEventListener("focusin",i),()=>n.removeEventListener("focusin",i)},[n,r]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function dx(){const t=new CustomEvent(ah);document.dispatchEvent(t)}function M1(t,n,r,{discrete:s}){const i=r.originalEvent.target,c=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});n&&i.addEventListener(t,n,{once:!0}),s?T1(i,c):i.dispatchEvent(c)}var Cm="focusScope.autoFocusOnMount",Nm="focusScope.autoFocusOnUnmount",fx={bubbles:!1,cancelable:!0},pj="FocusScope",Uu=b.forwardRef((t,n)=>{const{loop:r=!1,trapped:s=!1,onMountAutoFocus:i,onUnmountAutoFocus:c,...u}=t,[f,g]=b.useState(null),p=sr(i),y=sr(c),v=b.useRef(null),w=Wt(n,_=>g(_)),C=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(s){let _=function(A){if(C.paused||!f)return;const D=A.target;f.contains(D)?v.current=D:Br(v.current,{select:!0})},E=function(A){if(C.paused||!f)return;const D=A.relatedTarget;D!==null&&(f.contains(D)||Br(v.current,{select:!0}))},R=function(A){if(document.activeElement===document.body)for(const H of A)H.removedNodes.length>0&&Br(f)};document.addEventListener("focusin",_),document.addEventListener("focusout",E);const k=new MutationObserver(R);return f&&k.observe(f,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",E),k.disconnect()}}},[s,f,C.paused]),b.useEffect(()=>{if(f){hx.add(C);const _=document.activeElement;if(!f.contains(_)){const R=new CustomEvent(Cm,fx);f.addEventListener(Cm,p),f.dispatchEvent(R),R.defaultPrevented||(gj(wj(D1(f)),{select:!0}),document.activeElement===_&&Br(f))}return()=>{f.removeEventListener(Cm,p),setTimeout(()=>{const R=new CustomEvent(Nm,fx);f.addEventListener(Nm,y),f.dispatchEvent(R),R.defaultPrevented||Br(_??document.body,{select:!0}),f.removeEventListener(Nm,y),hx.remove(C)},0)}}},[f,p,y,C]);const S=b.useCallback(_=>{if(!r&&!s||C.paused)return;const E=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,R=document.activeElement;if(E&&R){const k=_.currentTarget,[A,D]=vj(k);A&&D?!_.shiftKey&&R===D?(_.preventDefault(),r&&Br(A,{select:!0})):_.shiftKey&&R===A&&(_.preventDefault(),r&&Br(D,{select:!0})):R===k&&_.preventDefault()}},[r,s,C.paused]);return h.jsx(kt.div,{tabIndex:-1,...u,ref:w,onKeyDown:S})});Uu.displayName=pj;function gj(t,{select:n=!1}={}){const r=document.activeElement;for(const s of t)if(Br(s,{select:n}),document.activeElement!==r)return}function vj(t){const n=D1(t),r=mx(n,t),s=mx(n.reverse(),t);return[r,s]}function D1(t){const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const i=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||i?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)n.push(r.currentNode);return n}function mx(t,n){for(const r of t)if(!yj(r,{upTo:n}))return r}function yj(t,{upTo:n}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(n!==void 0&&t===n)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function bj(t){return t instanceof HTMLInputElement&&"select"in t}function Br(t,{select:n=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&bj(t)&&n&&t.select()}}var hx=xj();function xj(){let t=[];return{add(n){const r=t[0];n!==r&&(r==null||r.pause()),t=px(t,n),t.unshift(n)},remove(n){var r;t=px(t,n),(r=t[0])==null||r.resume()}}}function px(t,n){const r=[...t],s=r.indexOf(n);return s!==-1&&r.splice(s,1),r}function wj(t){return t.filter(n=>n.tagName!=="A")}var Sj="Portal",Bu=b.forwardRef((t,n)=>{var f;const{container:r,...s}=t,[i,c]=b.useState(!1);Fr(()=>c(!0),[]);const u=r||i&&((f=globalThis==null?void 0:globalThis.document)==null?void 0:f.body);return u?B0.createPortal(h.jsx(kt.div,{...s,ref:n}),u):null});Bu.displayName=Sj;var Rm=0;function Hh(){b.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??gx()),document.body.insertAdjacentElement("beforeend",t[1]??gx()),Rm++,()=>{Rm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(n=>n.remove()),Rm--}},[])}function gx(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Aa=function(){return Aa=Object.assign||function(n){for(var r,s=1,i=arguments.length;s<i;s++){r=arguments[s];for(var c in r)Object.prototype.hasOwnProperty.call(r,c)&&(n[c]=r[c])}return n},Aa.apply(this,arguments)};function z1(t,n){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&n.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(t);i<s.length;i++)n.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(t,s[i])&&(r[s[i]]=t[s[i]]);return r}function Ej(t,n,r){if(r||arguments.length===2)for(var s=0,i=n.length,c;s<i;s++)(c||!(s in n))&&(c||(c=Array.prototype.slice.call(n,0,s)),c[s]=n[s]);return t.concat(c||Array.prototype.slice.call(n))}var Qc="right-scroll-bar-position",Wc="width-before-scroll-bar",_j="with-scroll-bars-hidden",Cj="--removed-body-scroll-bar-size";function Am(t,n){return typeof t=="function"?t(n):t&&(t.current=n),t}function Nj(t,n){var r=b.useState(function(){return{value:t,callback:n,facade:{get current(){return r.value},set current(s){var i=r.value;i!==s&&(r.value=s,r.callback(s,i))}}}})[0];return r.callback=n,r.facade}var Rj=typeof window<"u"?b.useLayoutEffect:b.useEffect,vx=new WeakMap;function Aj(t,n){var r=Nj(null,function(s){return t.forEach(function(i){return Am(i,s)})});return Rj(function(){var s=vx.get(r);if(s){var i=new Set(s),c=new Set(t),u=r.current;i.forEach(function(f){c.has(f)||Am(f,null)}),c.forEach(function(f){i.has(f)||Am(f,u)})}vx.set(r,t)},[t]),r}function Tj(t){return t}function Oj(t,n){n===void 0&&(n=Tj);var r=[],s=!1,i={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:t},useMedium:function(c){var u=n(c,s);return r.push(u),function(){r=r.filter(function(f){return f!==u})}},assignSyncMedium:function(c){for(s=!0;r.length;){var u=r;r=[],u.forEach(c)}r={push:function(f){return c(f)},filter:function(){return r}}},assignMedium:function(c){s=!0;var u=[];if(r.length){var f=r;r=[],f.forEach(c),u=r}var g=function(){var y=u;u=[],y.forEach(c)},p=function(){return Promise.resolve().then(g)};p(),r={push:function(y){u.push(y),p()},filter:function(y){return u=u.filter(y),r}}}};return i}function jj(t){t===void 0&&(t={});var n=Oj(null);return n.options=Aa({async:!0,ssr:!1},t),n}var L1=function(t){var n=t.sideCar,r=z1(t,["sideCar"]);if(!n)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=n.read();if(!s)throw new Error("Sidecar medium not found");return b.createElement(s,Aa({},r))};L1.isSideCarExport=!0;function kj(t,n){return t.useMedium(n),L1}var U1=jj(),Tm=function(){},Pu=b.forwardRef(function(t,n){var r=b.useRef(null),s=b.useState({onScrollCapture:Tm,onWheelCapture:Tm,onTouchMoveCapture:Tm}),i=s[0],c=s[1],u=t.forwardProps,f=t.children,g=t.className,p=t.removeScrollBar,y=t.enabled,v=t.shards,w=t.sideCar,C=t.noRelative,S=t.noIsolation,_=t.inert,E=t.allowPinchZoom,R=t.as,k=R===void 0?"div":R,A=t.gapMode,D=z1(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),H=w,$=Aj([r,n]),U=Aa(Aa({},D),i);return b.createElement(b.Fragment,null,y&&b.createElement(H,{sideCar:U1,removeScrollBar:p,shards:v,noRelative:C,noIsolation:S,inert:_,setCallbacks:c,allowPinchZoom:!!E,lockRef:r,gapMode:A}),u?b.cloneElement(b.Children.only(f),Aa(Aa({},U),{ref:$})):b.createElement(k,Aa({},U,{className:g,ref:$}),f))});Pu.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Pu.classNames={fullWidth:Wc,zeroRight:Qc};var Mj=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Dj(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var n=Mj();return n&&t.setAttribute("nonce",n),t}function zj(t,n){t.styleSheet?t.styleSheet.cssText=n:t.appendChild(document.createTextNode(n))}function Lj(t){var n=document.head||document.getElementsByTagName("head")[0];n.appendChild(t)}var Uj=function(){var t=0,n=null;return{add:function(r){t==0&&(n=Dj())&&(zj(n,r),Lj(n)),t++},remove:function(){t--,!t&&n&&(n.parentNode&&n.parentNode.removeChild(n),n=null)}}},Bj=function(){var t=Uj();return function(n,r){b.useEffect(function(){return t.add(n),function(){t.remove()}},[n&&r])}},B1=function(){var t=Bj(),n=function(r){var s=r.styles,i=r.dynamic;return t(s,i),null};return n},Pj={left:0,top:0,right:0,gap:0},Om=function(t){return parseInt(t||"",10)||0},Hj=function(t){var n=window.getComputedStyle(document.body),r=n[t==="padding"?"paddingLeft":"marginLeft"],s=n[t==="padding"?"paddingTop":"marginTop"],i=n[t==="padding"?"paddingRight":"marginRight"];return[Om(r),Om(s),Om(i)]},Vj=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return Pj;var n=Hj(t),r=document.documentElement.clientWidth,s=window.innerWidth;return{left:n[0],top:n[1],right:n[2],gap:Math.max(0,s-r+n[2]-n[0])}},Ij=B1(),Oo="data-scroll-locked",qj=function(t,n,r,s){var i=t.left,c=t.top,u=t.right,f=t.gap;return r===void 0&&(r="margin"),`+ .`.concat(_j,` {+ overflow: hidden `).concat(s,`;+ padding-right: `).concat(f,"px ").concat(s,`;+ }+ body[`).concat(Oo,`] {+ overflow: hidden `).concat(s,`;+ overscroll-behavior: contain;+ `).concat([n&&"position: relative ".concat(s,";"),r==="margin"&&`+ padding-left: `.concat(i,`px;+ padding-top: `).concat(c,`px;+ padding-right: `).concat(u,`px;+ margin-left:0;+ margin-top:0;+ margin-right: `).concat(f,"px ").concat(s,`;+ `),r==="padding"&&"padding-right: ".concat(f,"px ").concat(s,";")].filter(Boolean).join(""),`+ }++ .`).concat(Qc,` {+ right: `).concat(f,"px ").concat(s,`;+ }++ .`).concat(Wc,` {+ margin-right: `).concat(f,"px ").concat(s,`;+ }++ .`).concat(Qc," .").concat(Qc,` {+ right: 0 `).concat(s,`;+ }++ .`).concat(Wc," .").concat(Wc,` {+ margin-right: 0 `).concat(s,`;+ }++ body[`).concat(Oo,`] {+ `).concat(Cj,": ").concat(f,`px;+ }+`)},yx=function(){var t=parseInt(document.body.getAttribute(Oo)||"0",10);return isFinite(t)?t:0},Fj=function(){b.useEffect(function(){return document.body.setAttribute(Oo,(yx()+1).toString()),function(){var t=yx()-1;t<=0?document.body.removeAttribute(Oo):document.body.setAttribute(Oo,t.toString())}},[])},$j=function(t){var n=t.noRelative,r=t.noImportant,s=t.gapMode,i=s===void 0?"margin":s;Fj();var c=b.useMemo(function(){return Vj(i)},[i]);return b.createElement(Ij,{styles:qj(c,!n,i,r?"":"!important")})},rh=!1;if(typeof window<"u")try{var Bc=Object.defineProperty({},"passive",{get:function(){return rh=!0,!0}});window.addEventListener("test",Bc,Bc),window.removeEventListener("test",Bc,Bc)}catch{rh=!1}var bo=rh?{passive:!1}:!1,Gj=function(t){return t.tagName==="TEXTAREA"},P1=function(t,n){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[n]!=="hidden"&&!(r.overflowY===r.overflowX&&!Gj(t)&&r[n]==="visible")},Yj=function(t){return P1(t,"overflowY")},Zj=function(t){return P1(t,"overflowX")},bx=function(t,n){var r=n.ownerDocument,s=n;do{typeof ShadowRoot<"u"&&s instanceof ShadowRoot&&(s=s.host);var i=H1(t,s);if(i){var c=V1(t,s),u=c[1],f=c[2];if(u>f)return!0}s=s.parentNode}while(s&&s!==r.body);return!1},Xj=function(t){var n=t.scrollTop,r=t.scrollHeight,s=t.clientHeight;return[n,r,s]},Kj=function(t){var n=t.scrollLeft,r=t.scrollWidth,s=t.clientWidth;return[n,r,s]},H1=function(t,n){return t==="v"?Yj(n):Zj(n)},V1=function(t,n){return t==="v"?Xj(n):Kj(n)},Qj=function(t,n){return t==="h"&&n==="rtl"?-1:1},Wj=function(t,n,r,s,i){var c=Qj(t,window.getComputedStyle(n).direction),u=c*s,f=r.target,g=n.contains(f),p=!1,y=u>0,v=0,w=0;do{if(!f)break;var C=V1(t,f),S=C[0],_=C[1],E=C[2],R=_-E-c*S;(S||R)&&H1(t,f)&&(v+=R,w+=S);var k=f.parentNode;f=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!g&&f!==document.body||g&&(n.contains(f)||n===f));return(y&&Math.abs(v)<1||!y&&Math.abs(w)<1)&&(p=!0),p},Pc=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},xx=function(t){return[t.deltaX,t.deltaY]},wx=function(t){return t&&"current"in t?t.current:t},Jj=function(t,n){return t[0]===n[0]&&t[1]===n[1]},ek=function(t){return`+ .block-interactivity-`.concat(t,` {pointer-events: none;}+ .allow-interactivity-`).concat(t,` {pointer-events: all;}+`)},tk=0,xo=[];function nk(t){var n=b.useRef([]),r=b.useRef([0,0]),s=b.useRef(),i=b.useState(tk++)[0],c=b.useState(B1)[0],u=b.useRef(t);b.useEffect(function(){u.current=t},[t]),b.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var _=Ej([t.lockRef.current],(t.shards||[]).map(wx),!0).filter(Boolean);return _.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),_.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var f=b.useCallback(function(_,E){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!u.current.allowPinchZoom;var R=Pc(_),k=r.current,A="deltaX"in _?_.deltaX:k[0]-R[0],D="deltaY"in _?_.deltaY:k[1]-R[1],H,$=_.target,U=Math.abs(A)>Math.abs(D)?"h":"v";if("touches"in _&&U==="h"&&$.type==="range")return!1;var F=window.getSelection(),de=F&&F.anchorNode,fe=de?de===$||de.contains($):!1;if(fe)return!1;var me=bx(U,$);if(!me)return!0;if(me?H=U:(H=U==="v"?"h":"v",me=bx(U,$)),!me)return!1;if(!s.current&&"changedTouches"in _&&(A||D)&&(s.current=H),!H)return!0;var se=s.current||H;return Wj(se,E,_,se==="h"?A:D)},[]),g=b.useCallback(function(_){var E=_;if(!(!xo.length||xo[xo.length-1]!==c)){var R="deltaY"in E?xx(E):Pc(E),k=n.current.filter(function(H){return H.name===E.type&&(H.target===E.target||E.target===H.shadowParent)&&Jj(H.delta,R)})[0];if(k&&k.should){E.cancelable&&E.preventDefault();return}if(!k){var A=(u.current.shards||[]).map(wx).filter(Boolean).filter(function(H){return H.contains(E.target)}),D=A.length>0?f(E,A[0]):!u.current.noIsolation;D&&E.cancelable&&E.preventDefault()}}},[]),p=b.useCallback(function(_,E,R,k){var A={name:_,delta:E,target:R,should:k,shadowParent:ak(R)};n.current.push(A),setTimeout(function(){n.current=n.current.filter(function(D){return D!==A})},1)},[]),y=b.useCallback(function(_){r.current=Pc(_),s.current=void 0},[]),v=b.useCallback(function(_){p(_.type,xx(_),_.target,f(_,t.lockRef.current))},[]),w=b.useCallback(function(_){p(_.type,Pc(_),_.target,f(_,t.lockRef.current))},[]);b.useEffect(function(){return xo.push(c),t.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:w}),document.addEventListener("wheel",g,bo),document.addEventListener("touchmove",g,bo),document.addEventListener("touchstart",y,bo),function(){xo=xo.filter(function(_){return _!==c}),document.removeEventListener("wheel",g,bo),document.removeEventListener("touchmove",g,bo),document.removeEventListener("touchstart",y,bo)}},[]);var C=t.removeScrollBar,S=t.inert;return b.createElement(b.Fragment,null,S?b.createElement(c,{styles:ek(i)}):null,C?b.createElement($j,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function ak(t){for(var n=null;t!==null;)t instanceof ShadowRoot&&(n=t.host,t=t.host),t=t.parentNode;return n}const rk=kj(U1,nk);var Hu=b.forwardRef(function(t,n){return b.createElement(Pu,Aa({},t,{ref:n,sideCar:rk}))});Hu.classNames=Pu.classNames;var sk=function(t){if(typeof document>"u")return null;var n=Array.isArray(t)?t[0]:t;return n.ownerDocument.body},wo=new WeakMap,Hc=new WeakMap,Vc={},jm=0,I1=function(t){return t&&(t.host||I1(t.parentNode))},ok=function(t,n){return n.map(function(r){if(t.contains(r))return r;var s=I1(r);return s&&t.contains(s)?s:(console.error("aria-hidden",r,"in not contained inside",t,". Doing nothing"),null)}).filter(function(r){return!!r})},ik=function(t,n,r,s){var i=ok(n,Array.isArray(t)?t:[t]);Vc[r]||(Vc[r]=new WeakMap);var c=Vc[r],u=[],f=new Set,g=new Set(i),p=function(v){!v||f.has(v)||(f.add(v),p(v.parentNode))};i.forEach(p);var y=function(v){!v||g.has(v)||Array.prototype.forEach.call(v.children,function(w){if(f.has(w))y(w);else try{var C=w.getAttribute(s),S=C!==null&&C!=="false",_=(wo.get(w)||0)+1,E=(c.get(w)||0)+1;wo.set(w,_),c.set(w,E),u.push(w),_===1&&S&&Hc.set(w,!0),E===1&&w.setAttribute(r,"true"),S||w.setAttribute(s,"true")}catch(R){console.error("aria-hidden: cannot operate on ",w,R)}})};return y(n),f.clear(),jm++,function(){u.forEach(function(v){var w=wo.get(v)-1,C=c.get(v)-1;wo.set(v,w),c.set(v,C),w||(Hc.has(v)||v.removeAttribute(s),Hc.delete(v)),C||v.removeAttribute(r)}),jm--,jm||(wo=new WeakMap,wo=new WeakMap,Hc=new WeakMap,Vc={})}},Vh=function(t,n,r){r===void 0&&(r="data-aria-hidden");var s=Array.from(Array.isArray(t)?t:[t]),i=sk(t);return i?(s.push.apply(s,Array.from(i.querySelectorAll("[aria-live], script"))),ik(s,i,r,"aria-hidden")):function(){return null}},Vu="Dialog",[q1]=Ts(Vu),[lk,ba]=q1(Vu),F1=t=>{const{__scopeDialog:n,children:r,open:s,defaultOpen:i,onOpenChange:c,modal:u=!0}=t,f=b.useRef(null),g=b.useRef(null),[p,y]=Bh({prop:s,defaultProp:i??!1,onChange:c,caller:Vu});return h.jsx(lk,{scope:n,triggerRef:f,contentRef:g,contentId:To(),titleId:To(),descriptionId:To(),open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(v=>!v),[y]),modal:u,children:r})};F1.displayName=Vu;var $1="DialogTrigger",ck=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ba($1,r),c=Wt(n,i.triggerRef);return h.jsx(kt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Fh(i.open),...s,ref:c,onClick:qe(t.onClick,i.onOpenToggle)})});ck.displayName=$1;var Ih="DialogPortal",[uk,G1]=q1(Ih,{forceMount:void 0}),Y1=t=>{const{__scopeDialog:n,forceMount:r,children:s,container:i}=t,c=ba(Ih,n);return h.jsx(uk,{scope:n,forceMount:r,children:b.Children.map(s,u=>h.jsx(za,{present:r||c.open,children:h.jsx(Bu,{asChild:!0,container:i,children:u})}))})};Y1.displayName=Ih;var au="DialogOverlay",Z1=b.forwardRef((t,n)=>{const r=G1(au,t.__scopeDialog),{forceMount:s=r.forceMount,...i}=t,c=ba(au,t.__scopeDialog);return c.modal?h.jsx(za,{present:s||c.open,children:h.jsx(fk,{...i,ref:n})}):null});Z1.displayName=au;var dk=Do("DialogOverlay.RemoveScroll"),fk=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ba(au,r);return h.jsx(Hu,{as:dk,allowPinchZoom:!0,shards:[i.contentRef],children:h.jsx(kt.div,{"data-state":Fh(i.open),...s,ref:n,style:{pointerEvents:"auto",...s.style}})})}),_s="DialogContent",X1=b.forwardRef((t,n)=>{const r=G1(_s,t.__scopeDialog),{forceMount:s=r.forceMount,...i}=t,c=ba(_s,t.__scopeDialog);return h.jsx(za,{present:s||c.open,children:c.modal?h.jsx(mk,{...i,ref:n}):h.jsx(hk,{...i,ref:n})})});X1.displayName=_s;var mk=b.forwardRef((t,n)=>{const r=ba(_s,t.__scopeDialog),s=b.useRef(null),i=Wt(n,r.contentRef,s);return b.useEffect(()=>{const c=s.current;if(c)return Vh(c)},[]),h.jsx(K1,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:qe(t.onCloseAutoFocus,c=>{var u;c.preventDefault(),(u=r.triggerRef.current)==null||u.focus()}),onPointerDownOutside:qe(t.onPointerDownOutside,c=>{const u=c.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0;(u.button===2||f)&&c.preventDefault()}),onFocusOutside:qe(t.onFocusOutside,c=>c.preventDefault())})}),hk=b.forwardRef((t,n)=>{const r=ba(_s,t.__scopeDialog),s=b.useRef(!1),i=b.useRef(!1);return h.jsx(K1,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var u,f;(u=t.onCloseAutoFocus)==null||u.call(t,c),c.defaultPrevented||(s.current||(f=r.triggerRef.current)==null||f.focus(),c.preventDefault()),s.current=!1,i.current=!1},onInteractOutside:c=>{var g,p;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(s.current=!0,c.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=c.target;((p=r.triggerRef.current)==null?void 0:p.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),K1=b.forwardRef((t,n)=>{const{__scopeDialog:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,...u}=t,f=ba(_s,r),g=b.useRef(null),p=Wt(n,g);return Hh(),h.jsxs(h.Fragment,{children:[h.jsx(Uu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:h.jsx(Lu,{role:"dialog",id:f.contentId,"aria-describedby":f.descriptionId,"aria-labelledby":f.titleId,"data-state":Fh(f.open),...u,ref:p,onDismiss:()=>f.onOpenChange(!1)})}),h.jsxs(h.Fragment,{children:[h.jsx(pk,{titleId:f.titleId}),h.jsx(vk,{contentRef:g,descriptionId:f.descriptionId})]})]})}),qh="DialogTitle",Q1=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ba(qh,r);return h.jsx(kt.h2,{id:i.titleId,...s,ref:n})});Q1.displayName=qh;var W1="DialogDescription",J1=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ba(W1,r);return h.jsx(kt.p,{id:i.descriptionId,...s,ref:n})});J1.displayName=W1;var ew="DialogClose",tw=b.forwardRef((t,n)=>{const{__scopeDialog:r,...s}=t,i=ba(ew,r);return h.jsx(kt.button,{type:"button",...s,ref:n,onClick:qe(t.onClick,()=>i.onOpenChange(!1))})});tw.displayName=ew;function Fh(t){return t?"open":"closed"}var nw="DialogTitleWarning",[iL,aw]=LO(nw,{contentName:_s,titleName:qh,docsSlug:"dialog"}),pk=({titleId:t})=>{const n=aw(nw),r=`\`${n.contentName}\` requires a \`${n.titleName}\` for the component to be accessible for screen reader users.++If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component.++For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return b.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},gk="DialogDescriptionWarning",vk=({contentRef:t,descriptionId:n})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${aw(gk).contentName}}.`;return b.useEffect(()=>{var c;const i=(c=t.current)==null?void 0:c.getAttribute("aria-describedby");n&&i&&(document.getElementById(n)||console.warn(s))},[s,t,n]),null},yk=F1,bk=Y1,rw=Z1,sw=X1,xk=Q1,wk=J1,Sk=tw,Ek=Symbol.for("react.lazy"),ru=Nu[" use ".trim().toString()];function _k(t){return typeof t=="object"&&t!==null&&"then"in t}function ow(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Ek&&"_payload"in t&&_k(t._payload)}function iw(t){const n=Ck(t),r=b.forwardRef((s,i)=>{let{children:c,...u}=s;ow(c)&&typeof ru=="function"&&(c=ru(c._payload));const f=b.Children.toArray(c),g=f.find(Rk);if(g){const p=g.props.children,y=f.map(v=>v===g?b.Children.count(p)>1?b.Children.only(null):b.isValidElement(p)?p.props.children:null:v);return h.jsx(n,{...u,ref:i,children:b.isValidElement(p)?b.cloneElement(p,void 0,y):null})}return h.jsx(n,{...u,ref:i,children:c})});return r.displayName=`${t}.Slot`,r}var lw=iw("Slot");function Ck(t){const n=b.forwardRef((r,s)=>{let{children:i,...c}=r;if(ow(i)&&typeof ru=="function"&&(i=ru(i._payload)),b.isValidElement(i)){const u=Tk(i),f=Ak(c,i.props);return i.type!==b.Fragment&&(f.ref=s?hl(s,u):u),b.cloneElement(i,f)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${t}.SlotClone`,n}var Nk=Symbol("radix.slottable");function Rk(t){return b.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Nk}function Ak(t,n){const r={...n};for(const s in n){const i=t[s],c=n[s];/^on[A-Z]/.test(s)?i&&c?r[s]=(...f)=>{const g=c(...f);return i(...f),g}:i&&(r[s]=i):s==="style"?r[s]={...i,...c}:s==="className"&&(r[s]=[i,c].filter(Boolean).join(" "))}return{...t,...r}}function Tk(t){var s,i;let n=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,r=n&&"isReactWarning"in n&&n.isReactWarning;return r?t.ref:(n=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=n&&"isReactWarning"in n&&n.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var Ok=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],jk=Ok.reduce((t,n)=>{const r=iw(`Primitive.${n}`),s=b.forwardRef((i,c)=>{const{asChild:u,...f}=i,g=u?r:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),h.jsx(g,{...f,ref:c})});return s.displayName=`Primitive.${n}`,{...t,[n]:s}},{});function kk(t){const[n,r]=b.useState(void 0);return Fr(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const s=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const c=i[0];let u,f;if("borderBoxSize"in c){const g=c.borderBoxSize,p=Array.isArray(g)?g[0]:g;u=p.inlineSize,f=p.blockSize}else u=t.offsetWidth,f=t.offsetHeight;r({width:u,height:f})});return s.observe(t,{box:"border-box"}),()=>s.unobserve(t)}else r(void 0)},[t]),n}const Mk=["top","right","bottom","left"],$r=Math.min,In=Math.max,su=Math.round,Ic=Math.floor,ka=t=>({x:t,y:t}),Dk={left:"right",right:"left",bottom:"top",top:"bottom"};function sh(t,n,r){return In(t,$r(n,r))}function or(t,n){return typeof t=="function"?t(n):t}function ir(t){return t.split("-")[0]}function Yo(t){return t.split("-")[1]}function $h(t){return t==="x"?"y":"x"}function Gh(t){return t==="y"?"height":"width"}function Oa(t){const n=t[0];return n==="t"||n==="b"?"y":"x"}function Yh(t){return $h(Oa(t))}function zk(t,n,r){r===void 0&&(r=!1);const s=Yo(t),i=Yh(t),c=Gh(i);let u=i==="x"?s===(r?"end":"start")?"right":"left":s==="start"?"bottom":"top";return n.reference[c]>n.floating[c]&&(u=ou(u)),[u,ou(u)]}function Lk(t){const n=ou(t);return[oh(t),n,oh(n)]}function oh(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const Sx=["left","right"],Ex=["right","left"],Uk=["top","bottom"],Bk=["bottom","top"];function Pk(t,n,r){switch(t){case"top":case"bottom":return r?n?Ex:Sx:n?Sx:Ex;case"left":case"right":return n?Uk:Bk;default:return[]}}function Hk(t,n,r,s){const i=Yo(t);let c=Pk(ir(t),r==="start",s);return i&&(c=c.map(u=>u+"-"+i),n&&(c=c.concat(c.map(oh)))),c}function ou(t){const n=ir(t);return Dk[n]+t.slice(n.length)}function Vk(t){return{top:0,right:0,bottom:0,left:0,...t}}function cw(t){return typeof t!="number"?Vk(t):{top:t,right:t,bottom:t,left:t}}function iu(t){const{x:n,y:r,width:s,height:i}=t;return{width:s,height:i,top:r,left:n,right:n+s,bottom:r+i,x:n,y:r}}function _x(t,n,r){let{reference:s,floating:i}=t;const c=Oa(n),u=Yh(n),f=Gh(u),g=ir(n),p=c==="y",y=s.x+s.width/2-i.width/2,v=s.y+s.height/2-i.height/2,w=s[f]/2-i[f]/2;let C;switch(g){case"top":C={x:y,y:s.y-i.height};break;case"bottom":C={x:y,y:s.y+s.height};break;case"right":C={x:s.x+s.width,y:v};break;case"left":C={x:s.x-i.width,y:v};break;default:C={x:s.x,y:s.y}}switch(Yo(n)){case"start":C[u]-=w*(r&&p?-1:1);break;case"end":C[u]+=w*(r&&p?-1:1);break}return C}async function Ik(t,n){var r;n===void 0&&(n={});const{x:s,y:i,platform:c,rects:u,elements:f,strategy:g}=t,{boundary:p="clippingAncestors",rootBoundary:y="viewport",elementContext:v="floating",altBoundary:w=!1,padding:C=0}=or(n,t),S=cw(C),E=f[w?v==="floating"?"reference":"floating":v],R=iu(await c.getClippingRect({element:(r=await(c.isElement==null?void 0:c.isElement(E)))==null||r?E:E.contextElement||await(c.getDocumentElement==null?void 0:c.getDocumentElement(f.floating)),boundary:p,rootBoundary:y,strategy:g})),k=v==="floating"?{x:s,y:i,width:u.floating.width,height:u.floating.height}:u.reference,A=await(c.getOffsetParent==null?void 0:c.getOffsetParent(f.floating)),D=await(c.isElement==null?void 0:c.isElement(A))?await(c.getScale==null?void 0:c.getScale(A))||{x:1,y:1}:{x:1,y:1},H=iu(c.convertOffsetParentRelativeRectToViewportRelativeRect?await c.convertOffsetParentRelativeRectToViewportRelativeRect({elements:f,rect:k,offsetParent:A,strategy:g}):k);return{top:(R.top-H.top+S.top)/D.y,bottom:(H.bottom-R.bottom+S.bottom)/D.y,left:(R.left-H.left+S.left)/D.x,right:(H.right-R.right+S.right)/D.x}}const qk=50,Fk=async(t,n,r)=>{const{placement:s="bottom",strategy:i="absolute",middleware:c=[],platform:u}=r,f=u.detectOverflow?u:{...u,detectOverflow:Ik},g=await(u.isRTL==null?void 0:u.isRTL(n));let p=await u.getElementRects({reference:t,floating:n,strategy:i}),{x:y,y:v}=_x(p,s,g),w=s,C=0;const S={};for(let _=0;_<c.length;_++){const E=c[_];if(!E)continue;const{name:R,fn:k}=E,{x:A,y:D,data:H,reset:$}=await k({x:y,y:v,initialPlacement:s,placement:w,strategy:i,middlewareData:S,rects:p,platform:f,elements:{reference:t,floating:n}});y=A??y,v=D??v,S[R]={...S[R],...H},$&&C<qk&&(C++,typeof $=="object"&&($.placement&&(w=$.placement),$.rects&&(p=$.rects===!0?await u.getElementRects({reference:t,floating:n,strategy:i}):$.rects),{x:y,y:v}=_x(p,w,g)),_=-1)}return{x:y,y:v,placement:w,strategy:i,middlewareData:S}},$k=t=>({name:"arrow",options:t,async fn(n){const{x:r,y:s,placement:i,rects:c,platform:u,elements:f,middlewareData:g}=n,{element:p,padding:y=0}=or(t,n)||{};if(p==null)return{};const v=cw(y),w={x:r,y:s},C=Yh(i),S=Gh(C),_=await u.getDimensions(p),E=C==="y",R=E?"top":"left",k=E?"bottom":"right",A=E?"clientHeight":"clientWidth",D=c.reference[S]+c.reference[C]-w[C]-c.floating[S],H=w[C]-c.reference[C],$=await(u.getOffsetParent==null?void 0:u.getOffsetParent(p));let U=$?$[A]:0;(!U||!await(u.isElement==null?void 0:u.isElement($)))&&(U=f.floating[A]||c.floating[S]);const F=D/2-H/2,de=U/2-_[S]/2-1,fe=$r(v[R],de),me=$r(v[k],de),se=fe,G=U-_[S]-me,he=U/2-_[S]/2+F,ve=sh(se,he,G),T=!g.arrow&&Yo(i)!=null&&he!==ve&&c.reference[S]/2-(he<se?fe:me)-_[S]/2<0,K=T?he<se?he-se:he-G:0;return{[C]:w[C]+K,data:{[C]:ve,centerOffset:he-ve-K,...T&&{alignmentOffset:K}},reset:T}}}),Gk=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(n){var r,s;const{placement:i,middlewareData:c,rects:u,initialPlacement:f,platform:g,elements:p}=n,{mainAxis:y=!0,crossAxis:v=!0,fallbackPlacements:w,fallbackStrategy:C="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:_=!0,...E}=or(t,n);if((r=c.arrow)!=null&&r.alignmentOffset)return{};const R=ir(i),k=Oa(f),A=ir(f)===f,D=await(g.isRTL==null?void 0:g.isRTL(p.floating)),H=w||(A||!_?[ou(f)]:Lk(f)),$=S!=="none";!w&&$&&H.push(...Hk(f,_,S,D));const U=[f,...H],F=await g.detectOverflow(n,E),de=[];let fe=((s=c.flip)==null?void 0:s.overflows)||[];if(y&&de.push(F[R]),v){const he=zk(i,u,D);de.push(F[he[0]],F[he[1]])}if(fe=[...fe,{placement:i,overflows:de}],!de.every(he=>he<=0)){var me,se;const he=(((me=c.flip)==null?void 0:me.index)||0)+1,ve=U[he];if(ve&&(!(v==="alignment"?k!==Oa(ve):!1)||fe.every(te=>Oa(te.placement)===k?te.overflows[0]>0:!0)))return{data:{index:he,overflows:fe},reset:{placement:ve}};let T=(se=fe.filter(K=>K.overflows[0]<=0).sort((K,te)=>K.overflows[1]-te.overflows[1])[0])==null?void 0:se.placement;if(!T)switch(C){case"bestFit":{var G;const K=(G=fe.filter(te=>{if($){const le=Oa(te.placement);return le===k||le==="y"}return!0}).map(te=>[te.placement,te.overflows.filter(le=>le>0).reduce((le,ne)=>le+ne,0)]).sort((te,le)=>te[1]-le[1])[0])==null?void 0:G[0];K&&(T=K);break}case"initialPlacement":T=f;break}if(i!==T)return{reset:{placement:T}}}return{}}}};function Cx(t,n){return{top:t.top-n.height,right:t.right-n.width,bottom:t.bottom-n.height,left:t.left-n.width}}function Nx(t){return Mk.some(n=>t[n]>=0)}const Yk=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(n){const{rects:r,platform:s}=n,{strategy:i="referenceHidden",...c}=or(t,n);switch(i){case"referenceHidden":{const u=await s.detectOverflow(n,{...c,elementContext:"reference"}),f=Cx(u,r.reference);return{data:{referenceHiddenOffsets:f,referenceHidden:Nx(f)}}}case"escaped":{const u=await s.detectOverflow(n,{...c,altBoundary:!0}),f=Cx(u,r.floating);return{data:{escapedOffsets:f,escaped:Nx(f)}}}default:return{}}}}},uw=new Set(["left","top"]);async function Zk(t,n){const{placement:r,platform:s,elements:i}=t,c=await(s.isRTL==null?void 0:s.isRTL(i.floating)),u=ir(r),f=Yo(r),g=Oa(r)==="y",p=uw.has(u)?-1:1,y=c&&g?-1:1,v=or(n,t);let{mainAxis:w,crossAxis:C,alignmentAxis:S}=typeof v=="number"?{mainAxis:v,crossAxis:0,alignmentAxis:null}:{mainAxis:v.mainAxis||0,crossAxis:v.crossAxis||0,alignmentAxis:v.alignmentAxis};return f&&typeof S=="number"&&(C=f==="end"?S*-1:S),g?{x:C*y,y:w*p}:{x:w*p,y:C*y}}const Xk=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(n){var r,s;const{x:i,y:c,placement:u,middlewareData:f}=n,g=await Zk(n,t);return u===((r=f.offset)==null?void 0:r.placement)&&(s=f.arrow)!=null&&s.alignmentOffset?{}:{x:i+g.x,y:c+g.y,data:{...g,placement:u}}}}},Kk=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(n){const{x:r,y:s,placement:i,platform:c}=n,{mainAxis:u=!0,crossAxis:f=!1,limiter:g={fn:R=>{let{x:k,y:A}=R;return{x:k,y:A}}},...p}=or(t,n),y={x:r,y:s},v=await c.detectOverflow(n,p),w=Oa(ir(i)),C=$h(w);let S=y[C],_=y[w];if(u){const R=C==="y"?"top":"left",k=C==="y"?"bottom":"right",A=S+v[R],D=S-v[k];S=sh(A,S,D)}if(f){const R=w==="y"?"top":"left",k=w==="y"?"bottom":"right",A=_+v[R],D=_-v[k];_=sh(A,_,D)}const E=g.fn({...n,[C]:S,[w]:_});return{...E,data:{x:E.x-r,y:E.y-s,enabled:{[C]:u,[w]:f}}}}}},Qk=function(t){return t===void 0&&(t={}),{options:t,fn(n){const{x:r,y:s,placement:i,rects:c,middlewareData:u}=n,{offset:f=0,mainAxis:g=!0,crossAxis:p=!0}=or(t,n),y={x:r,y:s},v=Oa(i),w=$h(v);let C=y[w],S=y[v];const _=or(f,n),E=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(g){const A=w==="y"?"height":"width",D=c.reference[w]-c.floating[A]+E.mainAxis,H=c.reference[w]+c.reference[A]-E.mainAxis;C<D?C=D:C>H&&(C=H)}if(p){var R,k;const A=w==="y"?"width":"height",D=uw.has(ir(i)),H=c.reference[v]-c.floating[A]+(D&&((R=u.offset)==null?void 0:R[v])||0)+(D?0:E.crossAxis),$=c.reference[v]+c.reference[A]+(D?0:((k=u.offset)==null?void 0:k[v])||0)-(D?E.crossAxis:0);S<H?S=H:S>$&&(S=$)}return{[w]:C,[v]:S}}}},Wk=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(n){var r,s;const{placement:i,rects:c,platform:u,elements:f}=n,{apply:g=()=>{},...p}=or(t,n),y=await u.detectOverflow(n,p),v=ir(i),w=Yo(i),C=Oa(i)==="y",{width:S,height:_}=c.floating;let E,R;v==="top"||v==="bottom"?(E=v,R=w===(await(u.isRTL==null?void 0:u.isRTL(f.floating))?"start":"end")?"left":"right"):(R=v,E=w==="end"?"top":"bottom");const k=_-y.top-y.bottom,A=S-y.left-y.right,D=$r(_-y[E],k),H=$r(S-y[R],A),$=!n.middlewareData.shift;let U=D,F=H;if((r=n.middlewareData.shift)!=null&&r.enabled.x&&(F=A),(s=n.middlewareData.shift)!=null&&s.enabled.y&&(U=k),$&&!w){const fe=In(y.left,0),me=In(y.right,0),se=In(y.top,0),G=In(y.bottom,0);C?F=S-2*(fe!==0||me!==0?fe+me:In(y.left,y.right)):U=_-2*(se!==0||G!==0?se+G:In(y.top,y.bottom))}await g({...n,availableWidth:F,availableHeight:U});const de=await u.getDimensions(f.floating);return S!==de.width||_!==de.height?{reset:{rects:!0}}:{}}}};function Iu(){return typeof window<"u"}function Zo(t){return dw(t)?(t.nodeName||"").toLowerCase():"#document"}function Fn(t){var n;return(t==null||(n=t.ownerDocument)==null?void 0:n.defaultView)||window}function La(t){var n;return(n=(dw(t)?t.ownerDocument:t.document)||window.document)==null?void 0:n.documentElement}function dw(t){return Iu()?t instanceof Node||t instanceof Fn(t).Node:!1}function ga(t){return Iu()?t instanceof Element||t instanceof Fn(t).Element:!1}function cr(t){return Iu()?t instanceof HTMLElement||t instanceof Fn(t).HTMLElement:!1}function Rx(t){return!Iu()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Fn(t).ShadowRoot}function pl(t){const{overflow:n,overflowX:r,overflowY:s,display:i}=va(t);return/auto|scroll|overlay|hidden|clip/.test(n+s+r)&&i!=="inline"&&i!=="contents"}function Jk(t){return/^(table|td|th)$/.test(Zo(t))}function qu(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}const eM=/transform|translate|scale|rotate|perspective|filter/,tM=/paint|layout|strict|content/,ys=t=>!!t&&t!=="none";let km;function Zh(t){const n=ga(t)?va(t):t;return ys(n.transform)||ys(n.translate)||ys(n.scale)||ys(n.rotate)||ys(n.perspective)||!Xh()&&(ys(n.backdropFilter)||ys(n.filter))||eM.test(n.willChange||"")||tM.test(n.contain||"")}function nM(t){let n=Gr(t);for(;cr(n)&&!zo(n);){if(Zh(n))return n;if(qu(n))return null;n=Gr(n)}return null}function Xh(){return km==null&&(km=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),km}function zo(t){return/^(html|body|#document)$/.test(Zo(t))}function va(t){return Fn(t).getComputedStyle(t)}function Fu(t){return ga(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Gr(t){if(Zo(t)==="html")return t;const n=t.assignedSlot||t.parentNode||Rx(t)&&t.host||La(t);return Rx(n)?n.host:n}function fw(t){const n=Gr(t);return zo(n)?t.ownerDocument?t.ownerDocument.body:t.body:cr(n)&&pl(n)?n:fw(n)}function tl(t,n,r){var s;n===void 0&&(n=[]),r===void 0&&(r=!0);const i=fw(t),c=i===((s=t.ownerDocument)==null?void 0:s.body),u=Fn(i);if(c){const f=ih(u);return n.concat(u,u.visualViewport||[],pl(i)?i:[],f&&r?tl(f):[])}else return n.concat(i,tl(i,[],r))}function ih(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function mw(t){const n=va(t);let r=parseFloat(n.width)||0,s=parseFloat(n.height)||0;const i=cr(t),c=i?t.offsetWidth:r,u=i?t.offsetHeight:s,f=su(r)!==c||su(s)!==u;return f&&(r=c,s=u),{width:r,height:s,$:f}}function Kh(t){return ga(t)?t:t.contextElement}function jo(t){const n=Kh(t);if(!cr(n))return ka(1);const r=n.getBoundingClientRect(),{width:s,height:i,$:c}=mw(n);let u=(c?su(r.width):r.width)/s,f=(c?su(r.height):r.height)/i;return(!u||!Number.isFinite(u))&&(u=1),(!f||!Number.isFinite(f))&&(f=1),{x:u,y:f}}const aM=ka(0);function hw(t){const n=Fn(t);return!Xh()||!n.visualViewport?aM:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function rM(t,n,r){return n===void 0&&(n=!1),!r||n&&r!==Fn(t)?!1:n}function Cs(t,n,r,s){n===void 0&&(n=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),c=Kh(t);let u=ka(1);n&&(s?ga(s)&&(u=jo(s)):u=jo(t));const f=rM(c,r,s)?hw(c):ka(0);let g=(i.left+f.x)/u.x,p=(i.top+f.y)/u.y,y=i.width/u.x,v=i.height/u.y;if(c){const w=Fn(c),C=s&&ga(s)?Fn(s):s;let S=w,_=ih(S);for(;_&&s&&C!==S;){const E=jo(_),R=_.getBoundingClientRect(),k=va(_),A=R.left+(_.clientLeft+parseFloat(k.paddingLeft))*E.x,D=R.top+(_.clientTop+parseFloat(k.paddingTop))*E.y;g*=E.x,p*=E.y,y*=E.x,v*=E.y,g+=A,p+=D,S=Fn(_),_=ih(S)}}return iu({width:y,height:v,x:g,y:p})}function $u(t,n){const r=Fu(t).scrollLeft;return n?n.left+r:Cs(La(t)).left+r}function pw(t,n){const r=t.getBoundingClientRect(),s=r.left+n.scrollLeft-$u(t,r),i=r.top+n.scrollTop;return{x:s,y:i}}function sM(t){let{elements:n,rect:r,offsetParent:s,strategy:i}=t;const c=i==="fixed",u=La(s),f=n?qu(n.floating):!1;if(s===u||f&&c)return r;let g={scrollLeft:0,scrollTop:0},p=ka(1);const y=ka(0),v=cr(s);if((v||!v&&!c)&&((Zo(s)!=="body"||pl(u))&&(g=Fu(s)),v)){const C=Cs(s);p=jo(s),y.x=C.x+s.clientLeft,y.y=C.y+s.clientTop}const w=u&&!v&&!c?pw(u,g):ka(0);return{width:r.width*p.x,height:r.height*p.y,x:r.x*p.x-g.scrollLeft*p.x+y.x+w.x,y:r.y*p.y-g.scrollTop*p.y+y.y+w.y}}function oM(t){return Array.from(t.getClientRects())}function iM(t){const n=La(t),r=Fu(t),s=t.ownerDocument.body,i=In(n.scrollWidth,n.clientWidth,s.scrollWidth,s.clientWidth),c=In(n.scrollHeight,n.clientHeight,s.scrollHeight,s.clientHeight);let u=-r.scrollLeft+$u(t);const f=-r.scrollTop;return va(s).direction==="rtl"&&(u+=In(n.clientWidth,s.clientWidth)-i),{width:i,height:c,x:u,y:f}}const Ax=25;function lM(t,n){const r=Fn(t),s=La(t),i=r.visualViewport;let c=s.clientWidth,u=s.clientHeight,f=0,g=0;if(i){c=i.width,u=i.height;const y=Xh();(!y||y&&n==="fixed")&&(f=i.offsetLeft,g=i.offsetTop)}const p=$u(s);if(p<=0){const y=s.ownerDocument,v=y.body,w=getComputedStyle(v),C=y.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,S=Math.abs(s.clientWidth-v.clientWidth-C);S<=Ax&&(c-=S)}else p<=Ax&&(c+=p);return{width:c,height:u,x:f,y:g}}function cM(t,n){const r=Cs(t,!0,n==="fixed"),s=r.top+t.clientTop,i=r.left+t.clientLeft,c=cr(t)?jo(t):ka(1),u=t.clientWidth*c.x,f=t.clientHeight*c.y,g=i*c.x,p=s*c.y;return{width:u,height:f,x:g,y:p}}function Tx(t,n,r){let s;if(n==="viewport")s=lM(t,r);else if(n==="document")s=iM(La(t));else if(ga(n))s=cM(n,r);else{const i=hw(t);s={x:n.x-i.x,y:n.y-i.y,width:n.width,height:n.height}}return iu(s)}function gw(t,n){const r=Gr(t);return r===n||!ga(r)||zo(r)?!1:va(r).position==="fixed"||gw(r,n)}function uM(t,n){const r=n.get(t);if(r)return r;let s=tl(t,[],!1).filter(f=>ga(f)&&Zo(f)!=="body"),i=null;const c=va(t).position==="fixed";let u=c?Gr(t):t;for(;ga(u)&&!zo(u);){const f=va(u),g=Zh(u);!g&&f.position==="fixed"&&(i=null),(c?!g&&!i:!g&&f.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||pl(u)&&!g&&gw(t,u))?s=s.filter(y=>y!==u):i=f,u=Gr(u)}return n.set(t,s),s}function dM(t){let{element:n,boundary:r,rootBoundary:s,strategy:i}=t;const u=[...r==="clippingAncestors"?qu(n)?[]:uM(n,this._c):[].concat(r),s],f=Tx(n,u[0],i);let g=f.top,p=f.right,y=f.bottom,v=f.left;for(let w=1;w<u.length;w++){const C=Tx(n,u[w],i);g=In(C.top,g),p=$r(C.right,p),y=$r(C.bottom,y),v=In(C.left,v)}return{width:p-v,height:y-g,x:v,y:g}}function fM(t){const{width:n,height:r}=mw(t);return{width:n,height:r}}function mM(t,n,r){const s=cr(n),i=La(n),c=r==="fixed",u=Cs(t,!0,c,n);let f={scrollLeft:0,scrollTop:0};const g=ka(0);function p(){g.x=$u(i)}if(s||!s&&!c)if((Zo(n)!=="body"||pl(i))&&(f=Fu(n)),s){const C=Cs(n,!0,c,n);g.x=C.x+n.clientLeft,g.y=C.y+n.clientTop}else i&&p();c&&!s&&i&&p();const y=i&&!s&&!c?pw(i,f):ka(0),v=u.left+f.scrollLeft-g.x-y.x,w=u.top+f.scrollTop-g.y-y.y;return{x:v,y:w,width:u.width,height:u.height}}function Mm(t){return va(t).position==="static"}function Ox(t,n){if(!cr(t)||va(t).position==="fixed")return null;if(n)return n(t);let r=t.offsetParent;return La(t)===r&&(r=r.ownerDocument.body),r}function vw(t,n){const r=Fn(t);if(qu(t))return r;if(!cr(t)){let i=Gr(t);for(;i&&!zo(i);){if(ga(i)&&!Mm(i))return i;i=Gr(i)}return r}let s=Ox(t,n);for(;s&&Jk(s)&&Mm(s);)s=Ox(s,n);return s&&zo(s)&&Mm(s)&&!Zh(s)?r:s||nM(t)||r}const hM=async function(t){const n=this.getOffsetParent||vw,r=this.getDimensions,s=await r(t.floating);return{reference:mM(t.reference,await n(t.floating),t.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function pM(t){return va(t).direction==="rtl"}const gM={convertOffsetParentRelativeRectToViewportRelativeRect:sM,getDocumentElement:La,getClippingRect:dM,getOffsetParent:vw,getElementRects:hM,getClientRects:oM,getDimensions:fM,getScale:jo,isElement:ga,isRTL:pM};function yw(t,n){return t.x===n.x&&t.y===n.y&&t.width===n.width&&t.height===n.height}function vM(t,n){let r=null,s;const i=La(t);function c(){var f;clearTimeout(s),(f=r)==null||f.disconnect(),r=null}function u(f,g){f===void 0&&(f=!1),g===void 0&&(g=1),c();const p=t.getBoundingClientRect(),{left:y,top:v,width:w,height:C}=p;if(f||n(),!w||!C)return;const S=Ic(v),_=Ic(i.clientWidth-(y+w)),E=Ic(i.clientHeight-(v+C)),R=Ic(y),A={rootMargin:-S+"px "+-_+"px "+-E+"px "+-R+"px",threshold:In(0,$r(1,g))||1};let D=!0;function H($){const U=$[0].intersectionRatio;if(U!==g){if(!D)return u();U?u(!1,U):s=setTimeout(()=>{u(!1,1e-7)},1e3)}U===1&&!yw(p,t.getBoundingClientRect())&&u(),D=!1}try{r=new IntersectionObserver(H,{...A,root:i.ownerDocument})}catch{r=new IntersectionObserver(H,A)}r.observe(t)}return u(!0),c}function yM(t,n,r,s){s===void 0&&(s={});const{ancestorScroll:i=!0,ancestorResize:c=!0,elementResize:u=typeof ResizeObserver=="function",layoutShift:f=typeof IntersectionObserver=="function",animationFrame:g=!1}=s,p=Kh(t),y=i||c?[...p?tl(p):[],...n?tl(n):[]]:[];y.forEach(R=>{i&&R.addEventListener("scroll",r,{passive:!0}),c&&R.addEventListener("resize",r)});const v=p&&f?vM(p,r):null;let w=-1,C=null;u&&(C=new ResizeObserver(R=>{let[k]=R;k&&k.target===p&&C&&n&&(C.unobserve(n),cancelAnimationFrame(w),w=requestAnimationFrame(()=>{var A;(A=C)==null||A.observe(n)})),r()}),p&&!g&&C.observe(p),n&&C.observe(n));let S,_=g?Cs(t):null;g&&E();function E(){const R=Cs(t);_&&!yw(_,R)&&r(),_=R,S=requestAnimationFrame(E)}return r(),()=>{var R;y.forEach(k=>{i&&k.removeEventListener("scroll",r),c&&k.removeEventListener("resize",r)}),v==null||v(),(R=C)==null||R.disconnect(),C=null,g&&cancelAnimationFrame(S)}}const bM=Xk,xM=Kk,wM=Gk,SM=Wk,EM=Yk,jx=$k,_M=Qk,CM=(t,n,r)=>{const s=new Map,i={platform:gM,...r},c={...i.platform,_c:s};return Fk(t,n,{...i,platform:c})};var NM=typeof document<"u",RM=function(){},Jc=NM?b.useLayoutEffect:RM;function lu(t,n){if(t===n)return!0;if(typeof t!=typeof n)return!1;if(typeof t=="function"&&t.toString()===n.toString())return!0;let r,s,i;if(t&&n&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==n.length)return!1;for(s=r;s--!==0;)if(!lu(t[s],n[s]))return!1;return!0}if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!{}.hasOwnProperty.call(n,i[s]))return!1;for(s=r;s--!==0;){const c=i[s];if(!(c==="_owner"&&t.$$typeof)&&!lu(t[c],n[c]))return!1}return!0}return t!==t&&n!==n}function bw(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function kx(t,n){const r=bw(t);return Math.round(n*r)/r}function Dm(t){const n=b.useRef(t);return Jc(()=>{n.current=t}),n}function AM(t){t===void 0&&(t={});const{placement:n="bottom",strategy:r="absolute",middleware:s=[],platform:i,elements:{reference:c,floating:u}={},transform:f=!0,whileElementsMounted:g,open:p}=t,[y,v]=b.useState({x:0,y:0,strategy:r,placement:n,middlewareData:{},isPositioned:!1}),[w,C]=b.useState(s);lu(w,s)||C(s);const[S,_]=b.useState(null),[E,R]=b.useState(null),k=b.useCallback(te=>{te!==$.current&&($.current=te,_(te))},[]),A=b.useCallback(te=>{te!==U.current&&(U.current=te,R(te))},[]),D=c||S,H=u||E,$=b.useRef(null),U=b.useRef(null),F=b.useRef(y),de=g!=null,fe=Dm(g),me=Dm(i),se=Dm(p),G=b.useCallback(()=>{if(!$.current||!U.current)return;const te={placement:n,strategy:r,middleware:w};me.current&&(te.platform=me.current),CM($.current,U.current,te).then(le=>{const ne={...le,isPositioned:se.current!==!1};he.current&&!lu(F.current,ne)&&(F.current=ne,Ah.flushSync(()=>{v(ne)}))})},[w,n,r,me,se]);Jc(()=>{p===!1&&F.current.isPositioned&&(F.current.isPositioned=!1,v(te=>({...te,isPositioned:!1})))},[p]);const he=b.useRef(!1);Jc(()=>(he.current=!0,()=>{he.current=!1}),[]),Jc(()=>{if(D&&($.current=D),H&&(U.current=H),D&&H){if(fe.current)return fe.current(D,H,G);G()}},[D,H,G,fe,de]);const ve=b.useMemo(()=>({reference:$,floating:U,setReference:k,setFloating:A}),[k,A]),T=b.useMemo(()=>({reference:D,floating:H}),[D,H]),K=b.useMemo(()=>{const te={position:r,left:0,top:0};if(!T.floating)return te;const le=kx(T.floating,y.x),ne=kx(T.floating,y.y);return f?{...te,transform:"translate("+le+"px, "+ne+"px)",...bw(T.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:le,top:ne}},[r,f,T.floating,y.x,y.y]);return b.useMemo(()=>({...y,update:G,refs:ve,elements:T,floatingStyles:K}),[y,G,ve,T,K])}const TM=t=>{function n(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:s,padding:i}=typeof t=="function"?t(r):t;return s&&n(s)?s.current!=null?jx({element:s.current,padding:i}).fn(r):{}:s?jx({element:s,padding:i}).fn(r):{}}}},OM=(t,n)=>{const r=bM(t);return{name:r.name,fn:r.fn,options:[t,n]}},jM=(t,n)=>{const r=xM(t);return{name:r.name,fn:r.fn,options:[t,n]}},kM=(t,n)=>({fn:_M(t).fn,options:[t,n]}),MM=(t,n)=>{const r=wM(t);return{name:r.name,fn:r.fn,options:[t,n]}},DM=(t,n)=>{const r=SM(t);return{name:r.name,fn:r.fn,options:[t,n]}},zM=(t,n)=>{const r=EM(t);return{name:r.name,fn:r.fn,options:[t,n]}},LM=(t,n)=>{const r=TM(t);return{name:r.name,fn:r.fn,options:[t,n]}};var UM="Arrow",xw=b.forwardRef((t,n)=>{const{children:r,width:s=10,height:i=5,...c}=t;return h.jsx(kt.svg,{...c,ref:n,width:s,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:h.jsx("polygon",{points:"0,0 30,0 15,10"})})});xw.displayName=UM;var BM=xw,Qh="Popper",[ww,Gu]=Ts(Qh),[PM,Sw]=ww(Qh),Ew=t=>{const{__scopePopper:n,children:r}=t,[s,i]=b.useState(null);return h.jsx(PM,{scope:n,anchor:s,onAnchorChange:i,children:r})};Ew.displayName=Qh;var _w="PopperAnchor",Cw=b.forwardRef((t,n)=>{const{__scopePopper:r,virtualRef:s,...i}=t,c=Sw(_w,r),u=b.useRef(null),f=Wt(n,u),g=b.useRef(null);return b.useEffect(()=>{const p=g.current;g.current=(s==null?void 0:s.current)||u.current,p!==g.current&&c.onAnchorChange(g.current)}),s?null:h.jsx(kt.div,{...i,ref:f})});Cw.displayName=_w;var Wh="PopperContent",[HM,VM]=ww(Wh),Nw=b.forwardRef((t,n)=>{var pe,Q,oe,Re,et,Me;const{__scopePopper:r,side:s="bottom",sideOffset:i=0,align:c="center",alignOffset:u=0,arrowPadding:f=0,avoidCollisions:g=!0,collisionBoundary:p=[],collisionPadding:y=0,sticky:v="partial",hideWhenDetached:w=!1,updatePositionStrategy:C="optimized",onPlaced:S,..._}=t,E=Sw(Wh,r),[R,k]=b.useState(null),A=Wt(n,ze=>k(ze)),[D,H]=b.useState(null),$=kk(D),U=($==null?void 0:$.width)??0,F=($==null?void 0:$.height)??0,de=s+(c!=="center"?"-"+c:""),fe=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},me=Array.isArray(p)?p:[p],se=me.length>0,G={padding:fe,boundary:me.filter(qM),altBoundary:se},{refs:he,floatingStyles:ve,placement:T,isPositioned:K,middlewareData:te}=AM({strategy:"fixed",placement:de,whileElementsMounted:(...ze)=>yM(...ze,{animationFrame:C==="always"}),elements:{reference:E.anchor},middleware:[OM({mainAxis:i+F,alignmentAxis:u}),g&&jM({mainAxis:!0,crossAxis:!1,limiter:v==="partial"?kM():void 0,...G}),g&&MM({...G}),DM({...G,apply:({elements:ze,rects:be,availableWidth:je,availableHeight:at})=>{const{width:ht,height:Qe}=be.reference,Pe=ze.floating.style;Pe.setProperty("--radix-popper-available-width",`${je}px`),Pe.setProperty("--radix-popper-available-height",`${at}px`),Pe.setProperty("--radix-popper-anchor-width",`${ht}px`),Pe.setProperty("--radix-popper-anchor-height",`${Qe}px`)}}),D&&LM({element:D,padding:f}),FM({arrowWidth:U,arrowHeight:F}),w&&zM({strategy:"referenceHidden",...G})]}),[le,ne]=Tw(T),j=sr(S);Fr(()=>{K&&(j==null||j())},[K,j]);const X=(pe=te.arrow)==null?void 0:pe.x,L=(Q=te.arrow)==null?void 0:Q.y,Y=((oe=te.arrow)==null?void 0:oe.centerOffset)!==0,[J,ie]=b.useState();return Fr(()=>{R&&ie(window.getComputedStyle(R).zIndex)},[R]),h.jsx("div",{ref:he.setFloating,"data-radix-popper-content-wrapper":"",style:{...ve,transform:K?ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[(Re=te.transformOrigin)==null?void 0:Re.x,(et=te.transformOrigin)==null?void 0:et.y].join(" "),...((Me=te.hide)==null?void 0:Me.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:h.jsx(HM,{scope:r,placedSide:le,onArrowChange:H,arrowX:X,arrowY:L,shouldHideArrow:Y,children:h.jsx(kt.div,{"data-side":le,"data-align":ne,..._,ref:A,style:{..._.style,animation:K?void 0:"none"}})})})});Nw.displayName=Wh;var Rw="PopperArrow",IM={top:"bottom",right:"left",bottom:"top",left:"right"},Aw=b.forwardRef(function(n,r){const{__scopePopper:s,...i}=n,c=VM(Rw,s),u=IM[c.placedSide];return h.jsx("span",{ref:c.onArrowChange,style:{position:"absolute",left:c.arrowX,top:c.arrowY,[u]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[c.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[c.placedSide],visibility:c.shouldHideArrow?"hidden":void 0},children:h.jsx(BM,{...i,ref:r,style:{...i.style,display:"block"}})})});Aw.displayName=Rw;function qM(t){return t!==null}var FM=t=>({name:"transformOrigin",options:t,fn(n){var E,R,k;const{placement:r,rects:s,middlewareData:i}=n,u=((E=i.arrow)==null?void 0:E.centerOffset)!==0,f=u?0:t.arrowWidth,g=u?0:t.arrowHeight,[p,y]=Tw(r),v={start:"0%",center:"50%",end:"100%"}[y],w=(((R=i.arrow)==null?void 0:R.x)??0)+f/2,C=(((k=i.arrow)==null?void 0:k.y)??0)+g/2;let S="",_="";return p==="bottom"?(S=u?v:`${w}px`,_=`${-g}px`):p==="top"?(S=u?v:`${w}px`,_=`${s.floating.height+g}px`):p==="right"?(S=`${-g}px`,_=u?v:`${C}px`):p==="left"&&(S=`${s.floating.width+g}px`,_=u?v:`${C}px`),{data:{x:S,y:_}}}});function Tw(t){const[n,r="center"]=t.split("-");return[n,r]}var $M=Ew,Jh=Cw,Ow=Nw,jw=Aw,zm="rovingFocusGroup.onEntryFocus",GM={bubbles:!1,cancelable:!0},gl="RovingFocusGroup",[lh,kw,YM]=A1(gl),[ZM,Mw]=Ts(gl,[YM]),[XM,KM]=ZM(gl),Dw=b.forwardRef((t,n)=>h.jsx(lh.Provider,{scope:t.__scopeRovingFocusGroup,children:h.jsx(lh.Slot,{scope:t.__scopeRovingFocusGroup,children:h.jsx(QM,{...t,ref:n})})}));Dw.displayName=gl;var QM=b.forwardRef((t,n)=>{const{__scopeRovingFocusGroup:r,orientation:s,loop:i=!1,dir:c,currentTabStopId:u,defaultCurrentTabStopId:f,onCurrentTabStopIdChange:g,onEntryFocus:p,preventScrollOnEntryFocus:y=!1,...v}=t,w=b.useRef(null),C=Wt(n,w),S=O1(c),[_,E]=Bh({prop:u,defaultProp:f??null,onChange:g,caller:gl}),[R,k]=b.useState(!1),A=sr(p),D=kw(r),H=b.useRef(!1),[$,U]=b.useState(0);return b.useEffect(()=>{const F=w.current;if(F)return F.addEventListener(zm,A),()=>F.removeEventListener(zm,A)},[A]),h.jsx(XM,{scope:r,orientation:s,dir:S,loop:i,currentTabStopId:_,onItemFocus:b.useCallback(F=>E(F),[E]),onItemShiftTab:b.useCallback(()=>k(!0),[]),onFocusableItemAdd:b.useCallback(()=>U(F=>F+1),[]),onFocusableItemRemove:b.useCallback(()=>U(F=>F-1),[]),children:h.jsx(kt.div,{tabIndex:R||$===0?-1:0,"data-orientation":s,...v,ref:C,style:{outline:"none",...t.style},onMouseDown:qe(t.onMouseDown,()=>{H.current=!0}),onFocus:qe(t.onFocus,F=>{const de=!H.current;if(F.target===F.currentTarget&&de&&!R){const fe=new CustomEvent(zm,GM);if(F.currentTarget.dispatchEvent(fe),!fe.defaultPrevented){const me=D().filter(T=>T.focusable),se=me.find(T=>T.active),G=me.find(T=>T.id===_),ve=[se,G,...me].filter(Boolean).map(T=>T.ref.current);Uw(ve,y)}}H.current=!1}),onBlur:qe(t.onBlur,()=>k(!1))})})}),zw="RovingFocusGroupItem",Lw=b.forwardRef((t,n)=>{const{__scopeRovingFocusGroup:r,focusable:s=!0,active:i=!1,tabStopId:c,children:u,...f}=t,g=To(),p=c||g,y=KM(zw,r),v=y.currentTabStopId===p,w=kw(r),{onFocusableItemAdd:C,onFocusableItemRemove:S,currentTabStopId:_}=y;return b.useEffect(()=>{if(s)return C(),()=>S()},[s,C,S]),h.jsx(lh.ItemSlot,{scope:r,id:p,focusable:s,active:i,children:h.jsx(kt.span,{tabIndex:v?0:-1,"data-orientation":y.orientation,...f,ref:n,onMouseDown:qe(t.onMouseDown,E=>{s?y.onItemFocus(p):E.preventDefault()}),onFocus:qe(t.onFocus,()=>y.onItemFocus(p)),onKeyDown:qe(t.onKeyDown,E=>{if(E.key==="Tab"&&E.shiftKey){y.onItemShiftTab();return}if(E.target!==E.currentTarget)return;const R=eD(E,y.orientation,y.dir);if(R!==void 0){if(E.metaKey||E.ctrlKey||E.altKey||E.shiftKey)return;E.preventDefault();let A=w().filter(D=>D.focusable).map(D=>D.ref.current);if(R==="last")A.reverse();else if(R==="prev"||R==="next"){R==="prev"&&A.reverse();const D=A.indexOf(E.currentTarget);A=y.loop?tD(A,D+1):A.slice(D+1)}setTimeout(()=>Uw(A))}}),children:typeof u=="function"?u({isCurrentTabStop:v,hasTabStop:_!=null}):u})})});Lw.displayName=zw;var WM={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function JM(t,n){return n!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function eD(t,n,r){const s=JM(t.key,r);if(!(n==="vertical"&&["ArrowLeft","ArrowRight"].includes(s))&&!(n==="horizontal"&&["ArrowUp","ArrowDown"].includes(s)))return WM[s]}function Uw(t,n=!1){const r=document.activeElement;for(const s of t)if(s===r||(s.focus({preventScroll:n}),document.activeElement!==r))return}function tD(t,n){return t.map((r,s)=>t[(n+s)%t.length])}var nD=Dw,aD=Lw,ch=["Enter"," "],rD=["ArrowDown","PageUp","Home"],Bw=["ArrowUp","PageDown","End"],sD=[...rD,...Bw],oD={ltr:[...ch,"ArrowRight"],rtl:[...ch,"ArrowLeft"]},iD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},vl="Menu",[nl,lD,cD]=A1(vl),[Os,Pw]=Ts(vl,[cD,Gu,Mw]),Yu=Gu(),Hw=Mw(),[uD,js]=Os(vl),[dD,yl]=Os(vl),Vw=t=>{const{__scopeMenu:n,open:r=!1,children:s,dir:i,onOpenChange:c,modal:u=!0}=t,f=Yu(n),[g,p]=b.useState(null),y=b.useRef(!1),v=sr(c),w=O1(i);return b.useEffect(()=>{const C=()=>{y.current=!0,document.addEventListener("pointerdown",S,{capture:!0,once:!0}),document.addEventListener("pointermove",S,{capture:!0,once:!0})},S=()=>y.current=!1;return document.addEventListener("keydown",C,{capture:!0}),()=>{document.removeEventListener("keydown",C,{capture:!0}),document.removeEventListener("pointerdown",S,{capture:!0}),document.removeEventListener("pointermove",S,{capture:!0})}},[]),h.jsx($M,{...f,children:h.jsx(uD,{scope:n,open:r,onOpenChange:v,content:g,onContentChange:p,children:h.jsx(dD,{scope:n,onClose:b.useCallback(()=>v(!1),[v]),isUsingKeyboardRef:y,dir:w,modal:u,children:s})})})};Vw.displayName=vl;var fD="MenuAnchor",ep=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t,i=Yu(r);return h.jsx(Jh,{...i,...s,ref:n})});ep.displayName=fD;var tp="MenuPortal",[mD,Iw]=Os(tp,{forceMount:void 0}),qw=t=>{const{__scopeMenu:n,forceMount:r,children:s,container:i}=t,c=js(tp,n);return h.jsx(mD,{scope:n,forceMount:r,children:h.jsx(za,{present:r||c.open,children:h.jsx(Bu,{asChild:!0,container:i,children:s})})})};qw.displayName=tp;var sa="MenuContent",[hD,np]=Os(sa),Fw=b.forwardRef((t,n)=>{const r=Iw(sa,t.__scopeMenu),{forceMount:s=r.forceMount,...i}=t,c=js(sa,t.__scopeMenu),u=yl(sa,t.__scopeMenu);return h.jsx(nl.Provider,{scope:t.__scopeMenu,children:h.jsx(za,{present:s||c.open,children:h.jsx(nl.Slot,{scope:t.__scopeMenu,children:u.modal?h.jsx(pD,{...i,ref:n}):h.jsx(gD,{...i,ref:n})})})})}),pD=b.forwardRef((t,n)=>{const r=js(sa,t.__scopeMenu),s=b.useRef(null),i=Wt(n,s);return b.useEffect(()=>{const c=s.current;if(c)return Vh(c)},[]),h.jsx(ap,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:qe(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),gD=b.forwardRef((t,n)=>{const r=js(sa,t.__scopeMenu);return h.jsx(ap,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),vD=Do("MenuContent.ScrollLock"),ap=b.forwardRef((t,n)=>{const{__scopeMenu:r,loop:s=!1,trapFocus:i,onOpenAutoFocus:c,onCloseAutoFocus:u,disableOutsidePointerEvents:f,onEntryFocus:g,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:w,onDismiss:C,disableOutsideScroll:S,..._}=t,E=js(sa,r),R=yl(sa,r),k=Yu(r),A=Hw(r),D=lD(r),[H,$]=b.useState(null),U=b.useRef(null),F=Wt(n,U,E.onContentChange),de=b.useRef(0),fe=b.useRef(""),me=b.useRef(0),se=b.useRef(null),G=b.useRef("right"),he=b.useRef(0),ve=S?Hu:b.Fragment,T=S?{as:vD,allowPinchZoom:!0}:void 0,K=le=>{var pe,Q;const ne=fe.current+le,j=D().filter(oe=>!oe.disabled),X=document.activeElement,L=(pe=j.find(oe=>oe.ref.current===X))==null?void 0:pe.textValue,Y=j.map(oe=>oe.textValue),J=TD(Y,ne,L),ie=(Q=j.find(oe=>oe.textValue===J))==null?void 0:Q.ref.current;(function oe(Re){fe.current=Re,window.clearTimeout(de.current),Re!==""&&(de.current=window.setTimeout(()=>oe(""),1e3))})(ne),ie&&setTimeout(()=>ie.focus())};b.useEffect(()=>()=>window.clearTimeout(de.current),[]),Hh();const te=b.useCallback(le=>{var j,X;return G.current===((j=se.current)==null?void 0:j.side)&&jD(le,(X=se.current)==null?void 0:X.area)},[]);return h.jsx(hD,{scope:r,searchRef:fe,onItemEnter:b.useCallback(le=>{te(le)&&le.preventDefault()},[te]),onItemLeave:b.useCallback(le=>{var ne;te(le)||((ne=U.current)==null||ne.focus(),$(null))},[te]),onTriggerLeave:b.useCallback(le=>{te(le)&&le.preventDefault()},[te]),pointerGraceTimerRef:me,onPointerGraceIntentChange:b.useCallback(le=>{se.current=le},[]),children:h.jsx(ve,{...T,children:h.jsx(Uu,{asChild:!0,trapped:i,onMountAutoFocus:qe(c,le=>{var ne;le.preventDefault(),(ne=U.current)==null||ne.focus({preventScroll:!0})}),onUnmountAutoFocus:u,children:h.jsx(Lu,{asChild:!0,disableOutsidePointerEvents:f,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:w,onDismiss:C,children:h.jsx(nD,{asChild:!0,...A,dir:R.dir,orientation:"vertical",loop:s,currentTabStopId:H,onCurrentTabStopIdChange:$,onEntryFocus:qe(g,le=>{R.isUsingKeyboardRef.current||le.preventDefault()}),preventScrollOnEntryFocus:!0,children:h.jsx(Ow,{role:"menu","aria-orientation":"vertical","data-state":oS(E.open),"data-radix-menu-content":"",dir:R.dir,...k,..._,ref:F,style:{outline:"none",..._.style},onKeyDown:qe(_.onKeyDown,le=>{const j=le.target.closest("[data-radix-menu-content]")===le.currentTarget,X=le.ctrlKey||le.altKey||le.metaKey,L=le.key.length===1;j&&(le.key==="Tab"&&le.preventDefault(),!X&&L&&K(le.key));const Y=U.current;if(le.target!==Y||!sD.includes(le.key))return;le.preventDefault();const ie=D().filter(pe=>!pe.disabled).map(pe=>pe.ref.current);Bw.includes(le.key)&&ie.reverse(),RD(ie)}),onBlur:qe(t.onBlur,le=>{le.currentTarget.contains(le.target)||(window.clearTimeout(de.current),fe.current="")}),onPointerMove:qe(t.onPointerMove,al(le=>{const ne=le.target,j=he.current!==le.clientX;if(le.currentTarget.contains(ne)&&j){const X=le.clientX>he.current?"right":"left";G.current=X,he.current=le.clientX}}))})})})})})})});Fw.displayName=sa;var yD="MenuGroup",rp=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return h.jsx(kt.div,{role:"group",...s,ref:n})});rp.displayName=yD;var bD="MenuLabel",$w=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return h.jsx(kt.div,{...s,ref:n})});$w.displayName=bD;var cu="MenuItem",Mx="menu.itemSelect",Zu=b.forwardRef((t,n)=>{const{disabled:r=!1,onSelect:s,...i}=t,c=b.useRef(null),u=yl(cu,t.__scopeMenu),f=np(cu,t.__scopeMenu),g=Wt(n,c),p=b.useRef(!1),y=()=>{const v=c.current;if(!r&&v){const w=new CustomEvent(Mx,{bubbles:!0,cancelable:!0});v.addEventListener(Mx,C=>s==null?void 0:s(C),{once:!0}),T1(v,w),w.defaultPrevented?p.current=!1:u.onClose()}};return h.jsx(Gw,{...i,ref:g,disabled:r,onClick:qe(t.onClick,y),onPointerDown:v=>{var w;(w=t.onPointerDown)==null||w.call(t,v),p.current=!0},onPointerUp:qe(t.onPointerUp,v=>{var w;p.current||(w=v.currentTarget)==null||w.click()}),onKeyDown:qe(t.onKeyDown,v=>{const w=f.searchRef.current!=="";r||w&&v.key===" "||ch.includes(v.key)&&(v.currentTarget.click(),v.preventDefault())})})});Zu.displayName=cu;var Gw=b.forwardRef((t,n)=>{const{__scopeMenu:r,disabled:s=!1,textValue:i,...c}=t,u=np(cu,r),f=Hw(r),g=b.useRef(null),p=Wt(n,g),[y,v]=b.useState(!1),[w,C]=b.useState("");return b.useEffect(()=>{const S=g.current;S&&C((S.textContent??"").trim())},[c.children]),h.jsx(nl.ItemSlot,{scope:r,disabled:s,textValue:i??w,children:h.jsx(aD,{asChild:!0,...f,focusable:!s,children:h.jsx(kt.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":s||void 0,"data-disabled":s?"":void 0,...c,ref:p,onPointerMove:qe(t.onPointerMove,al(S=>{s?u.onItemLeave(S):(u.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:qe(t.onPointerLeave,al(S=>u.onItemLeave(S))),onFocus:qe(t.onFocus,()=>v(!0)),onBlur:qe(t.onBlur,()=>v(!1))})})})}),xD="MenuCheckboxItem",Yw=b.forwardRef((t,n)=>{const{checked:r=!1,onCheckedChange:s,...i}=t;return h.jsx(Ww,{scope:t.__scopeMenu,checked:r,children:h.jsx(Zu,{role:"menuitemcheckbox","aria-checked":uu(r)?"mixed":r,...i,ref:n,"data-state":op(r),onSelect:qe(i.onSelect,()=>s==null?void 0:s(uu(r)?!0:!r),{checkForDefaultPrevented:!1})})})});Yw.displayName=xD;var Zw="MenuRadioGroup",[wD,SD]=Os(Zw,{value:void 0,onValueChange:()=>{}}),Xw=b.forwardRef((t,n)=>{const{value:r,onValueChange:s,...i}=t,c=sr(s);return h.jsx(wD,{scope:t.__scopeMenu,value:r,onValueChange:c,children:h.jsx(rp,{...i,ref:n})})});Xw.displayName=Zw;var Kw="MenuRadioItem",Qw=b.forwardRef((t,n)=>{const{value:r,...s}=t,i=SD(Kw,t.__scopeMenu),c=r===i.value;return h.jsx(Ww,{scope:t.__scopeMenu,checked:c,children:h.jsx(Zu,{role:"menuitemradio","aria-checked":c,...s,ref:n,"data-state":op(c),onSelect:qe(s.onSelect,()=>{var u;return(u=i.onValueChange)==null?void 0:u.call(i,r)},{checkForDefaultPrevented:!1})})})});Qw.displayName=Kw;var sp="MenuItemIndicator",[Ww,ED]=Os(sp,{checked:!1}),Jw=b.forwardRef((t,n)=>{const{__scopeMenu:r,forceMount:s,...i}=t,c=ED(sp,r);return h.jsx(za,{present:s||uu(c.checked)||c.checked===!0,children:h.jsx(kt.span,{...i,ref:n,"data-state":op(c.checked)})})});Jw.displayName=sp;var _D="MenuSeparator",eS=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t;return h.jsx(kt.div,{role:"separator","aria-orientation":"horizontal",...s,ref:n})});eS.displayName=_D;var CD="MenuArrow",tS=b.forwardRef((t,n)=>{const{__scopeMenu:r,...s}=t,i=Yu(r);return h.jsx(jw,{...i,...s,ref:n})});tS.displayName=CD;var ND="MenuSub",[lL,nS]=Os(ND),Yi="MenuSubTrigger",aS=b.forwardRef((t,n)=>{const r=js(Yi,t.__scopeMenu),s=yl(Yi,t.__scopeMenu),i=nS(Yi,t.__scopeMenu),c=np(Yi,t.__scopeMenu),u=b.useRef(null),{pointerGraceTimerRef:f,onPointerGraceIntentChange:g}=c,p={__scopeMenu:t.__scopeMenu},y=b.useCallback(()=>{u.current&&window.clearTimeout(u.current),u.current=null},[]);return b.useEffect(()=>y,[y]),b.useEffect(()=>{const v=f.current;return()=>{window.clearTimeout(v),g(null)}},[f,g]),h.jsx(ep,{asChild:!0,...p,children:h.jsx(Gw,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":oS(r.open),...t,ref:hl(n,i.onTriggerChange),onClick:v=>{var w;(w=t.onClick)==null||w.call(t,v),!(t.disabled||v.defaultPrevented)&&(v.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:qe(t.onPointerMove,al(v=>{c.onItemEnter(v),!v.defaultPrevented&&!t.disabled&&!r.open&&!u.current&&(c.onPointerGraceIntentChange(null),u.current=window.setTimeout(()=>{r.onOpenChange(!0),y()},100))})),onPointerLeave:qe(t.onPointerLeave,al(v=>{var C,S;y();const w=(C=r.content)==null?void 0:C.getBoundingClientRect();if(w){const _=(S=r.content)==null?void 0:S.dataset.side,E=_==="right",R=E?-5:5,k=w[E?"left":"right"],A=w[E?"right":"left"];c.onPointerGraceIntentChange({area:[{x:v.clientX+R,y:v.clientY},{x:k,y:w.top},{x:A,y:w.top},{x:A,y:w.bottom},{x:k,y:w.bottom}],side:_}),window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.onPointerGraceIntentChange(null),300)}else{if(c.onTriggerLeave(v),v.defaultPrevented)return;c.onPointerGraceIntentChange(null)}})),onKeyDown:qe(t.onKeyDown,v=>{var C;const w=c.searchRef.current!=="";t.disabled||w&&v.key===" "||oD[s.dir].includes(v.key)&&(r.onOpenChange(!0),(C=r.content)==null||C.focus(),v.preventDefault())})})})});aS.displayName=Yi;var rS="MenuSubContent",sS=b.forwardRef((t,n)=>{const r=Iw(sa,t.__scopeMenu),{forceMount:s=r.forceMount,...i}=t,c=js(sa,t.__scopeMenu),u=yl(sa,t.__scopeMenu),f=nS(rS,t.__scopeMenu),g=b.useRef(null),p=Wt(n,g);return h.jsx(nl.Provider,{scope:t.__scopeMenu,children:h.jsx(za,{present:s||c.open,children:h.jsx(nl.Slot,{scope:t.__scopeMenu,children:h.jsx(ap,{id:f.contentId,"aria-labelledby":f.triggerId,...i,ref:p,align:"start",side:u.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:y=>{var v;u.isUsingKeyboardRef.current&&((v=g.current)==null||v.focus()),y.preventDefault()},onCloseAutoFocus:y=>y.preventDefault(),onFocusOutside:qe(t.onFocusOutside,y=>{y.target!==f.trigger&&c.onOpenChange(!1)}),onEscapeKeyDown:qe(t.onEscapeKeyDown,y=>{u.onClose(),y.preventDefault()}),onKeyDown:qe(t.onKeyDown,y=>{var C;const v=y.currentTarget.contains(y.target),w=iD[u.dir].includes(y.key);v&&w&&(c.onOpenChange(!1),(C=f.trigger)==null||C.focus(),y.preventDefault())})})})})})});sS.displayName=rS;function oS(t){return t?"open":"closed"}function uu(t){return t==="indeterminate"}function op(t){return uu(t)?"indeterminate":t?"checked":"unchecked"}function RD(t){const n=document.activeElement;for(const r of t)if(r===n||(r.focus(),document.activeElement!==n))return}function AD(t,n){return t.map((r,s)=>t[(n+s)%t.length])}function TD(t,n,r){const i=n.length>1&&Array.from(n).every(p=>p===n[0])?n[0]:n,c=r?t.indexOf(r):-1;let u=AD(t,Math.max(c,0));i.length===1&&(u=u.filter(p=>p!==r));const g=u.find(p=>p.toLowerCase().startsWith(i.toLowerCase()));return g!==r?g:void 0}function OD(t,n){const{x:r,y:s}=t;let i=!1;for(let c=0,u=n.length-1;c<n.length;u=c++){const f=n[c],g=n[u],p=f.x,y=f.y,v=g.x,w=g.y;y>s!=w>s&&r<(v-p)*(s-y)/(w-y)+p&&(i=!i)}return i}function jD(t,n){if(!n)return!1;const r={x:t.clientX,y:t.clientY};return OD(r,n)}function al(t){return n=>n.pointerType==="mouse"?t(n):void 0}var kD=Vw,MD=ep,DD=qw,zD=Fw,LD=rp,UD=$w,BD=Zu,PD=Yw,HD=Xw,VD=Qw,ID=Jw,qD=eS,FD=tS,$D=aS,GD=sS;function YD(t){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}const ZD=ae.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),Xu=()=>{const t=ae.useContext(ZD);if(!t)throw new Error("useDrawerContext must be used within a Drawer.Root");return t};YD(`[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(+[data-state=closed]+){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}`);function XD(t,n){typeof t=="function"?t(n):t!=null&&(t.current=n)}function KD(...t){return n=>t.forEach(r=>XD(r,n))}function iS(...t){return b.useCallback(KD(...t),t)}const Dx=t=>{switch(t){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return t}};function Lm(t,n){if(!t)return()=>{};const r=t.style.cssText;return Object.assign(t.style,n),()=>{t.style.cssText=r}}function QD(...t){return(...n)=>{for(const r of t)typeof r=="function"&&r(...n)}}const Um={DURATION:.5,EASE:[.32,.72,0,1]},WD=8,JD=26,e4=()=>()=>{};function t4(){const{direction:t,isOpen:n,shouldScaleBackground:r,setBackgroundColorOnScale:s,noBodyStyles:i}=Xu(),c=ae.useRef(null),u=b.useMemo(()=>document.body.style.backgroundColor,[]);function f(){return(window.innerWidth-JD)/window.innerWidth}ae.useEffect(()=>{if(n&&r){c.current&&clearTimeout(c.current);const g=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!g)return;QD(s&&!i?Lm(document.body,{background:"black"}):e4,Lm(g,{transformOrigin:Dx(t)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${Um.DURATION}s`,transitionTimingFunction:`cubic-bezier(${Um.EASE.join(",")})`}));const p=Lm(g,{borderRadius:`${WD}px`,overflow:"hidden",...Dx(t)?{transform:`scale(${f()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${f()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{p(),c.current=window.setTimeout(()=>{u?document.body.style.background=u:document.body.style.removeProperty("background")},Um.DURATION*1e3)}}},[n,r,u])}const n4=ae.forwardRef(function({...t},n){const{overlayRef:r,snapPoints:s,onRelease:i,shouldFade:c,isOpen:u,modal:f,shouldAnimate:g}=Xu(),p=iS(n,r),y=s&&s.length>0;if(!f)return null;const v=ae.useCallback(w=>i(w),[i]);return ae.createElement(rw,{onMouseUp:v,ref:p,"data-vaul-overlay":"","data-vaul-snap-points":u&&y?"true":"false","data-vaul-snap-points-overlay":u&&c?"true":"false","data-vaul-animate":g!=null&&g.current?"true":"false",...t})});n4.displayName="Drawer.Overlay";const a4=ae.forwardRef(function({onPointerDownOutside:t,style:n,onOpenAutoFocus:r,...s},i){const{drawerRef:c,onPress:u,onRelease:f,onDrag:g,keyboardIsOpen:p,snapPointsOffset:y,activeSnapPointIndex:v,modal:w,isOpen:C,direction:S,snapPoints:_,container:E,handleOnly:R,shouldAnimate:k,autoFocus:A}=Xu(),[D,H]=ae.useState(!1),$=iS(i,c),U=ae.useRef(null),F=ae.useRef(null),de=ae.useRef(!1),fe=_&&_.length>0;t4();const me=(G,he,ve=0)=>{if(de.current)return!0;const T=Math.abs(G.y),K=Math.abs(G.x),te=K>T,le=["bottom","right"].includes(he)?1:-1;if(he==="left"||he==="right"){if(!(G.x*le<0)&&K>=0&&K<=ve)return te}else if(!(G.y*le<0)&&T>=0&&T<=ve)return!te;return de.current=!0,!0};ae.useEffect(()=>{fe&&window.requestAnimationFrame(()=>{H(!0)})},[]);function se(G){U.current=null,de.current=!1,f(G)}return ae.createElement(sw,{"data-vaul-drawer-direction":S,"data-vaul-drawer":"","data-vaul-delayed-snap-points":D?"true":"false","data-vaul-snap-points":C&&fe?"true":"false","data-vaul-custom-container":E?"true":"false","data-vaul-animate":k!=null&&k.current?"true":"false",...s,ref:$,style:y&&y.length>0?{"--snap-point-height":`${y[v??0]}px`,...n}:n,onPointerDown:G=>{R||(s.onPointerDown==null||s.onPointerDown.call(s,G),U.current={x:G.pageX,y:G.pageY},u(G))},onOpenAutoFocus:G=>{r==null||r(G),A||G.preventDefault()},onPointerDownOutside:G=>{if(t==null||t(G),!w||G.defaultPrevented){G.preventDefault();return}p.current&&(p.current=!1)},onFocusOutside:G=>{if(!w){G.preventDefault();return}},onPointerMove:G=>{if(F.current=G,R||(s.onPointerMove==null||s.onPointerMove.call(s,G),!U.current))return;const he=G.pageY-U.current.y,ve=G.pageX-U.current.x,T=G.pointerType==="touch"?10:2;me({x:ve,y:he},S,T)?g(G):(Math.abs(ve)>T||Math.abs(he)>T)&&(U.current=null)},onPointerUp:G=>{s.onPointerUp==null||s.onPointerUp.call(s,G),U.current=null,de.current=!1,f(G)},onPointerOut:G=>{s.onPointerOut==null||s.onPointerOut.call(s,G),se(F.current)},onContextMenu:G=>{s.onContextMenu==null||s.onContextMenu.call(s,G),F.current&&se(F.current)}})});a4.displayName="Drawer.Content";const r4=250,s4=120,o4=ae.forwardRef(function({preventCycle:t=!1,children:n,...r},s){const{closeDrawer:i,isDragging:c,snapPoints:u,activeSnapPoint:f,setActiveSnapPoint:g,dismissible:p,handleOnly:y,isOpen:v,onPress:w,onDrag:C}=Xu(),S=ae.useRef(null),_=ae.useRef(!1);function E(){if(_.current){A();return}window.setTimeout(()=>{R()},s4)}function R(){if(c||t||_.current){A();return}if(A(),!u||u.length===0){p||i();return}if(f===u[u.length-1]&&p){i();return}const H=u.findIndex(U=>U===f);if(H===-1)return;const $=u[H+1];g($)}function k(){S.current=window.setTimeout(()=>{_.current=!0},r4)}function A(){S.current&&window.clearTimeout(S.current),_.current=!1}return ae.createElement("div",{onClick:E,onPointerCancel:A,onPointerDown:D=>{y&&w(D),k()},onPointerMove:D=>{y&&C(D)},ref:s,"data-vaul-drawer-visible":v?"true":"false","data-vaul-handle":"","aria-hidden":"true",...r},ae.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},n))});o4.displayName="Drawer.Handle";var Ku="DropdownMenu",[i4]=Ts(Ku,[Pw]),yn=Pw(),[l4,lS]=i4(Ku),cS=t=>{const{__scopeDropdownMenu:n,children:r,dir:s,open:i,defaultOpen:c,onOpenChange:u,modal:f=!0}=t,g=yn(n),p=b.useRef(null),[y,v]=Bh({prop:i,defaultProp:c??!1,onChange:u,caller:Ku});return h.jsx(l4,{scope:n,triggerId:To(),triggerRef:p,contentId:To(),open:y,onOpenChange:v,onOpenToggle:b.useCallback(()=>v(w=>!w),[v]),modal:f,children:h.jsx(kD,{...g,open:y,onOpenChange:v,dir:s,modal:f,children:r})})};cS.displayName=Ku;var uS="DropdownMenuTrigger",dS=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,disabled:s=!1,...i}=t,c=lS(uS,r),u=yn(r);return h.jsx(MD,{asChild:!0,...u,children:h.jsx(kt.button,{type:"button",id:c.triggerId,"aria-haspopup":"menu","aria-expanded":c.open,"aria-controls":c.open?c.contentId:void 0,"data-state":c.open?"open":"closed","data-disabled":s?"":void 0,disabled:s,...i,ref:hl(n,c.triggerRef),onPointerDown:qe(t.onPointerDown,f=>{!s&&f.button===0&&f.ctrlKey===!1&&(c.onOpenToggle(),c.open||f.preventDefault())}),onKeyDown:qe(t.onKeyDown,f=>{s||(["Enter"," "].includes(f.key)&&c.onOpenToggle(),f.key==="ArrowDown"&&c.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(f.key)&&f.preventDefault())})})})});dS.displayName=uS;var c4="DropdownMenuPortal",fS=t=>{const{__scopeDropdownMenu:n,...r}=t,s=yn(n);return h.jsx(DD,{...s,...r})};fS.displayName=c4;var mS="DropdownMenuContent",hS=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=lS(mS,r),c=yn(r),u=b.useRef(!1);return h.jsx(zD,{id:i.contentId,"aria-labelledby":i.triggerId,...c,...s,ref:n,onCloseAutoFocus:qe(t.onCloseAutoFocus,f=>{var g;u.current||(g=i.triggerRef.current)==null||g.focus(),u.current=!1,f.preventDefault()}),onInteractOutside:qe(t.onInteractOutside,f=>{const g=f.detail.originalEvent,p=g.button===0&&g.ctrlKey===!0,y=g.button===2||p;(!i.modal||y)&&(u.current=!0)}),style:{...t.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)"}})});hS.displayName=mS;var u4="DropdownMenuGroup",d4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(LD,{...i,...s,ref:n})});d4.displayName=u4;var f4="DropdownMenuLabel",m4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(UD,{...i,...s,ref:n})});m4.displayName=f4;var h4="DropdownMenuItem",pS=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(BD,{...i,...s,ref:n})});pS.displayName=h4;var p4="DropdownMenuCheckboxItem",g4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(PD,{...i,...s,ref:n})});g4.displayName=p4;var v4="DropdownMenuRadioGroup",y4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(HD,{...i,...s,ref:n})});y4.displayName=v4;var b4="DropdownMenuRadioItem",x4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(VD,{...i,...s,ref:n})});x4.displayName=b4;var w4="DropdownMenuItemIndicator",S4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(ID,{...i,...s,ref:n})});S4.displayName=w4;var E4="DropdownMenuSeparator",_4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(qD,{...i,...s,ref:n})});_4.displayName=E4;var C4="DropdownMenuArrow",N4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(FD,{...i,...s,ref:n})});N4.displayName=C4;var R4="DropdownMenuSubTrigger",A4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx($D,{...i,...s,ref:n})});A4.displayName=R4;var T4="DropdownMenuSubContent",O4=b.forwardRef((t,n)=>{const{__scopeDropdownMenu:r,...s}=t,i=yn(r);return h.jsx(GD,{...i,...s,ref:n,style:{...t.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)"}})});O4.displayName=T4;var j4=cS,k4=dS,M4=fS,D4=hS,z4=pS,bl=t=>t.type==="checkbox",ws=t=>t instanceof Date,On=t=>t==null;const gS=t=>typeof t=="object";var Ut=t=>!On(t)&&!Array.isArray(t)&&gS(t)&&!ws(t),L4=t=>Ut(t)&&t.target?bl(t.target)?t.target.checked:t.target.value:t,vS=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,U4=(t,n)=>t.has(vS(n)),B4=t=>{const n=t.constructor&&t.constructor.prototype;return Ut(n)&&n.hasOwnProperty("isPrototypeOf")},ip=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Qt(t){if(t instanceof Date)return new Date(t);const n=typeof FileList<"u"&&t instanceof FileList;if(ip&&(t instanceof Blob||n))return t;const r=Array.isArray(t);if(!r&&!(Ut(t)&&B4(t)))return t;const s=r?[]:Object.create(Object.getPrototypeOf(t));for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=Qt(t[i]));return s}var Qu=t=>/^\w*$/.test(t),At=t=>t===void 0,lp=t=>Array.isArray(t)?t.filter(Boolean):[],cp=t=>lp(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Ce=(t,n,r)=>{if(!n||!Ut(t))return r;const s=(Qu(n)?[n]:cp(n)).reduce((i,c)=>On(i)?i:i[c],t);return At(s)||s===t?At(t[n])?r:t[n]:s},Na=t=>typeof t=="boolean",ha=t=>typeof t=="function",xt=(t,n,r)=>{let s=-1;const i=Qu(n)?[n]:cp(n),c=i.length,u=c-1;for(;++s<c;){const f=i[s];let g=r;if(s!==u){const p=t[f];g=Ut(p)||Array.isArray(p)?p:isNaN(+i[s+1])?{}:[]}if(f==="__proto__"||f==="constructor"||f==="prototype")return;t[f]=g,t=t[f]}};const So={BLUR:"blur",FOCUS_OUT:"focusout",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},pa={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ma={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},Bm="form",yS="root",P4=ae.createContext(null);P4.displayName="HookFormControlContext";var H4=(t,n,r,s=!0)=>{const i={defaultValues:n._defaultValues};for(const c in t)Object.defineProperty(i,c,{get:()=>{const u=c;return n._proxyFormState[u]!==pa.all&&(n._proxyFormState[u]=!s||pa.all),t[u]}});return i};const V4=typeof window<"u"?ae.useLayoutEffect:ae.useEffect;var vn=t=>typeof t=="string",I4=(t,n,r,s,i)=>vn(t)?(s&&n.watch.add(t),Ce(r,t,i)):Array.isArray(t)?t.map(c=>(s&&n.watch.add(c),Ce(r,c))):(s&&(n.watchAll=!0),r),uh=t=>On(t)||!gS(t);function Vr(t,n,r=new WeakSet){if(uh(t)||uh(n))return Object.is(t,n);if(ws(t)&&ws(n))return Object.is(t.getTime(),n.getTime());const s=Object.keys(t),i=Object.keys(n);if(s.length!==i.length)return!1;if(r.has(t)||r.has(n))return!0;r.add(t),r.add(n);for(const c of s){const u=t[c];if(!i.includes(c))return!1;if(c!=="ref"){const f=n[c];if(ws(u)&&ws(f)||Ut(u)&&Ut(f)||Array.isArray(u)&&Array.isArray(f)?!Vr(u,f,r):!Object.is(u,f))return!1}}return!0}const q4=ae.createContext(null);q4.displayName="HookFormContext";var up=(t,n,r,s,i)=>n?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[s]:i||!0}}:{},Qi=t=>Array.isArray(t)?t:[t],zx=()=>{let t=[];return{get observers(){return t},next:i=>{for(const c of t)c.next&&c.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(c=>c!==i)}}),unsubscribe:()=>{t=[]}}};function bS(t,n){const r={};for(const s in t)if(t.hasOwnProperty(s)){const i=t[s],c=n[s];if(i&&Ut(i)&&c){const u=bS(i,c);Ut(u)&&(r[s]=u)}else t[s]&&(r[s]=c)}return r}var gn=t=>Ut(t)&&!Object.keys(t).length,dp=t=>t.type==="file",du=t=>{if(!ip)return!1;const n=t?t.ownerDocument:0;return t instanceof(n&&n.defaultView?n.defaultView.HTMLElement:HTMLElement)},xS=t=>t.type==="select-multiple",fp=t=>t.type==="radio",F4=t=>fp(t)||bl(t),Pm=t=>du(t)&&t.isConnected;function $4(t,n){const r=n.slice(0,-1).length;let s=0;for(;s<r;)t=At(t)?s++:t[n[s++]];return t}function G4(t){for(const n in t)if(t.hasOwnProperty(n)&&!At(t[n]))return!1;return!0}function $t(t,n){const r=Array.isArray(n)?n:Qu(n)?[n]:cp(n),s=r.length===1?t:$4(t,r),i=r.length-1,c=r[i];return s&&delete s[c],i!==0&&(Ut(s)&&gn(s)||Array.isArray(s)&&G4(s))&&$t(t,r.slice(0,-1)),t}var Y4=t=>{for(const n in t)if(ha(t[n]))return!0;return!1};function wS(t){return Array.isArray(t)||Ut(t)&&!Y4(t)}function dh(t,n={}){for(const r in t){const s=t[r];wS(s)?(n[r]=Array.isArray(s)?[]:{},dh(s,n[r])):At(s)||(n[r]=!0)}return n}function Co(t,n,r){r||(r=dh(n));for(const s in t){const i=t[s];if(wS(i))At(n)||uh(r[s])?r[s]=dh(i,Array.isArray(i)?[]:{}):Co(i,On(n)?{}:n[s],r[s]);else{const c=n[s];r[s]=!Vr(i,c)}}return r}const Lx={value:!1,isValid:!1},Ux={value:!0,isValid:!0};var SS=t=>{if(Array.isArray(t)){if(t.length>1){const n=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:n,isValid:!!n.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!At(t[0].attributes.value)?At(t[0].value)||t[0].value===""?Ux:{value:t[0].value,isValid:!0}:Ux:Lx}return Lx},ES=(t,{valueAsNumber:n,valueAsDate:r,setValueAs:s})=>At(t)?t:n?t===""?NaN:t&&+t:r&&vn(t)?new Date(t):s?s(t):t;const Bx={isValid:!1,value:null};var _S=t=>Array.isArray(t)?t.reduce((n,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:n,Bx):Bx;function Px(t){const n=t.ref;return dp(n)?n.files:fp(n)?_S(t.refs).value:xS(n)?[...n.selectedOptions].map(({value:r})=>r):bl(n)?SS(t.refs).value:ES(At(n.value)?t.ref.value:n.value,t)}var Z4=(t,n,r,s)=>{const i={};for(const c of t){const u=Ce(n,c);u&&xt(i,c,u._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:s}},fu=t=>t instanceof RegExp,$i=t=>At(t)?t:fu(t)?t.source:Ut(t)?fu(t.value)?t.value.source:t.value:t,Hx=t=>({isOnSubmit:!t||t===pa.onSubmit,isOnBlur:t===pa.onBlur,isOnChange:t===pa.onChange,isOnAll:t===pa.all,isOnTouch:t===pa.onTouched});const Vx="AsyncFunction";var X4=t=>!!t&&!!t.validate&&!!(ha(t.validate)&&t.validate.constructor.name===Vx||Ut(t.validate)&&Object.values(t.validate).find(n=>n.constructor.name===Vx)),K4=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),Ix=(t,n,r)=>!r&&(n.watchAll||n.watch.has(t)||[...n.watch].some(s=>t.startsWith(s)&&/^\.\w+/.test(t.slice(s.length))));const Wi=(t,n,r,s)=>{for(const i of r||Object.keys(t)){const c=Ce(t,i);if(c){const{_f:u,...f}=c;if(u){if(u.refs&&u.refs[0]&&n(u.refs[0],i)&&!s)return!0;if(u.ref&&n(u.ref,u.name)&&!s)return!0;if(Wi(f,n))break}else if(Ut(f)&&Wi(f,n))break}}};function qx(t,n,r){const s=Ce(t,r);if(s||Qu(r))return{error:s,name:r};const i=r.split(".");for(;i.length;){const c=i.join("."),u=Ce(n,c),f=Ce(t,c);if(u&&!Array.isArray(u)&&r!==c)return{name:r};if(f&&f.type)return{name:c,error:f};if(f&&f.root&&f.root.type)return{name:`${c}.root`,error:f.root};i.pop()}return{name:r}}var Q4=(t,n,r,s)=>{r(t);const{name:i,...c}=t;return gn(c)||Object.keys(c).length>=Object.keys(n).length||Object.keys(c).find(u=>n[u]===(!s||pa.all))},W4=(t,n,r)=>!t||!n||t===n||Qi(t).some(s=>s&&(r?s===n:s.startsWith(n)||n.startsWith(s))),J4=(t,n,r,s,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(n||t):(r?s.isOnBlur:i.isOnBlur)?!t:(r?s.isOnChange:i.isOnChange)?t:!0,ez=(t,n)=>!lp(Ce(t,n)).length&&$t(t,n),tz=(t,n,r)=>{const s=Qi(Ce(t,r));return xt(s,yS,n[r]),xt(t,r,s),t};function Fx(t,n,r="validate"){if(vn(t)||Array.isArray(t)&&t.every(vn)||Na(t)&&!t)return{type:r,message:vn(t)?t:"",ref:n}}var Eo=t=>Ut(t)&&!fu(t)?t:{value:t,message:""},$x=async(t,n,r,s,i,c)=>{const{ref:u,refs:f,required:g,maxLength:p,minLength:y,min:v,max:w,pattern:C,validate:S,name:_,valueAsNumber:E,mount:R}=t._f,k=Ce(r,_);if(!R||n.has(_))return{};const A=f?f[0]:u,D=se=>{i&&A.reportValidity&&(A.setCustomValidity(Na(se)?"":se||""),A.reportValidity())},H={},$=fp(u),U=bl(u),F=$||U,de=(E||dp(u))&&At(u.value)&&At(k)||du(u)&&u.value===""||k===""||Array.isArray(k)&&!k.length,fe=up.bind(null,_,s,H),me=(se,G,he,ve=ma.maxLength,T=ma.minLength)=>{const K=se?G:he;H[_]={type:se?ve:T,message:K,ref:u,...fe(se?ve:T,K)}};if(c?!Array.isArray(k)||!k.length:g&&(!F&&(de||On(k))||Na(k)&&!k||U&&!SS(f).isValid||$&&!_S(f).isValid)){const{value:se,message:G}=vn(g)?{value:!!g,message:g}:Eo(g);if(se&&(H[_]={type:ma.required,message:G,ref:A,...fe(ma.required,G)},!s))return D(G),H}if(!de&&(!On(v)||!On(w))){let se,G;const he=Eo(w),ve=Eo(v);if(!On(k)&&!isNaN(k)){const T=u.valueAsNumber||k&&+k;On(he.value)||(se=T>he.value),On(ve.value)||(G=T<ve.value)}else{const T=u.valueAsDate||new Date(k),K=ne=>new Date(new Date().toDateString()+" "+ne),te=u.type=="time",le=u.type=="week";vn(he.value)&&k&&(se=te?K(k)>K(he.value):le?k>he.value:T>new Date(he.value)),vn(ve.value)&&k&&(G=te?K(k)<K(ve.value):le?k<ve.value:T<new Date(ve.value))}if((se||G)&&(me(!!se,he.message,ve.message,ma.max,ma.min),!s))return D(H[_].message),H}if((p||y)&&!de&&(vn(k)||c&&Array.isArray(k))){const se=Eo(p),G=Eo(y),he=!On(se.value)&&k.length>+se.value,ve=!On(G.value)&&k.length<+G.value;if((he||ve)&&(me(he,se.message,G.message),!s))return D(H[_].message),H}if(C&&!de&&vn(k)){const{value:se,message:G}=Eo(C);if(fu(se)&&!k.match(se)&&(H[_]={type:ma.pattern,message:G,ref:u,...fe(ma.pattern,G)},!s))return D(G),H}if(S){if(ha(S)){const se=await S(k,r),G=Fx(se,A);if(G&&(H[_]={...G,...fe(ma.validate,G.message)},!s))return D(G.message),H}else if(Ut(S)){let se={};for(const G in S){if(!gn(se)&&!s)break;const he=Fx(await S[G](k,r),A,G);he&&(se={...he,...fe(G,he.message)},D(he.message),s&&(H[_]=se))}if(!gn(se)&&(H[_]={ref:A,...se},!s))return H}}return D(!0),H};const nz={mode:pa.onSubmit,reValidateMode:pa.onChange,shouldFocusError:!0};function az(t={}){let n={...nz,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:ha(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:n.errors||{},disabled:n.disabled||!1},s={},i=Ut(n.defaultValues)||Ut(n.values)?Qt(n.defaultValues||n.values)||{}:{},c=n.shouldUnregister?{}:Qt(i),u={action:!1,mount:!1,watch:!1,keepIsValid:!1},f={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},g,p=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},v={...y};let w={...v};const C={array:zx(),state:zx()},S=n.criteriaMode===pa.all,_=O=>B=>{clearTimeout(p),p=setTimeout(O,B)},E=async O=>{if(!u.keepIsValid&&!n.disabled&&(v.isValid||w.isValid||O)){let B;n.resolver?(B=gn((await F()).errors),R()):B=await me({fields:s,onlyCheckValid:!0,eventType:So.VALID}),B!==r.isValid&&C.state.next({isValid:B})}},R=(O,B)=>{!n.disabled&&(v.isValidating||v.validatingFields||w.isValidating||w.validatingFields)&&((O||Array.from(f.mount)).forEach(V=>{V&&(B?xt(r.validatingFields,V,B):$t(r.validatingFields,V))}),C.state.next({validatingFields:r.validatingFields,isValidating:!gn(r.validatingFields)}))},k=(O,B=[],V,we,ge=!0,ye=!0)=>{if(we&&V&&!n.disabled){if(u.action=!0,ye&&Array.isArray(Ce(s,O))){const Se=V(Ce(s,O),we.argA,we.argB);ge&&xt(s,O,Se)}if(ye&&Array.isArray(Ce(r.errors,O))){const Se=V(Ce(r.errors,O),we.argA,we.argB);ge&&xt(r.errors,O,Se),ez(r.errors,O)}if((v.touchedFields||w.touchedFields)&&ye&&Array.isArray(Ce(r.touchedFields,O))){const Se=V(Ce(r.touchedFields,O),we.argA,we.argB);ge&&xt(r.touchedFields,O,Se)}if(v.dirtyFields||w.dirtyFields){const Se=Co(i,c),Ue=vS(O);xt(r.dirtyFields,Ue,Ce(Se,Ue))}C.state.next({name:O,isDirty:G(O,B),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else xt(c,O,B)},A=(O,B)=>{xt(r.errors,O,B),C.state.next({errors:r.errors})},D=O=>{r.errors=O,C.state.next({errors:r.errors,isValid:!1})},H=(O,B,V,we)=>{const ge=Ce(s,O);if(ge){const ye=Ce(c,O,At(V)?Ce(i,O):V);At(ye)||we&&we.defaultChecked||B?xt(c,O,B?ye:Px(ge._f)):T(O,ye),u.mount&&!u.action&&E()}},$=(O,B,V,we,ge)=>{let ye=!1,Se=!1;const Ue={name:O};if(!n.disabled){if(!V||we){(v.isDirty||w.isDirty)&&(Se=r.isDirty,r.isDirty=Ue.isDirty=G(),ye=Se!==Ue.isDirty);const Ge=Vr(Ce(i,O),B);Se=!!Ce(r.dirtyFields,O),Ge?$t(r.dirtyFields,O):xt(r.dirtyFields,O,!0),Ue.dirtyFields=r.dirtyFields,ye=ye||(v.dirtyFields||w.dirtyFields)&&Se!==!Ge}if(V){const Ge=Ce(r.touchedFields,O);Ge||(xt(r.touchedFields,O,V),Ue.touchedFields=r.touchedFields,ye=ye||(v.touchedFields||w.touchedFields)&&Ge!==V)}ye&&ge&&C.state.next(Ue)}return ye?Ue:{}},U=(O,B,V,we)=>{const ge=Ce(r.errors,O),ye=(v.isValid||w.isValid)&&Na(B)&&r.isValid!==B;if(n.delayError&&V?(g=_(()=>A(O,V)),g(n.delayError)):(clearTimeout(p),g=null,V?xt(r.errors,O,V):$t(r.errors,O)),(V?!Vr(ge,V):ge)||!gn(we)||ye){const Se={...we,...ye&&Na(B)?{isValid:B}:{},errors:r.errors,name:O};r={...r,...Se},C.state.next(Se)}},F=async O=>(R(O,!0),await n.resolver(c,n.context,Z4(O||f.mount,s,n.criteriaMode,n.shouldUseNativeValidation))),de=async O=>{const{errors:B}=await F(O);if(R(O),O)for(const V of O){const we=Ce(B,V);we?xt(r.errors,V,we):$t(r.errors,V)}else r.errors=B;return B},fe=async({name:O,eventType:B})=>{if(t.validate){const V=await t.validate({formValues:c,formState:r,name:O,eventType:B});if(Ut(V))for(const we in V)V[we]&&J(`${Bm}.${we}`,{message:vn(V.message)?V.message:"",type:ma.validate});else vn(V)||!V?J(Bm,{message:V||"",type:ma.validate}):Y(Bm);return V}return!0},me=async({fields:O,onlyCheckValid:B,name:V,eventType:we,context:ge={valid:!0,runRootValidation:!1}})=>{if(t.validate&&(ge.runRootValidation=!0,!await fe({name:V,eventType:we})&&(ge.valid=!1,B)))return ge.valid;for(const ye in O){const Se=O[ye];if(Se){const{_f:Ue,...Ge}=Se;if(Ue){const Pt=f.array.has(Ue.name),Mt=Se._f&&X4(Se._f);Mt&&v.validatingFields&&R([Ue.name],!0);const mt=await $x(Se,f.disabled,c,S,n.shouldUseNativeValidation&&!B,Pt);if(Mt&&v.validatingFields&&R([Ue.name]),mt[Ue.name]&&(ge.valid=!1,B)||(!B&&(Ce(mt,Ue.name)?Pt?tz(r.errors,mt,Ue.name):xt(r.errors,Ue.name,mt[Ue.name]):$t(r.errors,Ue.name)),t.shouldUseNativeValidation&&mt[Ue.name]))break}!gn(Ge)&&await me({context:ge,onlyCheckValid:B,fields:Ge,name:ye,eventType:we})}}return ge.valid},se=()=>{for(const O of f.unMount){const B=Ce(s,O);B&&(B._f.refs?B._f.refs.every(V=>!Pm(V)):!Pm(B._f.ref))&&oe(O)}f.unMount=new Set},G=(O,B)=>!n.disabled&&(O&&B&&xt(c,O,B),!Vr(X(),i)),he=(O,B,V)=>I4(O,f,{...u.mount?c:At(B)?i:vn(O)?{[O]:B}:B},V,B),ve=O=>lp(Ce(u.mount?c:i,O,n.shouldUnregister?Ce(i,O,[]):[])),T=(O,B,V={})=>{const we=Ce(s,O);let ge=B;if(we){const ye=we._f;ye&&(!ye.disabled&&xt(c,O,ES(B,ye)),ge=du(ye.ref)&&On(B)?"":B,xS(ye.ref)?[...ye.ref.options].forEach(Se=>Se.selected=ge.includes(Se.value)):ye.refs?bl(ye.ref)?ye.refs.forEach(Se=>{(!Se.defaultChecked||!Se.disabled)&&(Array.isArray(ge)?Se.checked=!!ge.find(Ue=>Ue===Se.value):Se.checked=ge===Se.value||!!ge)}):ye.refs.forEach(Se=>Se.checked=Se.value===ge):dp(ye.ref)?ye.ref.value="":(ye.ref.value=ge,ye.ref.type||C.state.next({name:O,values:Qt(c)})))}(V.shouldDirty||V.shouldTouch)&&$(O,ge,V.shouldTouch,V.shouldDirty,!0),V.shouldValidate&&j(O)},K=(O,B,V)=>{for(const we in B){if(!B.hasOwnProperty(we))return;const ge=B[we],ye=O+"."+we,Se=Ce(s,ye);(f.array.has(O)||Ut(ge)||Se&&!Se._f)&&!ws(ge)?K(ye,ge,V):T(ye,ge,V)}},te=(O,B,V={})=>{const we=Ce(s,O),ge=f.array.has(O),ye=Qt(B);xt(c,O,ye),ge?(C.array.next({name:O,values:Qt(c)}),(v.isDirty||v.dirtyFields||w.isDirty||w.dirtyFields)&&V.shouldDirty&&C.state.next({name:O,dirtyFields:Co(i,c),isDirty:G(O,ye)})):we&&!we._f&&!On(ye)?K(O,ye,V):T(O,ye,V),Ix(O,f)?C.state.next({...r,name:O,values:Qt(c)}):C.state.next({name:u.mount?O:void 0,values:Qt(c)})},le=async O=>{u.mount=!0;const B=O.target;let V=B.name,we=!0;const ge=Ce(s,V),ye=Ge=>{we=Number.isNaN(Ge)||ws(Ge)&&isNaN(Ge.getTime())||Vr(Ge,Ce(c,V,Ge))},Se=Hx(n.mode),Ue=Hx(n.reValidateMode);if(ge){let Ge,Pt;const Mt=B.type?Px(ge._f):L4(O),mt=O.type===So.BLUR||O.type===So.FOCUS_OUT,Dt=!K4(ge._f)&&!t.validate&&!n.resolver&&!Ce(r.errors,V)&&!ge._f.deps||J4(mt,Ce(r.touchedFields,V),r.isSubmitted,Ue,Se),an=Ix(V,f,mt);xt(c,V,Mt),mt?(!B||!B.readOnly)&&(ge._f.onBlur&&ge._f.onBlur(O),g&&g(0)):ge._f.onChange&&ge._f.onChange(O);const Ht=$(V,Mt,mt),Ko=!gn(Ht)||an;if(!mt&&C.state.next({name:V,type:O.type,values:Qt(c)}),Dt)return(v.isValid||w.isValid)&&(n.mode==="onBlur"?mt&&E():mt||E()),Ko&&C.state.next({name:V,...an?{}:Ht});if(!n.resolver&&t.validate&&await fe({name:V,eventType:O.type}),!mt&&an&&C.state.next({...r}),n.resolver){const{errors:ur}=await F([V]);if(R([V]),ye(Mt),we){const Yn=qx(r.errors,s,V),Ua=qx(ur,s,Yn.name||V);Ge=Ua.error,V=Ua.name,Pt=gn(ur)}}else R([V],!0),Ge=(await $x(ge,f.disabled,c,S,n.shouldUseNativeValidation))[V],R([V]),ye(Mt),we&&(Ge?Pt=!1:(v.isValid||w.isValid)&&(Pt=await me({fields:s,onlyCheckValid:!0,name:V,eventType:O.type})));we&&(ge._f.deps&&(!Array.isArray(ge._f.deps)||ge._f.deps.length>0)&&j(ge._f.deps),U(V,Pt,Ge,Ht))}},ne=(O,B)=>{if(Ce(r.errors,B)&&O.focus)return O.focus(),1},j=async(O,B={})=>{let V,we;const ge=Qi(O);if(n.resolver){const ye=await de(At(O)?O:ge);V=gn(ye),we=O?!ge.some(Se=>Ce(ye,Se)):V}else O?(we=(await Promise.all(ge.map(async ye=>{const Se=Ce(s,ye);return await me({fields:Se&&Se._f?{[ye]:Se}:Se,eventType:So.TRIGGER})}))).every(Boolean),!(!we&&!r.isValid)&&E()):we=V=await me({fields:s,name:O,eventType:So.TRIGGER});return C.state.next({...!vn(O)||(v.isValid||w.isValid)&&V!==r.isValid?{}:{name:O},...n.resolver||!O?{isValid:V}:{},errors:r.errors}),B.shouldFocus&&!we&&Wi(s,ne,O?ge:f.mount),we},X=(O,B)=>{let V={...u.mount?c:i};return B&&(V=bS(B.dirtyFields?r.dirtyFields:r.touchedFields,V)),At(O)?V:vn(O)?Ce(V,O):O.map(we=>Ce(V,we))},L=(O,B)=>({invalid:!!Ce((B||r).errors,O),isDirty:!!Ce((B||r).dirtyFields,O),error:Ce((B||r).errors,O),isValidating:!!Ce(r.validatingFields,O),isTouched:!!Ce((B||r).touchedFields,O)}),Y=O=>{const B=O?Qi(O):void 0;B==null||B.forEach(V=>$t(r.errors,V)),B?B.forEach(V=>{C.state.next({name:V,errors:r.errors})}):C.state.next({errors:{}})},J=(O,B,V)=>{const we=(Ce(s,O,{_f:{}})._f||{}).ref,ge=Ce(r.errors,O)||{},{ref:ye,message:Se,type:Ue,...Ge}=ge;xt(r.errors,O,{...Ge,...B,ref:we}),C.state.next({name:O,errors:r.errors,isValid:!1}),V&&V.shouldFocus&&we&&we.focus&&we.focus()},ie=(O,B)=>ha(O)?C.state.subscribe({next:V=>"values"in V&&O(he(void 0,B),V)}):he(O,B,!0),pe=O=>C.state.subscribe({next:B=>{W4(O.name,B.name,O.exact)&&Q4(B,O.formState||v,Pe,O.reRenderRoot)&&O.callback({values:{...c},...r,...B,defaultValues:i})}}).unsubscribe,Q=O=>(u.mount=!0,w={...w,...O.formState},pe({...O,formState:{...y,...O.formState}})),oe=(O,B={})=>{for(const V of O?Qi(O):f.mount)f.mount.delete(V),f.array.delete(V),B.keepValue||($t(s,V),$t(c,V)),!B.keepError&&$t(r.errors,V),!B.keepDirty&&$t(r.dirtyFields,V),!B.keepTouched&&$t(r.touchedFields,V),!B.keepIsValidating&&$t(r.validatingFields,V),!n.shouldUnregister&&!B.keepDefaultValue&&$t(i,V);C.state.next({values:Qt(c)}),C.state.next({...r,...B.keepDirty?{isDirty:G()}:{}}),!B.keepIsValid&&E()},Re=({disabled:O,name:B})=>{if(Na(O)&&u.mount||O||f.disabled.has(B)){const ge=f.disabled.has(B)!==!!O;O?f.disabled.add(B):f.disabled.delete(B),ge&&u.mount&&!u.action&&E()}},et=(O,B={})=>{let V=Ce(s,O);const we=Na(B.disabled)||Na(n.disabled);return xt(s,O,{...V||{},_f:{...V&&V._f?V._f:{ref:{name:O}},name:O,mount:!0,...B}}),f.mount.add(O),V?Re({disabled:Na(B.disabled)?B.disabled:n.disabled,name:O}):H(O,!0,B.value),{...we?{disabled:B.disabled||n.disabled}:{},...n.progressive?{required:!!B.required,min:$i(B.min),max:$i(B.max),minLength:$i(B.minLength),maxLength:$i(B.maxLength),pattern:$i(B.pattern)}:{},name:O,onChange:le,onBlur:le,ref:ge=>{if(ge){et(O,B),V=Ce(s,O);const ye=At(ge.value)&&ge.querySelectorAll&&ge.querySelectorAll("input,select,textarea")[0]||ge,Se=F4(ye),Ue=V._f.refs||[];if(Se?Ue.find(Ge=>Ge===ye):ye===V._f.ref)return;xt(s,O,{_f:{...V._f,...Se?{refs:[...Ue.filter(Pm),ye,...Array.isArray(Ce(i,O))?[{}]:[]],ref:{type:ye.type,name:O}}:{ref:ye}}}),H(O,!1,void 0,ye)}else V=Ce(s,O,{}),V._f&&(V._f.mount=!1),(n.shouldUnregister||B.shouldUnregister)&&!(U4(f.array,O)&&u.action)&&f.unMount.add(O)}}},Me=()=>n.shouldFocusError&&Wi(s,ne,f.mount),ze=O=>{Na(O)&&(C.state.next({disabled:O}),Wi(s,(B,V)=>{const we=Ce(s,V);we&&(B.disabled=we._f.disabled||O,Array.isArray(we._f.refs)&&we._f.refs.forEach(ge=>{ge.disabled=we._f.disabled||O}))},0,!1))},be=(O,B)=>async V=>{let we;V&&(V.preventDefault&&V.preventDefault(),V.persist&&V.persist());let ge=Qt(c);if(C.state.next({isSubmitting:!0}),n.resolver){const{errors:ye,values:Se}=await F();R(),r.errors=ye,ge=Qt(Se)}else await me({fields:s,eventType:So.SUBMIT});if(f.disabled.size)for(const ye of f.disabled)$t(ge,ye);if($t(r.errors,yS),gn(r.errors)){C.state.next({errors:{}});try{await O(ge,V)}catch(ye){we=ye}}else B&&await B({...r.errors},V),Me(),setTimeout(Me);if(C.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:gn(r.errors)&&!we,submitCount:r.submitCount+1,errors:r.errors}),we)throw we},je=(O,B={})=>{Ce(s,O)&&(At(B.defaultValue)?te(O,Qt(Ce(i,O))):(te(O,B.defaultValue),xt(i,O,Qt(B.defaultValue))),B.keepTouched||$t(r.touchedFields,O),B.keepDirty||($t(r.dirtyFields,O),r.isDirty=B.defaultValue?G(O,Qt(Ce(i,O))):G()),B.keepError||($t(r.errors,O),v.isValid&&E()),C.state.next({...r}))},at=(O,B={})=>{const V=O?Qt(O):i,we=Qt(V),ge=gn(O),ye=ge?i:we;if(B.keepDefaultValues||(i=V),!B.keepValues){if(B.keepDirtyValues){const Se=new Set([...f.mount,...Object.keys(Co(i,c))]);for(const Ue of Array.from(Se)){const Ge=Ce(r.dirtyFields,Ue),Pt=Ce(c,Ue),Mt=Ce(ye,Ue);Ge&&!At(Pt)?xt(ye,Ue,Pt):!Ge&&!At(Mt)&&te(Ue,Mt)}}else{if(ip&&At(O))for(const Se of f.mount){const Ue=Ce(s,Se);if(Ue&&Ue._f){const Ge=Array.isArray(Ue._f.refs)?Ue._f.refs[0]:Ue._f.ref;if(du(Ge)){const Pt=Ge.closest("form");if(Pt){Pt.reset();break}}}}if(B.keepFieldsRef)for(const Se of f.mount)te(Se,Ce(ye,Se));else s={}}c=n.shouldUnregister?B.keepDefaultValues?Qt(i):{}:Qt(ye),C.array.next({values:{...ye}}),C.state.next({values:{...ye}})}f={mount:B.keepDirtyValues?f.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},u.mount=!v.isValid||!!B.keepIsValid||!!B.keepDirtyValues||!n.shouldUnregister&&!gn(ye),u.watch=!!n.shouldUnregister,u.keepIsValid=!!B.keepIsValid,u.action=!1,B.keepErrors||(r.errors={}),C.state.next({submitCount:B.keepSubmitCount?r.submitCount:0,isDirty:ge?!1:B.keepDirty?r.isDirty:!!(B.keepDefaultValues&&!Vr(O,i)),isSubmitted:B.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:ge?{}:B.keepDirtyValues?B.keepDefaultValues&&c?Co(i,c):r.dirtyFields:B.keepDefaultValues&&O?Co(i,O):B.keepDirty?r.dirtyFields:{},touchedFields:B.keepTouched?r.touchedFields:{},errors:B.keepErrors?r.errors:{},isSubmitSuccessful:B.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},ht=(O,B)=>at(ha(O)?O(c):O,{...n.resetOptions,...B}),Qe=(O,B={})=>{const V=Ce(s,O),we=V&&V._f;if(we){const ge=we.refs?we.refs[0]:we.ref;ge.focus&&setTimeout(()=>{ge.focus(),B.shouldSelect&&ha(ge.select)&&ge.select()})}},Pe=O=>{r={...r,...O}},Zt={control:{register:et,unregister:oe,getFieldState:L,handleSubmit:be,setError:J,_subscribe:pe,_runSchema:F,_updateIsValidating:R,_focusError:Me,_getWatch:he,_getDirty:G,_setValid:E,_setFieldArray:k,_setDisabledField:Re,_setErrors:D,_getFieldArray:ve,_reset:at,_resetDefaultValues:()=>ha(n.defaultValues)&&n.defaultValues().then(O=>{ht(O,n.resetOptions),C.state.next({isLoading:!1})}),_removeUnmounted:se,_disableForm:ze,_subjects:C,_proxyFormState:v,get _fields(){return s},get _formValues(){return c},get _state(){return u},set _state(O){u=O},get _defaultValues(){return i},get _names(){return f},set _names(O){f=O},get _formState(){return r},get _options(){return n},set _options(O){n={...n,...O}}},subscribe:Q,trigger:j,register:et,handleSubmit:be,watch:ie,setValue:te,getValues:X,reset:ht,resetField:je,clearErrors:Y,unregister:oe,setError:J,setFocus:Qe,getFieldState:L};return{...Zt,formControl:Zt}}function Lo(t={}){const n=ae.useRef(void 0),r=ae.useRef(void 0),[s,i]=ae.useState({isDirty:!1,isValidating:!1,isLoading:ha(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:ha(t.defaultValues)?void 0:t.defaultValues});if(!n.current)if(t.formControl)n.current={...t.formControl,formState:s},t.defaultValues&&!ha(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:u,...f}=az(t);n.current={...f,formState:s}}const c=n.current.control;return c._options=t,V4(()=>{const u=c._subscribe({formState:c._proxyFormState,callback:()=>i({...c._formState}),reRenderRoot:!0});return i(f=>({...f,isReady:!0})),c._formState.isReady=!0,u},[c]),ae.useEffect(()=>c._disableForm(t.disabled),[c,t.disabled]),ae.useEffect(()=>{t.mode&&(c._options.mode=t.mode),t.reValidateMode&&(c._options.reValidateMode=t.reValidateMode)},[c,t.mode,t.reValidateMode]),ae.useEffect(()=>{t.errors&&(c._setErrors(t.errors),c._focusError())},[c,t.errors]),ae.useEffect(()=>{t.shouldUnregister&&c._subjects.state.next({values:c._getWatch()})},[c,t.shouldUnregister]),ae.useEffect(()=>{if(c._proxyFormState.isDirty){const u=c._getDirty();u!==s.isDirty&&c._subjects.state.next({isDirty:u})}},[c,s.isDirty]),ae.useEffect(()=>{var u;t.values&&!Vr(t.values,r.current)?(c._reset(t.values,{keepFieldsRef:!0,...c._options.resetOptions}),!((u=c._options.resetOptions)===null||u===void 0)&&u.keepIsValid||c._setValid(),r.current=t.values,i(f=>({...f}))):c._resetDefaultValues()},[c,t.values]),ae.useEffect(()=>{c._state.mount||(c._setValid(),c._state.mount=!0),c._state.watch&&(c._state.watch=!1,c._subjects.state.next({...c._formState})),c._removeUnmounted()}),n.current.formState=ae.useMemo(()=>H4(s,c),[c,s]),n.current}var rz="Label",CS=b.forwardRef((t,n)=>h.jsx(jk.label,{...t,ref:n,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));CS.displayName=rz;var sz=CS,oz=Object.defineProperty,iz=Object.defineProperties,lz=Object.getOwnPropertyDescriptors,mu=Object.getOwnPropertySymbols,NS=Object.prototype.hasOwnProperty,RS=Object.prototype.propertyIsEnumerable,Gx=(t,n,r)=>n in t?oz(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r,cz=(t,n)=>{for(var r in n||(n={}))NS.call(n,r)&&Gx(t,r,n[r]);if(mu)for(var r of mu(n))RS.call(n,r)&&Gx(t,r,n[r]);return t},uz=(t,n)=>iz(t,lz(n)),dz=(t,n)=>{var r={};for(var s in t)NS.call(t,s)&&n.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&mu)for(var s of mu(t))n.indexOf(s)<0&&RS.call(t,s)&&(r[s]=t[s]);return r};function fz(t){let n=setTimeout(t,0),r=setTimeout(t,10),s=setTimeout(t,50);return[n,r,s]}function mz(t){let n=b.useRef();return b.useEffect(()=>{n.current=t}),n.current}var hz=18,AS=40,pz=`${AS}px`,gz=["[data-lastpass-icon-root]","com-1password-button","[data-dashlanecreated]",'[style$="2147483647 !important;"]'].join(",");function vz({containerRef:t,inputRef:n,pushPasswordManagerStrategy:r,isFocused:s}){let[i,c]=b.useState(!1),[u,f]=b.useState(!1),[g,p]=b.useState(!1),y=b.useMemo(()=>r==="none"?!1:(r==="increase-width"||r==="experimental-no-flickering")&&i&&u,[i,u,r]),v=b.useCallback(()=>{let w=t.current,C=n.current;if(!w||!C||g||r==="none")return;let S=w,_=S.getBoundingClientRect().left+S.offsetWidth,E=S.getBoundingClientRect().top+S.offsetHeight/2,R=_-hz,k=E;document.querySelectorAll(gz).length===0&&document.elementFromPoint(R,k)===w||(c(!0),p(!0))},[t,n,g,r]);return b.useEffect(()=>{let w=t.current;if(!w||r==="none")return;function C(){let _=window.innerWidth-w.getBoundingClientRect().right;f(_>=AS)}C();let S=setInterval(C,1e3);return()=>{clearInterval(S)}},[t,r]),b.useEffect(()=>{let w=s||document.activeElement===n.current;if(r==="none"||!w)return;let C=setTimeout(v,0),S=setTimeout(v,2e3),_=setTimeout(v,5e3),E=setTimeout(()=>{p(!0)},6e3);return()=>{clearTimeout(C),clearTimeout(S),clearTimeout(_),clearTimeout(E)}},[n,s,r,v]),{hasPWMBadge:i,willPushPWMBadge:y,PWM_BADGE_SPACE_WIDTH:pz}}var yz=b.createContext({}),bz=b.forwardRef((t,n)=>{var r=t,{value:s,onChange:i,maxLength:c,textAlign:u="left",pattern:f,placeholder:g,inputMode:p="numeric",onComplete:y,pushPasswordManagerStrategy:v="increase-width",pasteTransformer:w,containerClassName:C,noScriptCSSFallback:S=xz,render:_,children:E}=r,R=dz(r,["value","onChange","maxLength","textAlign","pattern","placeholder","inputMode","onComplete","pushPasswordManagerStrategy","pasteTransformer","containerClassName","noScriptCSSFallback","render","children"]),k,A,D,H,$;let[U,F]=b.useState(typeof R.defaultValue=="string"?R.defaultValue:""),de=s??U,fe=mz(de),me=b.useCallback(be=>{i==null||i(be),F(be)},[i]),se=b.useMemo(()=>f?typeof f=="string"?new RegExp(f):f:null,[f]),G=b.useRef(null),he=b.useRef(null),ve=b.useRef({value:de,onChange:me,isIOS:typeof window<"u"&&((A=(k=window==null?void 0:window.CSS)==null?void 0:k.supports)==null?void 0:A.call(k,"-webkit-touch-callout","none"))}),T=b.useRef({prev:[(D=G.current)==null?void 0:D.selectionStart,(H=G.current)==null?void 0:H.selectionEnd,($=G.current)==null?void 0:$.selectionDirection]});b.useImperativeHandle(n,()=>G.current,[]),b.useEffect(()=>{let be=G.current,je=he.current;if(!be||!je)return;ve.current.value!==be.value&&ve.current.onChange(be.value),T.current.prev=[be.selectionStart,be.selectionEnd,be.selectionDirection];function at(){if(document.activeElement!==be){X(null),Y(null);return}let Pe=be.selectionStart,Tt=be.selectionEnd,Zt=be.selectionDirection,O=be.maxLength,B=be.value,V=T.current.prev,we=-1,ge=-1,ye;if(B.length!==0&&Pe!==null&&Tt!==null){let Pt=Pe===Tt,Mt=Pe===B.length&&B.length<O;if(Pt&&!Mt){let mt=Pe;if(mt===0)we=0,ge=1,ye="forward";else if(mt===O)we=mt-1,ge=mt,ye="backward";else if(O>1&&B.length>1){let Dt=0;if(V[0]!==null&&V[1]!==null){ye=mt<V[1]?"backward":"forward";let an=V[0]===V[1]&&V[0]<O;ye==="backward"&&!an&&(Dt=-1)}we=Dt+mt,ge=Dt+mt+1}}we!==-1&&ge!==-1&&we!==ge&&G.current.setSelectionRange(we,ge,ye)}let Se=we!==-1?we:Pe,Ue=ge!==-1?ge:Tt,Ge=ye??Zt;X(Se),Y(Ue),T.current.prev=[Se,Ue,Ge]}if(document.addEventListener("selectionchange",at,{capture:!0}),at(),document.activeElement===be&&ne(!0),!document.getElementById("input-otp-style")){let Pe=document.createElement("style");if(Pe.id="input-otp-style",document.head.appendChild(Pe),Pe.sheet){let Tt="background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;";Gi(Pe.sheet,"[data-input-otp]::selection { background: transparent !important; color: transparent !important; }"),Gi(Pe.sheet,`[data-input-otp]:autofill { ${Tt} }`),Gi(Pe.sheet,`[data-input-otp]:-webkit-autofill { ${Tt} }`),Gi(Pe.sheet,"@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }"),Gi(Pe.sheet,"[data-input-otp] + * { pointer-events: all !important; }")}}let ht=()=>{je&&je.style.setProperty("--root-height",`${be.clientHeight}px`)};ht();let Qe=new ResizeObserver(ht);return Qe.observe(be),()=>{document.removeEventListener("selectionchange",at,{capture:!0}),Qe.disconnect()}},[]);let[K,te]=b.useState(!1),[le,ne]=b.useState(!1),[j,X]=b.useState(null),[L,Y]=b.useState(null);b.useEffect(()=>{fz(()=>{var be,je,at,ht;(be=G.current)==null||be.dispatchEvent(new Event("input"));let Qe=(je=G.current)==null?void 0:je.selectionStart,Pe=(at=G.current)==null?void 0:at.selectionEnd,Tt=(ht=G.current)==null?void 0:ht.selectionDirection;Qe!==null&&Pe!==null&&(X(Qe),Y(Pe),T.current.prev=[Qe,Pe,Tt])})},[de,le]),b.useEffect(()=>{fe!==void 0&&de!==fe&&fe.length<c&&de.length===c&&(y==null||y(de))},[c,y,fe,de]);let J=vz({containerRef:he,inputRef:G,pushPasswordManagerStrategy:v,isFocused:le}),ie=b.useCallback(be=>{let je=be.currentTarget.value.slice(0,c);if(je.length>0&&se&&!se.test(je)){be.preventDefault();return}typeof fe=="string"&&je.length<fe.length&&document.dispatchEvent(new Event("selectionchange")),me(je)},[c,me,fe,se]),pe=b.useCallback(()=>{var be;if(G.current){let je=Math.min(G.current.value.length,c-1),at=G.current.value.length;(be=G.current)==null||be.setSelectionRange(je,at),X(je),Y(at)}ne(!0)},[c]),Q=b.useCallback(be=>{var je,at;let ht=G.current;if(!w&&(!ve.current.isIOS||!be.clipboardData||!ht))return;let Qe=be.clipboardData.getData("text/plain"),Pe=w?w(Qe):Qe;be.preventDefault();let Tt=(je=G.current)==null?void 0:je.selectionStart,Zt=(at=G.current)==null?void 0:at.selectionEnd,O=(Tt!==Zt?de.slice(0,Tt)+Pe+de.slice(Zt):de.slice(0,Tt)+Pe+de.slice(Tt)).slice(0,c);if(O.length>0&&se&&!se.test(O))return;ht.value=O,me(O);let B=Math.min(O.length,c-1),V=O.length;ht.setSelectionRange(B,V),X(B),Y(V)},[c,me,se,de]),oe=b.useMemo(()=>({position:"relative",cursor:R.disabled?"default":"text",userSelect:"none",WebkitUserSelect:"none",pointerEvents:"none"}),[R.disabled]),Re=b.useMemo(()=>({position:"absolute",inset:0,width:J.willPushPWMBadge?`calc(100% + ${J.PWM_BADGE_SPACE_WIDTH})`:"100%",clipPath:J.willPushPWMBadge?`inset(0 ${J.PWM_BADGE_SPACE_WIDTH} 0 0)`:void 0,height:"100%",display:"flex",textAlign:u,opacity:"1",color:"transparent",pointerEvents:"all",background:"transparent",caretColor:"transparent",border:"0 solid transparent",outline:"0 solid transparent",boxShadow:"none",lineHeight:"1",letterSpacing:"-.5em",fontSize:"var(--root-height)",fontFamily:"monospace",fontVariantNumeric:"tabular-nums"}),[J.PWM_BADGE_SPACE_WIDTH,J.willPushPWMBadge,u]),et=b.useMemo(()=>b.createElement("input",uz(cz({autoComplete:R.autoComplete||"one-time-code"},R),{"data-input-otp":!0,"data-input-otp-placeholder-shown":de.length===0||void 0,"data-input-otp-mss":j,"data-input-otp-mse":L,inputMode:p,pattern:se==null?void 0:se.source,"aria-placeholder":g,style:Re,maxLength:c,value:de,ref:G,onPaste:be=>{var je;Q(be),(je=R.onPaste)==null||je.call(R,be)},onChange:ie,onMouseOver:be=>{var je;te(!0),(je=R.onMouseOver)==null||je.call(R,be)},onMouseLeave:be=>{var je;te(!1),(je=R.onMouseLeave)==null||je.call(R,be)},onFocus:be=>{var je;pe(),(je=R.onFocus)==null||je.call(R,be)},onBlur:be=>{var je;ne(!1),(je=R.onBlur)==null||je.call(R,be)}})),[ie,pe,Q,p,Re,c,L,j,R,se==null?void 0:se.source,de]),Me=b.useMemo(()=>({slots:Array.from({length:c}).map((be,je)=>{var at;let ht=le&&j!==null&&L!==null&&(j===L&&je===j||je>=j&&je<L),Qe=de[je]!==void 0?de[je]:null,Pe=de[0]!==void 0?null:(at=g==null?void 0:g[je])!=null?at:null;return{char:Qe,placeholderChar:Pe,isActive:ht,hasFakeCaret:ht&&Qe===null}}),isFocused:le,isHovering:!R.disabled&&K}),[le,K,c,L,j,R.disabled,de]),ze=b.useMemo(()=>_?_(Me):b.createElement(yz.Provider,{value:Me},E),[E,Me,_]);return b.createElement(b.Fragment,null,S!==null&&b.createElement("noscript",null,b.createElement("style",null,S)),b.createElement("div",{ref:he,"data-input-otp-container":!0,style:oe,className:C},ze,b.createElement("div",{style:{position:"absolute",inset:0,pointerEvents:"none"}},et)))});bz.displayName="Input";function Gi(t,n){try{t.insertRule(n)}catch{console.error("input-otp could not insert CSS rule:",n)}}var xz=`+[data-input-otp] {+ --nojs-bg: white !important;+ --nojs-fg: black !important;++ background-color: var(--nojs-bg) !important;+ color: var(--nojs-fg) !important;+ caret-color: var(--nojs-fg) !important;+ letter-spacing: .25em !important;+ text-align: center !important;+ border: 1px solid var(--nojs-fg) !important;+ border-radius: 4px !important;+ width: 100% !important;+}+@media (prefers-color-scheme: dark) {+ [data-input-otp] {+ --nojs-bg: black !important;+ --nojs-fg: white !important;+ }+}`,TS="Popover",[OS]=Ts(TS,[Gu]),Wu=Gu(),[cL,Qr]=OS(TS),jS="PopoverAnchor",wz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(jS,r),c=Wu(r),{onCustomAnchorAdd:u,onCustomAnchorRemove:f}=i;return b.useEffect(()=>(u(),()=>f()),[u,f]),h.jsx(Jh,{...c,...s,ref:n})});wz.displayName=jS;var kS="PopoverTrigger",Sz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(kS,r),c=Wu(r),u=Wt(n,i.triggerRef),f=h.jsx(kt.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":US(i.open),...s,ref:u,onClick:qe(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?f:h.jsx(Jh,{asChild:!0,...c,children:f})});Sz.displayName=kS;var mp="PopoverPortal",[Ez,_z]=OS(mp,{forceMount:void 0}),MS=t=>{const{__scopePopover:n,forceMount:r,children:s,container:i}=t,c=Qr(mp,n);return h.jsx(Ez,{scope:n,forceMount:r,children:h.jsx(za,{present:r||c.open,children:h.jsx(Bu,{asChild:!0,container:i,children:s})})})};MS.displayName=mp;var Uo="PopoverContent",DS=b.forwardRef((t,n)=>{const r=_z(Uo,t.__scopePopover),{forceMount:s=r.forceMount,...i}=t,c=Qr(Uo,t.__scopePopover);return h.jsx(za,{present:s||c.open,children:c.modal?h.jsx(Nz,{...i,ref:n}):h.jsx(Rz,{...i,ref:n})})});DS.displayName=Uo;var Cz=Do("PopoverContent.RemoveScroll"),Nz=b.forwardRef((t,n)=>{const r=Qr(Uo,t.__scopePopover),s=b.useRef(null),i=Wt(n,s),c=b.useRef(!1);return b.useEffect(()=>{const u=s.current;if(u)return Vh(u)},[]),h.jsx(Hu,{as:Cz,allowPinchZoom:!0,children:h.jsx(zS,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:qe(t.onCloseAutoFocus,u=>{var f;u.preventDefault(),c.current||(f=r.triggerRef.current)==null||f.focus()}),onPointerDownOutside:qe(t.onPointerDownOutside,u=>{const f=u.detail.originalEvent,g=f.button===0&&f.ctrlKey===!0,p=f.button===2||g;c.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:qe(t.onFocusOutside,u=>u.preventDefault(),{checkForDefaultPrevented:!1})})})}),Rz=b.forwardRef((t,n)=>{const r=Qr(Uo,t.__scopePopover),s=b.useRef(!1),i=b.useRef(!1);return h.jsx(zS,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var u,f;(u=t.onCloseAutoFocus)==null||u.call(t,c),c.defaultPrevented||(s.current||(f=r.triggerRef.current)==null||f.focus(),c.preventDefault()),s.current=!1,i.current=!1},onInteractOutside:c=>{var g,p;(g=t.onInteractOutside)==null||g.call(t,c),c.defaultPrevented||(s.current=!0,c.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const u=c.target;((p=r.triggerRef.current)==null?void 0:p.contains(u))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&i.current&&c.preventDefault()}})}),zS=b.forwardRef((t,n)=>{const{__scopePopover:r,trapFocus:s,onOpenAutoFocus:i,onCloseAutoFocus:c,disableOutsidePointerEvents:u,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onInteractOutside:y,...v}=t,w=Qr(Uo,r),C=Wu(r);return Hh(),h.jsx(Uu,{asChild:!0,loop:!0,trapped:s,onMountAutoFocus:i,onUnmountAutoFocus:c,children:h.jsx(Lu,{asChild:!0,disableOutsidePointerEvents:u,onInteractOutside:y,onEscapeKeyDown:f,onPointerDownOutside:g,onFocusOutside:p,onDismiss:()=>w.onOpenChange(!1),children:h.jsx(Ow,{"data-state":US(w.open),role:"dialog",id:w.contentId,...C,...v,ref:n,style:{...v.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),LS="PopoverClose",Az=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Qr(LS,r);return h.jsx(kt.button,{type:"button",...s,ref:n,onClick:qe(t.onClick,()=>i.onOpenChange(!1))})});Az.displayName=LS;var Tz="PopoverArrow",Oz=b.forwardRef((t,n)=>{const{__scopePopover:r,...s}=t,i=Wu(r);return h.jsx(jw,{...i,...s,ref:n})});Oz.displayName=Tz;function US(t){return t?"open":"closed"}var jz=MS,BS=DS;const hp=b.createContext(null);hp.displayName="PanelGroupContext";const qn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandleId:"data-panel-resize-handle-id"},pp=10,ko=b.useLayoutEffect,Yx=Nu.useId,kz=typeof Yx=="function"?Yx:()=>null;let Mz=0;function PS(t=null){const n=kz(),r=b.useRef(t||n||null);return r.current===null&&(r.current=""+Mz++),t??r.current}function HS({children:t,className:n="",collapsedSize:r,collapsible:s,defaultSize:i,forwardedRef:c,id:u,maxSize:f,minSize:g,onCollapse:p,onExpand:y,onResize:v,order:w,style:C,tagName:S="div",..._}){const E=b.useContext(hp);if(E===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:R,expandPanel:k,getPanelSize:A,getPanelStyle:D,groupId:H,isPanelCollapsed:$,reevaluatePanelConstraints:U,registerPanel:F,resizePanel:de,unregisterPanel:fe}=E,me=PS(u),se=b.useRef({callbacks:{onCollapse:p,onExpand:y,onResize:v},constraints:{collapsedSize:r,collapsible:s,defaultSize:i,maxSize:f,minSize:g},id:me,idIsFromProps:u!==void 0,order:w});b.useRef({didLogMissingDefaultSizeWarning:!1}),ko(()=>{const{callbacks:he,constraints:ve}=se.current,T={...ve};se.current.id=me,se.current.idIsFromProps=u!==void 0,se.current.order=w,he.onCollapse=p,he.onExpand=y,he.onResize=v,ve.collapsedSize=r,ve.collapsible=s,ve.defaultSize=i,ve.maxSize=f,ve.minSize=g,(T.collapsedSize!==ve.collapsedSize||T.collapsible!==ve.collapsible||T.maxSize!==ve.maxSize||T.minSize!==ve.minSize)&&U(se.current,T)}),ko(()=>{const he=se.current;return F(he),()=>{fe(he)}},[w,me,F,fe]),b.useImperativeHandle(c,()=>({collapse:()=>{R(se.current)},expand:he=>{k(se.current,he)},getId(){return me},getSize(){return A(se.current)},isCollapsed(){return $(se.current)},isExpanded(){return!$(se.current)},resize:he=>{de(se.current,he)}}),[R,k,A,$,me,de]);const G=D(se.current,i);return b.createElement(S,{..._,children:t,className:n,id:me,style:{...G,...C},[qn.groupId]:H,[qn.panel]:"",[qn.panelCollapsible]:s||void 0,[qn.panelId]:me,[qn.panelSize]:parseFloat(""+G.flexGrow).toFixed(1)})}const Dz=b.forwardRef((t,n)=>b.createElement(HS,{...t,forwardedRef:n}));HS.displayName="Panel";Dz.displayName="forwardRef(Panel)";function VS(t){return t.type==="keydown"}function IS(t){return t.type.startsWith("pointer")}function qS(t){return t.type.startsWith("mouse")}function zz(t){if(IS(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(qS(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function Lz(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}const Uz=1,Bz=2,Pz=4,Hz=8;Lz();let Vz=new Map;function Hm(t,n){Vz.set(t,n)}function Iz(){const[t,n]=b.useState(0);return b.useCallback(()=>n(r=>r+1),[])}function ot(t,n){if(!t)throw console.error(n),Error(n)}function Ns(t,n,r=pp){return t.toFixed(r)===n.toFixed(r)?0:t>n?1:-1}function ar(t,n,r=pp){return Ns(t,n,r)===0}function Vn(t,n,r){return Ns(t,n,r)===0}function qz(t,n,r){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++){const i=t[s],c=n[s];if(!Vn(i,c,r))return!1}return!0}function Ao({panelConstraints:t,panelIndex:n,size:r}){const s=t[n];ot(s!=null,`Panel constraints not found for index ${n}`);let{collapsedSize:i=0,collapsible:c,maxSize:u=100,minSize:f=0}=s;if(Ns(r,f)<0)if(c){const g=(i+f)/2;Ns(r,g)<0?r=i:r=f}else r=f;return r=Math.min(u,r),r=parseFloat(r.toFixed(pp)),r}function Zi({delta:t,initialLayout:n,panelConstraints:r,pivotIndices:s,prevLayout:i,trigger:c}){if(Vn(t,0))return n;const u=[...n],[f,g]=s;ot(f!=null,"Invalid first pivot index"),ot(g!=null,"Invalid second pivot index");let p=0;if(c==="keyboard"){{const v=t<0?g:f,w=r[v];ot(w,`Panel constraints not found for index ${v}`);const{collapsedSize:C=0,collapsible:S,minSize:_=0}=w;if(S){const E=n[v];if(ot(E!=null,`Previous layout not found for panel index ${v}`),Vn(E,C)){const R=_-E;Ns(R,Math.abs(t))>0&&(t=t<0?0-R:R)}}}{const v=t<0?f:g,w=r[v];ot(w,`No panel constraints found for index ${v}`);const{collapsedSize:C=0,collapsible:S,minSize:_=0}=w;if(S){const E=n[v];if(ot(E!=null,`Previous layout not found for panel index ${v}`),Vn(E,_)){const R=E-C;Ns(R,Math.abs(t))>0&&(t=t<0?0-R:R)}}}}{const v=t<0?1:-1;let w=t<0?g:f,C=0;for(;;){const _=n[w];ot(_!=null,`Previous layout not found for panel index ${w}`);const R=Ao({panelConstraints:r,panelIndex:w,size:100})-_;if(C+=R,w+=v,w<0||w>=r.length)break}const S=Math.min(Math.abs(t),Math.abs(C));t=t<0?0-S:S}{let w=t<0?f:g;for(;w>=0&&w<r.length;){const C=Math.abs(t)-Math.abs(p),S=n[w];ot(S!=null,`Previous layout not found for panel index ${w}`);const _=S-C,E=Ao({panelConstraints:r,panelIndex:w,size:_});if(!Vn(S,E)&&(p+=S-E,u[w]=E,p.toFixed(3).localeCompare(Math.abs(t).toFixed(3),void 0,{numeric:!0})>=0))break;t<0?w--:w++}}if(qz(i,u))return i;{const v=t<0?g:f,w=n[v];ot(w!=null,`Previous layout not found for panel index ${v}`);const C=w+p,S=Ao({panelConstraints:r,panelIndex:v,size:C});if(u[v]=S,!Vn(S,C)){let _=C-S,R=t<0?g:f;for(;R>=0&&R<r.length;){const k=u[R];ot(k!=null,`Previous layout not found for panel index ${R}`);const A=k+_,D=Ao({panelConstraints:r,panelIndex:R,size:A});if(Vn(k,D)||(_-=D-k,u[R]=D),Vn(_,0))break;t>0?R--:R++}}}const y=u.reduce((v,w)=>w+v,0);return Vn(y,100)?u:i}function Fz({layout:t,panelsArray:n,pivotIndices:r}){let s=0,i=100,c=0,u=0;const f=r[0];ot(f!=null,"No pivot index found"),n.forEach((v,w)=>{const{constraints:C}=v,{maxSize:S=100,minSize:_=0}=C;w===f?(s=_,i=S):(c+=_,u+=S)});const g=Math.min(i,100-c),p=Math.max(s,100-u),y=t[f];return{valueMax:g,valueMin:p,valueNow:y}}function hu(t,n=document){return Array.from(n.querySelectorAll(`[${qn.resizeHandleId}][data-panel-group-id="${t}"]`))}function $z(t,n,r=document){const i=hu(t,r).findIndex(c=>c.getAttribute(qn.resizeHandleId)===n);return i??null}function FS(t,n,r){const s=$z(t,n,r);return s!=null?[s,s+1]:[-1,-1]}function Gz(t){return t instanceof HTMLElement?!0:typeof t=="object"&&t!==null&&"tagName"in t&&"getAttribute"in t}function $S(t,n=document){if(Gz(n)&&n.dataset.panelGroupId==t)return n;const r=n.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return r||null}function gp(t,n=document){const r=n.querySelector(`[${qn.resizeHandleId}="${t}"]`);return r||null}function Yz(t,n,r,s=document){var i,c,u,f;const g=gp(n,s),p=hu(t,s),y=g?p.indexOf(g):-1,v=(i=(c=r[y])===null||c===void 0?void 0:c.id)!==null&&i!==void 0?i:null,w=(u=(f=r[y+1])===null||f===void 0?void 0:f.id)!==null&&u!==void 0?u:null;return[v,w]}function Zz({committedValuesRef:t,eagerValuesRef:n,groupId:r,layout:s,panelDataArray:i,panelGroupElement:c,setLayout:u}){b.useRef({didWarnAboutMissingResizeHandle:!1}),ko(()=>{if(!c)return;const f=hu(r,c);for(let g=0;g<i.length-1;g++){const{valueMax:p,valueMin:y,valueNow:v}=Fz({layout:s,panelsArray:i,pivotIndices:[g,g+1]}),w=f[g];if(w!=null){const C=i[g];ot(C,`No panel data found for index "${g}"`),w.setAttribute("aria-controls",C.id),w.setAttribute("aria-valuemax",""+Math.round(p)),w.setAttribute("aria-valuemin",""+Math.round(y)),w.setAttribute("aria-valuenow",v!=null?""+Math.round(v):"")}}return()=>{f.forEach((g,p)=>{g.removeAttribute("aria-controls"),g.removeAttribute("aria-valuemax"),g.removeAttribute("aria-valuemin"),g.removeAttribute("aria-valuenow")})}},[r,s,i,c]),b.useEffect(()=>{if(!c)return;const f=n.current;ot(f,"Eager values not found");const{panelDataArray:g}=f,p=$S(r,c);ot(p!=null,`No group found for id "${r}"`);const y=hu(r,c);ot(y,`No resize handles found for group id "${r}"`);const v=y.map(w=>{const C=w.getAttribute(qn.resizeHandleId);ot(C,"Resize handle element has no handle id attribute");const[S,_]=Yz(r,C,g,c);if(S==null||_==null)return()=>{};const E=R=>{if(!R.defaultPrevented)switch(R.key){case"Enter":{R.preventDefault();const k=g.findIndex(A=>A.id===S);if(k>=0){const A=g[k];ot(A,`No panel data found for index ${k}`);const D=s[k],{collapsedSize:H=0,collapsible:$,minSize:U=0}=A.constraints;if(D!=null&&$){const F=Zi({delta:Vn(D,H)?U-H:H-D,initialLayout:s,panelConstraints:g.map(de=>de.constraints),pivotIndices:FS(r,C,c),prevLayout:s,trigger:"keyboard"});s!==F&&u(F)}}break}}};return w.addEventListener("keydown",E),()=>{w.removeEventListener("keydown",E)}});return()=>{v.forEach(w=>w())}},[c,t,n,r,s,i,u])}function Zx(t,n){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==n[r])return!1;return!0}function GS(t,n){const r=t==="horizontal",{x:s,y:i}=zz(n);return r?s:i}function Xz(t,n,r,s,i){const c=r==="horizontal",u=gp(n,i);ot(u,`No resize handle element found for id "${n}"`);const f=u.getAttribute(qn.groupId);ot(f,"Resize handle element has no group id attribute");let{initialCursorPosition:g}=s;const p=GS(r,t),y=$S(f,i);ot(y,`No group element found for id "${f}"`);const v=y.getBoundingClientRect(),w=c?v.width:v.height;return(p-g)/w*100}function Kz(t,n,r,s,i,c){if(VS(t)){const u=r==="horizontal";let f=0;t.shiftKey?f=100:i!=null?f=i:f=10;let g=0;switch(t.key){case"ArrowDown":g=u?0:f;break;case"ArrowLeft":g=u?-f:0;break;case"ArrowRight":g=u?f:0;break;case"ArrowUp":g=u?0:-f;break;case"End":g=100;break;case"Home":g=-100;break}return g}else return s==null?0:Xz(t,n,r,s,c)}function Qz({panelDataArray:t}){const n=Array(t.length),r=t.map(c=>c.constraints);let s=0,i=100;for(let c=0;c<t.length;c++){const u=r[c];ot(u,`Panel constraints not found for index ${c}`);const{defaultSize:f}=u;f!=null&&(s++,n[c]=f,i-=f)}for(let c=0;c<t.length;c++){const u=r[c];ot(u,`Panel constraints not found for index ${c}`);const{defaultSize:f}=u;if(f!=null)continue;const g=t.length-s,p=i/g;s++,n[c]=p,i-=p}return n}function _o(t,n,r){n.forEach((s,i)=>{const c=t[i];ot(c,`Panel data not found for index ${i}`);const{callbacks:u,constraints:f,id:g}=c,{collapsedSize:p=0,collapsible:y}=f,v=r[g];if(v==null||s!==v){r[g]=s;const{onCollapse:w,onExpand:C,onResize:S}=u;S&&S(s,v),y&&(w||C)&&(C&&(v==null||ar(v,p))&&!ar(s,p)&&C(),w&&(v==null||!ar(v,p))&&ar(s,p)&&w())}})}function qc(t,n){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!=n[r])return!1;return!0}function Wz({defaultSize:t,dragState:n,layout:r,panelData:s,panelIndex:i,precision:c=3}){const u=r[i];let f;return u==null?f=t!=null?t.toFixed(c):"1":s.length===1?f="1":f=u.toFixed(c),{flexBasis:0,flexGrow:f,flexShrink:1,overflow:"hidden",pointerEvents:n!==null?"none":void 0}}function Jz(t,n=10){let r=null;return(...i)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{t(...i)},n)}}function Xx(t){try{if(typeof localStorage<"u")t.getItem=n=>localStorage.getItem(n),t.setItem=(n,r)=>{localStorage.setItem(n,r)};else throw new Error("localStorage not supported in this environment")}catch(n){console.error(n),t.getItem=()=>null,t.setItem=()=>{}}}function YS(t){return`react-resizable-panels:${t}`}function ZS(t){return t.map(n=>{const{constraints:r,id:s,idIsFromProps:i,order:c}=n;return i?s:c?`${c}:${JSON.stringify(r)}`:JSON.stringify(r)}).sort((n,r)=>n.localeCompare(r)).join(",")}function XS(t,n){try{const r=YS(t),s=n.getItem(r);if(s){const i=JSON.parse(s);if(typeof i=="object"&&i!=null)return i}}catch{}return null}function e3(t,n,r){var s,i;const c=(s=XS(t,r))!==null&&s!==void 0?s:{},u=ZS(n);return(i=c[u])!==null&&i!==void 0?i:null}function t3(t,n,r,s,i){var c;const u=YS(t),f=ZS(n),g=(c=XS(t,i))!==null&&c!==void 0?c:{};g[f]={expandToSizes:Object.fromEntries(r.entries()),layout:s};try{i.setItem(u,JSON.stringify(g))}catch(p){console.error(p)}}function Kx({layout:t,panelConstraints:n}){const r=[...t],s=r.reduce((c,u)=>c+u,0);if(r.length!==n.length)throw Error(`Invalid ${n.length} panel layout: ${r.map(c=>`${c}%`).join(", ")}`);if(!Vn(s,100)&&r.length>0)for(let c=0;c<n.length;c++){const u=r[c];ot(u!=null,`No layout data found for index ${c}`);const f=100/s*u;r[c]=f}let i=0;for(let c=0;c<n.length;c++){const u=r[c];ot(u!=null,`No layout data found for index ${c}`);const f=Ao({panelConstraints:n,panelIndex:c,size:u});u!=f&&(i+=u-f,r[c]=f)}if(!Vn(i,0))for(let c=0;c<n.length;c++){const u=r[c];ot(u!=null,`No layout data found for index ${c}`);const f=u+i,g=Ao({panelConstraints:n,panelIndex:c,size:f});if(u!==g&&(i-=g-u,r[c]=g,Vn(i,0)))break}return r}const n3=100,Xi={getItem:t=>(Xx(Xi),Xi.getItem(t)),setItem:(t,n)=>{Xx(Xi),Xi.setItem(t,n)}},Qx={};function KS({autoSaveId:t=null,children:n,className:r="",direction:s,forwardedRef:i,id:c=null,onLayout:u=null,keyboardResizeBy:f=null,storage:g=Xi,style:p,tagName:y="div",...v}){const w=PS(c),C=b.useRef(null),[S,_]=b.useState(null),[E,R]=b.useState([]),k=Iz(),A=b.useRef({}),D=b.useRef(new Map),H=b.useRef(0),$=b.useRef({autoSaveId:t,direction:s,dragState:S,id:w,keyboardResizeBy:f,onLayout:u,storage:g}),U=b.useRef({layout:E,panelDataArray:[],panelDataArrayChanged:!1});b.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),b.useImperativeHandle(i,()=>({getId:()=>$.current.id,getLayout:()=>{const{layout:L}=U.current;return L},setLayout:L=>{const{onLayout:Y}=$.current,{layout:J,panelDataArray:ie}=U.current,pe=Kx({layout:L,panelConstraints:ie.map(Q=>Q.constraints)});Zx(J,pe)||(R(pe),U.current.layout=pe,Y&&Y(pe),_o(ie,pe,A.current))}}),[]),ko(()=>{$.current.autoSaveId=t,$.current.direction=s,$.current.dragState=S,$.current.id=w,$.current.onLayout=u,$.current.storage=g}),Zz({committedValuesRef:$,eagerValuesRef:U,groupId:w,layout:E,panelDataArray:U.current.panelDataArray,setLayout:R,panelGroupElement:C.current}),b.useEffect(()=>{const{panelDataArray:L}=U.current;if(t){if(E.length===0||E.length!==L.length)return;let Y=Qx[t];Y==null&&(Y=Jz(t3,n3),Qx[t]=Y);const J=[...L],ie=new Map(D.current);Y(t,J,ie,E,g)}},[t,E,g]),b.useEffect(()=>{});const F=b.useCallback(L=>{const{onLayout:Y}=$.current,{layout:J,panelDataArray:ie}=U.current;if(L.constraints.collapsible){const pe=ie.map(et=>et.constraints),{collapsedSize:Q=0,panelSize:oe,pivotIndices:Re}=bs(ie,L,J);if(ot(oe!=null,`Panel size not found for panel "${L.id}"`),!ar(oe,Q)){D.current.set(L.id,oe);const Me=No(ie,L)===ie.length-1?oe-Q:Q-oe,ze=Zi({delta:Me,initialLayout:J,panelConstraints:pe,pivotIndices:Re,prevLayout:J,trigger:"imperative-api"});qc(J,ze)||(R(ze),U.current.layout=ze,Y&&Y(ze),_o(ie,ze,A.current))}}},[]),de=b.useCallback((L,Y)=>{const{onLayout:J}=$.current,{layout:ie,panelDataArray:pe}=U.current;if(L.constraints.collapsible){const Q=pe.map(be=>be.constraints),{collapsedSize:oe=0,panelSize:Re=0,minSize:et=0,pivotIndices:Me}=bs(pe,L,ie),ze=Y??et;if(ar(Re,oe)){const be=D.current.get(L.id),je=be!=null&&be>=ze?be:ze,ht=No(pe,L)===pe.length-1?Re-je:je-Re,Qe=Zi({delta:ht,initialLayout:ie,panelConstraints:Q,pivotIndices:Me,prevLayout:ie,trigger:"imperative-api"});qc(ie,Qe)||(R(Qe),U.current.layout=Qe,J&&J(Qe),_o(pe,Qe,A.current))}}},[]),fe=b.useCallback(L=>{const{layout:Y,panelDataArray:J}=U.current,{panelSize:ie}=bs(J,L,Y);return ot(ie!=null,`Panel size not found for panel "${L.id}"`),ie},[]),me=b.useCallback((L,Y)=>{const{panelDataArray:J}=U.current,ie=No(J,L);return Wz({defaultSize:Y,dragState:S,layout:E,panelData:J,panelIndex:ie})},[S,E]),se=b.useCallback(L=>{const{layout:Y,panelDataArray:J}=U.current,{collapsedSize:ie=0,collapsible:pe,panelSize:Q}=bs(J,L,Y);return ot(Q!=null,`Panel size not found for panel "${L.id}"`),pe===!0&&ar(Q,ie)},[]),G=b.useCallback(L=>{const{layout:Y,panelDataArray:J}=U.current,{collapsedSize:ie=0,collapsible:pe,panelSize:Q}=bs(J,L,Y);return ot(Q!=null,`Panel size not found for panel "${L.id}"`),!pe||Ns(Q,ie)>0},[]),he=b.useCallback(L=>{const{panelDataArray:Y}=U.current;Y.push(L),Y.sort((J,ie)=>{const pe=J.order,Q=ie.order;return pe==null&&Q==null?0:pe==null?-1:Q==null?1:pe-Q}),U.current.panelDataArrayChanged=!0,k()},[k]);ko(()=>{if(U.current.panelDataArrayChanged){U.current.panelDataArrayChanged=!1;const{autoSaveId:L,onLayout:Y,storage:J}=$.current,{layout:ie,panelDataArray:pe}=U.current;let Q=null;if(L){const Re=e3(L,pe,J);Re&&(D.current=new Map(Object.entries(Re.expandToSizes)),Q=Re.layout)}Q==null&&(Q=Qz({panelDataArray:pe}));const oe=Kx({layout:Q,panelConstraints:pe.map(Re=>Re.constraints)});Zx(ie,oe)||(R(oe),U.current.layout=oe,Y&&Y(oe),_o(pe,oe,A.current))}}),ko(()=>{const L=U.current;return()=>{L.layout=[]}},[]);const ve=b.useCallback(L=>{let Y=!1;const J=C.current;return J&&window.getComputedStyle(J,null).getPropertyValue("direction")==="rtl"&&(Y=!0),function(pe){pe.preventDefault();const Q=C.current;if(!Q)return()=>null;const{direction:oe,dragState:Re,id:et,keyboardResizeBy:Me,onLayout:ze}=$.current,{layout:be,panelDataArray:je}=U.current,{initialLayout:at}=Re??{},ht=FS(et,L,Q);let Qe=Kz(pe,L,oe,Re,Me,Q);const Pe=oe==="horizontal";Pe&&Y&&(Qe=-Qe);const Tt=je.map(B=>B.constraints),Zt=Zi({delta:Qe,initialLayout:at??be,panelConstraints:Tt,pivotIndices:ht,prevLayout:be,trigger:VS(pe)?"keyboard":"mouse-or-touch"}),O=!qc(be,Zt);(IS(pe)||qS(pe))&&H.current!=Qe&&(H.current=Qe,!O&&Qe!==0?Pe?Hm(L,Qe<0?Uz:Bz):Hm(L,Qe<0?Pz:Hz):Hm(L,0)),O&&(R(Zt),U.current.layout=Zt,ze&&ze(Zt),_o(je,Zt,A.current))}},[]),T=b.useCallback((L,Y)=>{const{onLayout:J}=$.current,{layout:ie,panelDataArray:pe}=U.current,Q=pe.map(be=>be.constraints),{panelSize:oe,pivotIndices:Re}=bs(pe,L,ie);ot(oe!=null,`Panel size not found for panel "${L.id}"`);const Me=No(pe,L)===pe.length-1?oe-Y:Y-oe,ze=Zi({delta:Me,initialLayout:ie,panelConstraints:Q,pivotIndices:Re,prevLayout:ie,trigger:"imperative-api"});qc(ie,ze)||(R(ze),U.current.layout=ze,J&&J(ze),_o(pe,ze,A.current))},[]),K=b.useCallback((L,Y)=>{const{layout:J,panelDataArray:ie}=U.current,{collapsedSize:pe=0,collapsible:Q}=Y,{collapsedSize:oe=0,collapsible:Re,maxSize:et=100,minSize:Me=0}=L.constraints,{panelSize:ze}=bs(ie,L,J);ze!=null&&(Q&&Re&&ar(ze,pe)?ar(pe,oe)||T(L,oe):ze<Me?T(L,Me):ze>et&&T(L,et))},[T]),te=b.useCallback((L,Y)=>{const{direction:J}=$.current,{layout:ie}=U.current;if(!C.current)return;const pe=gp(L,C.current);ot(pe,`Drag handle element not found for id "${L}"`);const Q=GS(J,Y);_({dragHandleId:L,dragHandleRect:pe.getBoundingClientRect(),initialCursorPosition:Q,initialLayout:ie})},[]),le=b.useCallback(()=>{_(null)},[]),ne=b.useCallback(L=>{const{panelDataArray:Y}=U.current,J=No(Y,L);J>=0&&(Y.splice(J,1),delete A.current[L.id],U.current.panelDataArrayChanged=!0,k())},[k]),j=b.useMemo(()=>({collapsePanel:F,direction:s,dragState:S,expandPanel:de,getPanelSize:fe,getPanelStyle:me,groupId:w,isPanelCollapsed:se,isPanelExpanded:G,reevaluatePanelConstraints:K,registerPanel:he,registerResizeHandle:ve,resizePanel:T,startDragging:te,stopDragging:le,unregisterPanel:ne,panelGroupElement:C.current}),[F,S,s,de,fe,me,w,se,G,K,he,ve,T,te,le,ne]),X={display:"flex",flexDirection:s==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return b.createElement(hp.Provider,{value:j},b.createElement(y,{...v,children:n,className:r,id:c,ref:C,style:{...X,...p},[qn.group]:"",[qn.groupDirection]:s,[qn.groupId]:w}))}const a3=b.forwardRef((t,n)=>b.createElement(KS,{...t,forwardedRef:n}));KS.displayName="PanelGroup";a3.displayName="forwardRef(PanelGroup)";function No(t,n){return t.findIndex(r=>r===n||r.id===n.id)}function bs(t,n,r){const s=No(t,n),c=s===t.length-1?[s-1,s]:[s,s+1],u=r[s];return{...n.constraints,panelSize:u,pivotIndices:c}}var r3=(t,n,r,s,i,c,u,f)=>{let g=document.documentElement,p=["light","dark"];function y(C){(Array.isArray(t)?t:[t]).forEach(S=>{let _=S==="class",E=_&&c?i.map(R=>c[R]||R):i;_?(g.classList.remove(...E),g.classList.add(c&&c[C]?c[C]:C)):g.setAttribute(S,C)}),v(C)}function v(C){f&&p.includes(C)&&(g.style.colorScheme=C)}function w(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(s)y(s);else try{let C=localStorage.getItem(n)||r,S=u&&C==="system"?w():C;y(S)}catch{}};b.createContext(void 0);b.memo(({forcedTheme:t,storageKey:n,attribute:r,enableSystem:s,enableColorScheme:i,defaultTheme:c,value:u,themes:f,nonce:g,scriptProps:p})=>{let y=JSON.stringify([r,n,c,t,f,u,s,i]).slice(1,-1);return b.createElement("script",{...p,suppressHydrationWarning:!0,nonce:typeof window>"u"?g:"",dangerouslySetInnerHTML:{__html:`(${r3.toString()})(${y})`}})});function Jt(...t){return a1(Oh(t))}var s3=Ph("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function o3({className:t,variant:n,...r}){return h.jsx("div",{"data-slot":"alert",role:"alert",className:Jt(s3({variant:n}),t),...r})}function i3({className:t,...n}){return h.jsx("div",{"data-slot":"alert-title",className:Jt("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",t),...n})}function l3({className:t,...n}){return h.jsx("div",{"data-slot":"alert-description",className:Jt("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...n})}var c3=Ph("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}}),ut=b.forwardRef(({className:t,variant:n,size:r,asChild:s=!1,...i},c)=>{const u=s?lw:"button";return h.jsx(u,{className:Jt(c3({variant:n,size:r,className:t})),ref:c,...i})});ut.displayName="Button";var u3=Ph("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function pu({className:t,variant:n,asChild:r=!1,...s}){const i=r?lw:"span";return h.jsx(i,{"data-slot":"badge",className:Jt(u3({variant:n}),t),...s})}function d3({className:t,...n}){return h.jsx("div",{"data-slot":"card",className:Jt("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",t),...n})}function f3({className:t,...n}){return h.jsx("div",{"data-slot":"card-content",className:Jt("px-6",t),...n})}b.createContext(null);b.createContext(null);function gu({...t}){return h.jsx(yk,{"data-slot":"dialog",...t})}function m3({...t}){return h.jsx(bk,{"data-slot":"dialog-portal",...t})}function h3({className:t,...n}){return h.jsx(rw,{"data-slot":"dialog-overlay",className:Jt("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...n})}function vu({className:t,children:n,showCloseButton:r=!0,...s}){return h.jsxs(m3,{"data-slot":"dialog-portal",children:[h.jsx(h3,{}),h.jsxs(sw,{"data-slot":"dialog-content",className:Jt("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...s,children:[n,r&&h.jsxs(Sk,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[h.jsx(oj,{}),h.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function yu({className:t,...n}){return h.jsx("div",{"data-slot":"dialog-header",className:Jt("flex flex-col gap-2 text-center sm:text-left",t),...n})}function QS({className:t,...n}){return h.jsx("div",{"data-slot":"dialog-footer",className:Jt("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...n})}function bu({className:t,...n}){return h.jsx(xk,{"data-slot":"dialog-title",className:Jt("text-lg leading-none font-semibold",t),...n})}function xu({className:t,...n}){return h.jsx(wk,{"data-slot":"dialog-description",className:Jt("text-muted-foreground text-sm",t),...n})}function p3({...t}){return h.jsx(j4,{"data-slot":"dropdown-menu",...t})}function g3({...t}){return h.jsx(k4,{"data-slot":"dropdown-menu-trigger",...t})}function v3({className:t,sideOffset:n=4,...r}){return h.jsx(M4,{children:h.jsx(D4,{"data-slot":"dropdown-menu-content",sideOffset:n,className:Jt("bg-popover text-popover-foreground 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 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...r})})}function y3({className:t,inset:n,variant:r="default",...s}){return h.jsx(z4,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:Jt("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...s})}function Pr({className:t,...n}){return h.jsx(sz,{"data-slot":"label",className:Jt("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...n})}b.createContext({});b.createContext({});function Ra({className:t,type:n,...r}){return h.jsx("input",{type:n,"data-slot":"input",className:Jt("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),...r})}var b3=b.forwardRef(({className:t,align:n="center",sideOffset:r=4,...s},i)=>h.jsx(jz,{children:h.jsx(BS,{ref:i,align:n,sideOffset:r,className:Jt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none",t),...s})}));b3.displayName=BS.displayName;function x3({className:t,...n}){return h.jsx("div",{"data-slot":"skeleton",className:Jt("bg-accent animate-pulse rounded-md",t),...n})}b.createContext(null);b.createContext({size:"default",variant:"default"});const w3=()=>{const t=Xr();return h.jsx("div",{className:"min-h-screen bg-gradient-to-br from-primary/10 via-background to-background",children:h.jsx("div",{className:"container mx-auto px-4 py-16",children:h.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[h.jsxs("div",{className:"space-y-4",children:[h.jsx("h1",{className:"text-6xl font-bold text-primary animate-fadeIn",children:"Evolution GO"}),h.jsx("p",{className:"text-xl text-muted-foreground",children:"Interface moderna para gerenciamento de instâncias WhatsApp"})]}),h.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mt-12",children:[h.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[h.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:h.jsx(QR,{className:"w-6 h-6 text-primary"})}),h.jsx("h3",{className:"text-lg font-semibold",children:"Rápido e Eficiente"}),h.jsx("p",{className:"text-sm text-muted-foreground",children:"Gerencie múltiplas instâncias WhatsApp com alta performance"})]}),h.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[h.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:h.jsx(VR,{className:"w-6 h-6 text-primary"})}),h.jsx("h3",{className:"text-lg font-semibold",children:"Seguro"}),h.jsx("p",{className:"text-sm text-muted-foreground",children:"Autenticação robusta e controle total sobre suas instâncias"})]}),h.jsxs("div",{className:"bg-card border rounded-lg p-6 space-y-3 hover:border-primary transition-colors",children:[h.jsx("div",{className:"w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center",children:h.jsx(vR,{className:"w-6 h-6 text-primary"})}),h.jsx("h3",{className:"text-lg font-semibold",children:"API Completa"}),h.jsx("p",{className:"text-sm text-muted-foreground",children:"Integração via API REST com Evolution GO"})]})]}),h.jsx("div",{className:"mt-12",children:h.jsxs(ut,{size:"lg",onClick:()=>t("/manager/login"),className:"text-lg px-8 py-6 group",children:["Acessar Manager",h.jsx(K2,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})}),h.jsxs("div",{className:"mt-16 pt-8 border-t",children:[h.jsx("p",{className:"text-sm text-muted-foreground",children:"Evolution GO Manager - Gerencie suas instâncias WhatsApp de forma simples e eficiente"}),h.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["© ",new Date().getFullYear()," Evolution GO. Todos os direitos reservados."]})]})]})})})};var dt;(function(t){t.assertEqual=i=>{};function n(i){}t.assertIs=n;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const c={};for(const u of i)c[u]=u;return c},t.getValidEnumValues=i=>{const c=t.objectKeys(i).filter(f=>typeof i[i[f]]!="number"),u={};for(const f of c)u[f]=i[f];return t.objectValues(u)},t.objectValues=i=>t.objectKeys(i).map(function(c){return i[c]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const c=[];for(const u in i)Object.prototype.hasOwnProperty.call(i,u)&&c.push(u);return c},t.find=(i,c)=>{for(const u of i)if(c(u))return u},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function s(i,c=" | "){return i.map(u=>typeof u=="string"?`'${u}'`:u).join(c)}t.joinValues=s,t.jsonStringifyReplacer=(i,c)=>typeof c=="bigint"?c.toString():c})(dt||(dt={}));var Wx;(function(t){t.mergeShapes=(n,r)=>({...n,...r})})(Wx||(Wx={}));const Te=dt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Hr=t=>{switch(typeof t){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(t)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(t)?Te.array:t===null?Te.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Te.promise:typeof Map<"u"&&t instanceof Map?Te.map:typeof Set<"u"&&t instanceof Set?Te.set:typeof Date<"u"&&t instanceof Date?Te.date:Te.object;default:return Te.unknown}},xe=dt.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"]);class lr extends Error{get errors(){return this.issues}constructor(n){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=n}format(n){const r=n||function(c){return c.message},s={_errors:[]},i=c=>{for(const u of c.issues)if(u.code==="invalid_union")u.unionErrors.map(i);else if(u.code==="invalid_return_type")i(u.returnTypeError);else if(u.code==="invalid_arguments")i(u.argumentsError);else if(u.path.length===0)s._errors.push(r(u));else{let f=s,g=0;for(;g<u.path.length;){const p=u.path[g];g===u.path.length-1?(f[p]=f[p]||{_errors:[]},f[p]._errors.push(r(u))):f[p]=f[p]||{_errors:[]},f=f[p],g++}}};return i(this),s}static assert(n){if(!(n instanceof lr))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,dt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=r=>r.message){const r={},s=[];for(const i of this.issues)if(i.path.length>0){const c=i.path[0];r[c]=r[c]||[],r[c].push(n(i))}else s.push(n(i));return{formErrors:s,fieldErrors:r}}get formErrors(){return this.flatten()}}lr.create=t=>new lr(t);const fh=(t,n)=>{let r;switch(t.code){case xe.invalid_type:t.received===Te.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case xe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,dt.jsonStringifyReplacer)}`;break;case xe.unrecognized_keys:r=`Unrecognized key(s) in object: ${dt.joinValues(t.keys,", ")}`;break;case xe.invalid_union:r="Invalid input";break;case xe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${dt.joinValues(t.options)}`;break;case xe.invalid_enum_value:r=`Invalid enum value. Expected ${dt.joinValues(t.options)}, received '${t.received}'`;break;case xe.invalid_arguments:r="Invalid function arguments";break;case xe.invalid_return_type:r="Invalid function return type";break;case xe.invalid_date:r="Invalid date";break;case xe.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:dt.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case xe.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case xe.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case xe.custom:r="Invalid input";break;case xe.invalid_intersection_types:r="Intersection results could not be merged";break;case xe.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case xe.not_finite:r="Number must be finite";break;default:r=n.defaultError,dt.assertNever(t)}return{message:r}};let S3=fh;function E3(){return S3}const _3=t=>{const{data:n,path:r,errorMaps:s,issueData:i}=t,c=[...r,...i.path||[]],u={...i,path:c};if(i.message!==void 0)return{...i,path:c,message:i.message};let f="";const g=s.filter(p=>!!p).slice().reverse();for(const p of g)f=p(u,{data:n,defaultError:f}).message;return{...i,path:c,message:f}};function Ee(t,n){const r=E3(),s=_3({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===fh?void 0:fh].filter(i=>!!i)});t.common.issues.push(s)}class $n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(n,r){const s=[];for(const i of r){if(i.status==="aborted")return Ie;i.status==="dirty"&&n.dirty(),s.push(i.value)}return{status:n.value,value:s}}static async mergeObjectAsync(n,r){const s=[];for(const i of r){const c=await i.key,u=await i.value;s.push({key:c,value:u})}return $n.mergeObjectSync(n,s)}static mergeObjectSync(n,r){const s={};for(const i of r){const{key:c,value:u}=i;if(c.status==="aborted"||u.status==="aborted")return Ie;c.status==="dirty"&&n.dirty(),u.status==="dirty"&&n.dirty(),c.value!=="__proto__"&&(typeof u.value<"u"||i.alwaysSet)&&(s[c.value]=u.value)}return{status:n.value,value:s}}}const Ie=Object.freeze({status:"aborted"}),Ki=t=>({status:"dirty",value:t}),la=t=>({status:"valid",value:t}),Jx=t=>t.status==="aborted",e0=t=>t.status==="dirty",Bo=t=>t.status==="valid",wu=t=>typeof Promise<"u"&&t instanceof Promise;var ke;(function(t){t.errToObj=n=>typeof n=="string"?{message:n}:n||{},t.toString=n=>typeof n=="string"?n:n==null?void 0:n.message})(ke||(ke={}));class Yr{constructor(n,r,s,i){this._cachedPath=[],this.parent=n,this.data=r,this._path=s,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const t0=(t,n)=>{if(Bo(n))return{success:!0,data:n.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new lr(t.common.issues);return this._error=r,this._error}}};function Ke(t){if(!t)return{};const{errorMap:n,invalid_type_error:r,required_error:s,description:i}=t;if(n&&(r||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return n?{errorMap:n,description:i}:{errorMap:(u,f)=>{const{message:g}=t;return u.code==="invalid_enum_value"?{message:g??f.defaultError}:typeof f.data>"u"?{message:g??s??f.defaultError}:u.code!=="invalid_type"?{message:f.defaultError}:{message:g??r??f.defaultError}},description:i}}class it{get description(){return this._def.description}_getType(n){return Hr(n.data)}_getOrReturnCtx(n,r){return r||{common:n.parent.common,data:n.data,parsedType:Hr(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new $n,ctx:{common:n.parent.common,data:n.data,parsedType:Hr(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const r=this._parse(n);if(wu(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(n){const r=this._parse(n);return Promise.resolve(r)}parse(n,r){const s=this.safeParse(n,r);if(s.success)return s.data;throw s.error}safeParse(n,r){const s={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Hr(n)},i=this._parseSync({data:n,path:s.path,parent:s});return t0(s,i)}"~validate"(n){var s,i;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Hr(n)};if(!this["~standard"].async)try{const c=this._parseSync({data:n,path:[],parent:r});return Bo(c)?{value:c.value}:{issues:r.common.issues}}catch(c){(i=(s=c==null?void 0:c.message)==null?void 0:s.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:r}).then(c=>Bo(c)?{value:c.value}:{issues:r.common.issues})}async parseAsync(n,r){const s=await this.safeParseAsync(n,r);if(s.success)return s.data;throw s.error}async safeParseAsync(n,r){const s={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Hr(n)},i=this._parse({data:n,path:s.path,parent:s}),c=await(wu(i)?i:Promise.resolve(i));return t0(s,c)}refine(n,r){const s=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,c)=>{const u=n(i),f=()=>c.addIssue({code:xe.custom,...s(i)});return typeof Promise<"u"&&u instanceof Promise?u.then(g=>g?!0:(f(),!1)):u?!0:(f(),!1)})}refinement(n,r){return this._refinement((s,i)=>n(s)?!0:(i.addIssue(typeof r=="function"?r(s,i):r),!1))}_refinement(n){return new Ho({schema:this,typeName:Fe.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,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),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return qr.create(this,this._def)}nullable(){return Vo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ma.create(this)}promise(){return Cu.create(this,this._def)}or(n){return Eu.create([this,n],this._def)}and(n){return _u.create(this,n,this._def)}transform(n){return new Ho({...Ke(this._def),schema:this,typeName:Fe.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const r=typeof n=="function"?n:()=>n;return new gh({...Ke(this._def),innerType:this,defaultValue:r,typeName:Fe.ZodDefault})}brand(){return new Y3({typeName:Fe.ZodBranded,type:this,...Ke(this._def)})}catch(n){const r=typeof n=="function"?n:()=>n;return new vh({...Ke(this._def),innerType:this,catchValue:r,typeName:Fe.ZodCatch})}describe(n){const r=this.constructor;return new r({...this._def,description:n})}pipe(n){return vp.create(this,n)}readonly(){return yh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const C3=/^c[^\s-]{8,}$/i,N3=/^[0-9a-z]+$/,R3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A3=/^[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,T3=/^[a-z0-9_-]{21}$/i,O3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j3=/^[-+]?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)?)??$/,k3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,M3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Vm;const D3=/^(?:(?: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])$/,z3=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,L3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,U3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,P3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,WS="((\\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])))",H3=new RegExp(`^${WS}$`);function JS(t){let n="[0-5]\\d";t.precision?n=`${n}\\.\\d{${t.precision}}`:t.precision==null&&(n=`${n}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${r}`}function V3(t){return new RegExp(`^${JS(t)}$`)}function I3(t){let n=`${WS}T${JS(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),n=`${n}(${r.join("|")})`,new RegExp(`^${n}$`)}function q3(t,n){return!!((n==="v4"||!n)&&D3.test(t)||(n==="v6"||!n)&&L3.test(t))}function F3(t,n){if(!O3.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||n&&i.alg!==n)}catch{return!1}}function $3(t,n){return!!((n==="v4"||!n)&&z3.test(t)||(n==="v6"||!n)&&U3.test(t))}class Ir extends it{_parse(n){if(this._def.coerce&&(n.data=String(n.data)),this._getType(n)!==Te.string){const c=this._getOrReturnCtx(n);return Ee(c,{code:xe.invalid_type,expected:Te.string,received:c.parsedType}),Ie}const s=new $n;let i;for(const c of this._def.checks)if(c.kind==="min")n.data.length<c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),s.dirty());else if(c.kind==="max")n.data.length>c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),s.dirty());else if(c.kind==="length"){const u=n.data.length>c.value,f=n.data.length<c.value;(u||f)&&(i=this._getOrReturnCtx(n,i),u?Ee(i,{code:xe.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}):f&&Ee(i,{code:xe.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}),s.dirty())}else if(c.kind==="email")k3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"email",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="emoji")Vm||(Vm=new RegExp(M3,"u")),Vm.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"emoji",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="uuid")A3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"uuid",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="nanoid")T3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"nanoid",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="cuid")C3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cuid",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="cuid2")N3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cuid2",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="ulid")R3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"ulid",code:xe.invalid_string,message:c.message}),s.dirty());else if(c.kind==="url")try{new URL(n.data)}catch{i=this._getOrReturnCtx(n,i),Ee(i,{validation:"url",code:xe.invalid_string,message:c.message}),s.dirty()}else c.kind==="regex"?(c.regex.lastIndex=0,c.regex.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"regex",code:xe.invalid_string,message:c.message}),s.dirty())):c.kind==="trim"?n.data=n.data.trim():c.kind==="includes"?n.data.includes(c.value,c.position)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:{includes:c.value,position:c.position},message:c.message}),s.dirty()):c.kind==="toLowerCase"?n.data=n.data.toLowerCase():c.kind==="toUpperCase"?n.data=n.data.toUpperCase():c.kind==="startsWith"?n.data.startsWith(c.value)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:{startsWith:c.value},message:c.message}),s.dirty()):c.kind==="endsWith"?n.data.endsWith(c.value)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:{endsWith:c.value},message:c.message}),s.dirty()):c.kind==="datetime"?I3(c).test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:"datetime",message:c.message}),s.dirty()):c.kind==="date"?H3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:"date",message:c.message}),s.dirty()):c.kind==="time"?V3(c).test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.invalid_string,validation:"time",message:c.message}),s.dirty()):c.kind==="duration"?j3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"duration",code:xe.invalid_string,message:c.message}),s.dirty()):c.kind==="ip"?q3(n.data,c.version)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"ip",code:xe.invalid_string,message:c.message}),s.dirty()):c.kind==="jwt"?F3(n.data,c.alg)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"jwt",code:xe.invalid_string,message:c.message}),s.dirty()):c.kind==="cidr"?$3(n.data,c.version)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"cidr",code:xe.invalid_string,message:c.message}),s.dirty()):c.kind==="base64"?B3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"base64",code:xe.invalid_string,message:c.message}),s.dirty()):c.kind==="base64url"?P3.test(n.data)||(i=this._getOrReturnCtx(n,i),Ee(i,{validation:"base64url",code:xe.invalid_string,message:c.message}),s.dirty()):dt.assertNever(c);return{status:s.value,value:n.data}}_regex(n,r,s){return this.refinement(i=>n.test(i),{validation:r,code:xe.invalid_string,...ke.errToObj(s)})}_addCheck(n){return new Ir({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...ke.errToObj(n)})}url(n){return this._addCheck({kind:"url",...ke.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...ke.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...ke.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...ke.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...ke.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...ke.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...ke.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...ke.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...ke.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...ke.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...ke.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...ke.errToObj(n)})}datetime(n){return typeof n=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n}):this._addCheck({kind:"datetime",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,offset:(n==null?void 0:n.offset)??!1,local:(n==null?void 0:n.local)??!1,...ke.errToObj(n==null?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){return typeof n=="string"?this._addCheck({kind:"time",precision:null,message:n}):this._addCheck({kind:"time",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,...ke.errToObj(n==null?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...ke.errToObj(n)})}regex(n,r){return this._addCheck({kind:"regex",regex:n,...ke.errToObj(r)})}includes(n,r){return this._addCheck({kind:"includes",value:n,position:r==null?void 0:r.position,...ke.errToObj(r==null?void 0:r.message)})}startsWith(n,r){return this._addCheck({kind:"startsWith",value:n,...ke.errToObj(r)})}endsWith(n,r){return this._addCheck({kind:"endsWith",value:n,...ke.errToObj(r)})}min(n,r){return this._addCheck({kind:"min",value:n,...ke.errToObj(r)})}max(n,r){return this._addCheck({kind:"max",value:n,...ke.errToObj(r)})}length(n,r){return this._addCheck({kind:"length",value:n,...ke.errToObj(r)})}nonempty(n){return this.min(1,ke.errToObj(n))}trim(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(n=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find(n=>n.kind==="date")}get isTime(){return!!this._def.checks.find(n=>n.kind==="time")}get isDuration(){return!!this._def.checks.find(n=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find(n=>n.kind==="email")}get isURL(){return!!this._def.checks.find(n=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find(n=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find(n=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(n=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(n=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(n=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find(n=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find(n=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find(n=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find(n=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find(n=>n.kind==="base64url")}get minLength(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxLength(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}}Ir.create=t=>new Ir({checks:[],typeName:Fe.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ke(t)});function G3(t,n){const r=(t.toString().split(".")[1]||"").length,s=(n.toString().split(".")[1]||"").length,i=r>s?r:s,c=Number.parseInt(t.toFixed(i).replace(".","")),u=Number.parseInt(n.toFixed(i).replace(".",""));return c%u/10**i}class rl extends it{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce&&(n.data=Number(n.data)),this._getType(n)!==Te.number){const c=this._getOrReturnCtx(n);return Ee(c,{code:xe.invalid_type,expected:Te.number,received:c.parsedType}),Ie}let s;const i=new $n;for(const c of this._def.checks)c.kind==="int"?dt.isInteger(n.data)||(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.invalid_type,expected:"integer",received:"float",message:c.message}),i.dirty()):c.kind==="min"?(c.inclusive?n.data<c.value:n.data<=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.too_small,minimum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),i.dirty()):c.kind==="max"?(c.inclusive?n.data>c.value:n.data>=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.too_big,maximum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),i.dirty()):c.kind==="multipleOf"?G3(n.data,c.value)!==0&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.not_multiple_of,multipleOf:c.value,message:c.message}),i.dirty()):c.kind==="finite"?Number.isFinite(n.data)||(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.not_finite,message:c.message}),i.dirty()):dt.assertNever(c);return{status:i.value,value:n.data}}gte(n,r){return this.setLimit("min",n,!0,ke.toString(r))}gt(n,r){return this.setLimit("min",n,!1,ke.toString(r))}lte(n,r){return this.setLimit("max",n,!0,ke.toString(r))}lt(n,r){return this.setLimit("max",n,!1,ke.toString(r))}setLimit(n,r,s,i){return new rl({...this._def,checks:[...this._def.checks,{kind:n,value:r,inclusive:s,message:ke.toString(i)}]})}_addCheck(n){return new rl({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:ke.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ke.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ke.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ke.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ke.toString(n)})}multipleOf(n,r){return this._addCheck({kind:"multipleOf",value:n,message:ke.toString(r)})}finite(n){return this._addCheck({kind:"finite",message:ke.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ke.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ke.toString(n)})}get minValue(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxValue(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}get isInt(){return!!this._def.checks.find(n=>n.kind==="int"||n.kind==="multipleOf"&&dt.isInteger(n.value))}get isFinite(){let n=null,r=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(r===null||s.value>r)&&(r=s.value):s.kind==="max"&&(n===null||s.value<n)&&(n=s.value)}return Number.isFinite(r)&&Number.isFinite(n)}}rl.create=t=>new rl({checks:[],typeName:Fe.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ke(t)});class sl extends it{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==Te.bigint)return this._getInvalidInput(n);let s;const i=new $n;for(const c of this._def.checks)c.kind==="min"?(c.inclusive?n.data<c.value:n.data<=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.too_small,type:"bigint",minimum:c.value,inclusive:c.inclusive,message:c.message}),i.dirty()):c.kind==="max"?(c.inclusive?n.data>c.value:n.data>=c.value)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.too_big,type:"bigint",maximum:c.value,inclusive:c.inclusive,message:c.message}),i.dirty()):c.kind==="multipleOf"?n.data%c.value!==BigInt(0)&&(s=this._getOrReturnCtx(n,s),Ee(s,{code:xe.not_multiple_of,multipleOf:c.value,message:c.message}),i.dirty()):dt.assertNever(c);return{status:i.value,value:n.data}}_getInvalidInput(n){const r=this._getOrReturnCtx(n);return Ee(r,{code:xe.invalid_type,expected:Te.bigint,received:r.parsedType}),Ie}gte(n,r){return this.setLimit("min",n,!0,ke.toString(r))}gt(n,r){return this.setLimit("min",n,!1,ke.toString(r))}lte(n,r){return this.setLimit("max",n,!0,ke.toString(r))}lt(n,r){return this.setLimit("max",n,!1,ke.toString(r))}setLimit(n,r,s,i){return new sl({...this._def,checks:[...this._def.checks,{kind:n,value:r,inclusive:s,message:ke.toString(i)}]})}_addCheck(n){return new sl({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ke.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ke.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ke.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ke.toString(n)})}multipleOf(n,r){return this._addCheck({kind:"multipleOf",value:n,message:ke.toString(r)})}get minValue(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n}get maxValue(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n}}sl.create=t=>new sl({checks:[],typeName:Fe.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ke(t)});class mh extends it{_parse(n){if(this._def.coerce&&(n.data=!!n.data),this._getType(n)!==Te.boolean){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.boolean,received:s.parsedType}),Ie}return la(n.data)}}mh.create=t=>new mh({typeName:Fe.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ke(t)});class Su extends it{_parse(n){if(this._def.coerce&&(n.data=new Date(n.data)),this._getType(n)!==Te.date){const c=this._getOrReturnCtx(n);return Ee(c,{code:xe.invalid_type,expected:Te.date,received:c.parsedType}),Ie}if(Number.isNaN(n.data.getTime())){const c=this._getOrReturnCtx(n);return Ee(c,{code:xe.invalid_date}),Ie}const s=new $n;let i;for(const c of this._def.checks)c.kind==="min"?n.data.getTime()<c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.too_small,message:c.message,inclusive:!0,exact:!1,minimum:c.value,type:"date"}),s.dirty()):c.kind==="max"?n.data.getTime()>c.value&&(i=this._getOrReturnCtx(n,i),Ee(i,{code:xe.too_big,message:c.message,inclusive:!0,exact:!1,maximum:c.value,type:"date"}),s.dirty()):dt.assertNever(c);return{status:s.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Su({...this._def,checks:[...this._def.checks,n]})}min(n,r){return this._addCheck({kind:"min",value:n.getTime(),message:ke.toString(r)})}max(n,r){return this._addCheck({kind:"max",value:n.getTime(),message:ke.toString(r)})}get minDate(){let n=null;for(const r of this._def.checks)r.kind==="min"&&(n===null||r.value>n)&&(n=r.value);return n!=null?new Date(n):null}get maxDate(){let n=null;for(const r of this._def.checks)r.kind==="max"&&(n===null||r.value<n)&&(n=r.value);return n!=null?new Date(n):null}}Su.create=t=>new Su({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Fe.ZodDate,...Ke(t)});class n0 extends it{_parse(n){if(this._getType(n)!==Te.symbol){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.symbol,received:s.parsedType}),Ie}return la(n.data)}}n0.create=t=>new n0({typeName:Fe.ZodSymbol,...Ke(t)});class a0 extends it{_parse(n){if(this._getType(n)!==Te.undefined){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.undefined,received:s.parsedType}),Ie}return la(n.data)}}a0.create=t=>new a0({typeName:Fe.ZodUndefined,...Ke(t)});class r0 extends it{_parse(n){if(this._getType(n)!==Te.null){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.null,received:s.parsedType}),Ie}return la(n.data)}}r0.create=t=>new r0({typeName:Fe.ZodNull,...Ke(t)});class s0 extends it{constructor(){super(...arguments),this._any=!0}_parse(n){return la(n.data)}}s0.create=t=>new s0({typeName:Fe.ZodAny,...Ke(t)});class o0 extends it{constructor(){super(...arguments),this._unknown=!0}_parse(n){return la(n.data)}}o0.create=t=>new o0({typeName:Fe.ZodUnknown,...Ke(t)});class Zr extends it{_parse(n){const r=this._getOrReturnCtx(n);return Ee(r,{code:xe.invalid_type,expected:Te.never,received:r.parsedType}),Ie}}Zr.create=t=>new Zr({typeName:Fe.ZodNever,...Ke(t)});class i0 extends it{_parse(n){if(this._getType(n)!==Te.undefined){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.void,received:s.parsedType}),Ie}return la(n.data)}}i0.create=t=>new i0({typeName:Fe.ZodVoid,...Ke(t)});class Ma extends it{_parse(n){const{ctx:r,status:s}=this._processInputParams(n),i=this._def;if(r.parsedType!==Te.array)return Ee(r,{code:xe.invalid_type,expected:Te.array,received:r.parsedType}),Ie;if(i.exactLength!==null){const u=r.data.length>i.exactLength.value,f=r.data.length<i.exactLength.value;(u||f)&&(Ee(r,{code:u?xe.too_big:xe.too_small,minimum:f?i.exactLength.value:void 0,maximum:u?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Ee(r,{code:xe.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Ee(r,{code:xe.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()),r.common.async)return Promise.all([...r.data].map((u,f)=>i.type._parseAsync(new Yr(r,u,r.path,f)))).then(u=>$n.mergeArray(s,u));const c=[...r.data].map((u,f)=>i.type._parseSync(new Yr(r,u,r.path,f)));return $n.mergeArray(s,c)}get element(){return this._def.type}min(n,r){return new Ma({...this._def,minLength:{value:n,message:ke.toString(r)}})}max(n,r){return new Ma({...this._def,maxLength:{value:n,message:ke.toString(r)}})}length(n,r){return new Ma({...this._def,exactLength:{value:n,message:ke.toString(r)}})}nonempty(n){return this.min(1,n)}}Ma.create=(t,n)=>new Ma({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Fe.ZodArray,...Ke(n)});function Ro(t){if(t instanceof Gt){const n={};for(const r in t.shape){const s=t.shape[r];n[r]=qr.create(Ro(s))}return new Gt({...t._def,shape:()=>n})}else return t instanceof Ma?new Ma({...t._def,type:Ro(t.element)}):t instanceof qr?qr.create(Ro(t.unwrap())):t instanceof Vo?Vo.create(Ro(t.unwrap())):t instanceof Rs?Rs.create(t.items.map(n=>Ro(n))):t}class Gt extends it{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const n=this._def.shape(),r=dt.objectKeys(n);return this._cached={shape:n,keys:r},this._cached}_parse(n){if(this._getType(n)!==Te.object){const p=this._getOrReturnCtx(n);return Ee(p,{code:xe.invalid_type,expected:Te.object,received:p.parsedType}),Ie}const{status:s,ctx:i}=this._processInputParams(n),{shape:c,keys:u}=this._getCached(),f=[];if(!(this._def.catchall instanceof Zr&&this._def.unknownKeys==="strip"))for(const p in i.data)u.includes(p)||f.push(p);const g=[];for(const p of u){const y=c[p],v=i.data[p];g.push({key:{status:"valid",value:p},value:y._parse(new Yr(i,v,i.path,p)),alwaysSet:p in i.data})}if(this._def.catchall instanceof Zr){const p=this._def.unknownKeys;if(p==="passthrough")for(const y of f)g.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(p==="strict")f.length>0&&(Ee(i,{code:xe.unrecognized_keys,keys:f}),s.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const p=this._def.catchall;for(const y of f){const v=i.data[y];g.push({key:{status:"valid",value:y},value:p._parse(new Yr(i,v,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const p=[];for(const y of g){const v=await y.key,w=await y.value;p.push({key:v,value:w,alwaysSet:y.alwaysSet})}return p}).then(p=>$n.mergeObjectSync(s,p)):$n.mergeObjectSync(s,g)}get shape(){return this._def.shape()}strict(n){return ke.errToObj,new Gt({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(r,s)=>{var c,u;const i=((u=(c=this._def).errorMap)==null?void 0:u.call(c,r,s).message)??s.defaultError;return r.code==="unrecognized_keys"?{message:ke.errToObj(n).message??i}:{message:i}}}:{}})}strip(){return new Gt({...this._def,unknownKeys:"strip"})}passthrough(){return new Gt({...this._def,unknownKeys:"passthrough"})}extend(n){return new Gt({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new Gt({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:Fe.ZodObject})}setKey(n,r){return this.augment({[n]:r})}catchall(n){return new Gt({...this._def,catchall:n})}pick(n){const r={};for(const s of dt.objectKeys(n))n[s]&&this.shape[s]&&(r[s]=this.shape[s]);return new Gt({...this._def,shape:()=>r})}omit(n){const r={};for(const s of dt.objectKeys(this.shape))n[s]||(r[s]=this.shape[s]);return new Gt({...this._def,shape:()=>r})}deepPartial(){return Ro(this)}partial(n){const r={};for(const s of dt.objectKeys(this.shape)){const i=this.shape[s];n&&!n[s]?r[s]=i:r[s]=i.optional()}return new Gt({...this._def,shape:()=>r})}required(n){const r={};for(const s of dt.objectKeys(this.shape))if(n&&!n[s])r[s]=this.shape[s];else{let c=this.shape[s];for(;c instanceof qr;)c=c._def.innerType;r[s]=c}return new Gt({...this._def,shape:()=>r})}keyof(){return eE(dt.objectKeys(this.shape))}}Gt.create=(t,n)=>new Gt({shape:()=>t,unknownKeys:"strip",catchall:Zr.create(),typeName:Fe.ZodObject,...Ke(n)});Gt.strictCreate=(t,n)=>new Gt({shape:()=>t,unknownKeys:"strict",catchall:Zr.create(),typeName:Fe.ZodObject,...Ke(n)});Gt.lazycreate=(t,n)=>new Gt({shape:t,unknownKeys:"strip",catchall:Zr.create(),typeName:Fe.ZodObject,...Ke(n)});class Eu extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s=this._def.options;function i(c){for(const f of c)if(f.result.status==="valid")return f.result;for(const f of c)if(f.result.status==="dirty")return r.common.issues.push(...f.ctx.common.issues),f.result;const u=c.map(f=>new lr(f.ctx.common.issues));return Ee(r,{code:xe.invalid_union,unionErrors:u}),Ie}if(r.common.async)return Promise.all(s.map(async c=>{const u={...r,common:{...r.common,issues:[]},parent:null};return{result:await c._parseAsync({data:r.data,path:r.path,parent:u}),ctx:u}})).then(i);{let c;const u=[];for(const g of s){const p={...r,common:{...r.common,issues:[]},parent:null},y=g._parseSync({data:r.data,path:r.path,parent:p});if(y.status==="valid")return y;y.status==="dirty"&&!c&&(c={result:y,ctx:p}),p.common.issues.length&&u.push(p.common.issues)}if(c)return r.common.issues.push(...c.ctx.common.issues),c.result;const f=u.map(g=>new lr(g));return Ee(r,{code:xe.invalid_union,unionErrors:f}),Ie}}get options(){return this._def.options}}Eu.create=(t,n)=>new Eu({options:t,typeName:Fe.ZodUnion,...Ke(n)});function hh(t,n){const r=Hr(t),s=Hr(n);if(t===n)return{valid:!0,data:t};if(r===Te.object&&s===Te.object){const i=dt.objectKeys(n),c=dt.objectKeys(t).filter(f=>i.indexOf(f)!==-1),u={...t,...n};for(const f of c){const g=hh(t[f],n[f]);if(!g.valid)return{valid:!1};u[f]=g.data}return{valid:!0,data:u}}else if(r===Te.array&&s===Te.array){if(t.length!==n.length)return{valid:!1};const i=[];for(let c=0;c<t.length;c++){const u=t[c],f=n[c],g=hh(u,f);if(!g.valid)return{valid:!1};i.push(g.data)}return{valid:!0,data:i}}else return r===Te.date&&s===Te.date&&+t==+n?{valid:!0,data:t}:{valid:!1}}class _u extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n),i=(c,u)=>{if(Jx(c)||Jx(u))return Ie;const f=hh(c.value,u.value);return f.valid?((e0(c)||e0(u))&&r.dirty(),{status:r.value,value:f.data}):(Ee(s,{code:xe.invalid_intersection_types}),Ie)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([c,u])=>i(c,u)):i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}_u.create=(t,n,r)=>new _u({left:t,right:n,typeName:Fe.ZodIntersection,...Ke(r)});class Rs extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.array)return Ee(s,{code:xe.invalid_type,expected:Te.array,received:s.parsedType}),Ie;if(s.data.length<this._def.items.length)return Ee(s,{code:xe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ie;!this._def.rest&&s.data.length>this._def.items.length&&(Ee(s,{code:xe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const c=[...s.data].map((u,f)=>{const g=this._def.items[f]||this._def.rest;return g?g._parse(new Yr(s,u,s.path,f)):null}).filter(u=>!!u);return s.common.async?Promise.all(c).then(u=>$n.mergeArray(r,u)):$n.mergeArray(r,c)}get items(){return this._def.items}rest(n){return new Rs({...this._def,rest:n})}}Rs.create=(t,n)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rs({items:t,typeName:Fe.ZodTuple,rest:null,...Ke(n)})};class l0 extends it{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.map)return Ee(s,{code:xe.invalid_type,expected:Te.map,received:s.parsedType}),Ie;const i=this._def.keyType,c=this._def.valueType,u=[...s.data.entries()].map(([f,g],p)=>({key:i._parse(new Yr(s,f,s.path,[p,"key"])),value:c._parse(new Yr(s,g,s.path,[p,"value"]))}));if(s.common.async){const f=new Map;return Promise.resolve().then(async()=>{for(const g of u){const p=await g.key,y=await g.value;if(p.status==="aborted"||y.status==="aborted")return Ie;(p.status==="dirty"||y.status==="dirty")&&r.dirty(),f.set(p.value,y.value)}return{status:r.value,value:f}})}else{const f=new Map;for(const g of u){const p=g.key,y=g.value;if(p.status==="aborted"||y.status==="aborted")return Ie;(p.status==="dirty"||y.status==="dirty")&&r.dirty(),f.set(p.value,y.value)}return{status:r.value,value:f}}}}l0.create=(t,n,r)=>new l0({valueType:n,keyType:t,typeName:Fe.ZodMap,...Ke(r)});class ol extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.parsedType!==Te.set)return Ee(s,{code:xe.invalid_type,expected:Te.set,received:s.parsedType}),Ie;const i=this._def;i.minSize!==null&&s.data.size<i.minSize.value&&(Ee(s,{code:xe.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&s.data.size>i.maxSize.value&&(Ee(s,{code:xe.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const c=this._def.valueType;function u(g){const p=new Set;for(const y of g){if(y.status==="aborted")return Ie;y.status==="dirty"&&r.dirty(),p.add(y.value)}return{status:r.value,value:p}}const f=[...s.data.values()].map((g,p)=>c._parse(new Yr(s,g,s.path,p)));return s.common.async?Promise.all(f).then(g=>u(g)):u(f)}min(n,r){return new ol({...this._def,minSize:{value:n,message:ke.toString(r)}})}max(n,r){return new ol({...this._def,maxSize:{value:n,message:ke.toString(r)}})}size(n,r){return this.min(n,r).max(n,r)}nonempty(n){return this.min(1,n)}}ol.create=(t,n)=>new ol({valueType:t,minSize:null,maxSize:null,typeName:Fe.ZodSet,...Ke(n)});class c0 extends it{get schema(){return this._def.getter()}_parse(n){const{ctx:r}=this._processInputParams(n);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}c0.create=(t,n)=>new c0({getter:t,typeName:Fe.ZodLazy,...Ke(n)});class ph extends it{_parse(n){if(n.data!==this._def.value){const r=this._getOrReturnCtx(n);return Ee(r,{received:r.data,code:xe.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:n.data}}get value(){return this._def.value}}ph.create=(t,n)=>new ph({value:t,typeName:Fe.ZodLiteral,...Ke(n)});function eE(t,n){return new Po({values:t,typeName:Fe.ZodEnum,...Ke(n)})}class Po extends it{_parse(n){if(typeof n.data!="string"){const r=this._getOrReturnCtx(n),s=this._def.values;return Ee(r,{expected:dt.joinValues(s),received:r.parsedType,code:xe.invalid_type}),Ie}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(n.data)){const r=this._getOrReturnCtx(n),s=this._def.values;return Ee(r,{received:r.data,code:xe.invalid_enum_value,options:s}),Ie}return la(n.data)}get options(){return this._def.values}get enum(){const n={};for(const r of this._def.values)n[r]=r;return n}get Values(){const n={};for(const r of this._def.values)n[r]=r;return n}get Enum(){const n={};for(const r of this._def.values)n[r]=r;return n}extract(n,r=this._def){return Po.create(n,{...this._def,...r})}exclude(n,r=this._def){return Po.create(this.options.filter(s=>!n.includes(s)),{...this._def,...r})}}Po.create=eE;class u0 extends it{_parse(n){const r=dt.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(n);if(s.parsedType!==Te.string&&s.parsedType!==Te.number){const i=dt.objectValues(r);return Ee(s,{expected:dt.joinValues(i),received:s.parsedType,code:xe.invalid_type}),Ie}if(this._cache||(this._cache=new Set(dt.getValidEnumValues(this._def.values))),!this._cache.has(n.data)){const i=dt.objectValues(r);return Ee(s,{received:s.data,code:xe.invalid_enum_value,options:i}),Ie}return la(n.data)}get enum(){return this._def.values}}u0.create=(t,n)=>new u0({values:t,typeName:Fe.ZodNativeEnum,...Ke(n)});class Cu extends it{unwrap(){return this._def.type}_parse(n){const{ctx:r}=this._processInputParams(n);if(r.parsedType!==Te.promise&&r.common.async===!1)return Ee(r,{code:xe.invalid_type,expected:Te.promise,received:r.parsedType}),Ie;const s=r.parsedType===Te.promise?r.data:Promise.resolve(r.data);return la(s.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Cu.create=(t,n)=>new Cu({type:t,typeName:Fe.ZodPromise,...Ke(n)});class Ho extends it{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:r,ctx:s}=this._processInputParams(n),i=this._def.effect||null,c={addIssue:u=>{Ee(s,u),u.fatal?r.abort():r.dirty()},get path(){return s.path}};if(c.addIssue=c.addIssue.bind(c),i.type==="preprocess"){const u=i.transform(s.data,c);if(s.common.async)return Promise.resolve(u).then(async f=>{if(r.value==="aborted")return Ie;const g=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});return g.status==="aborted"?Ie:g.status==="dirty"||r.value==="dirty"?Ki(g.value):g});{if(r.value==="aborted")return Ie;const f=this._def.schema._parseSync({data:u,path:s.path,parent:s});return f.status==="aborted"?Ie:f.status==="dirty"||r.value==="dirty"?Ki(f.value):f}}if(i.type==="refinement"){const u=f=>{const g=i.refinement(f,c);if(s.common.async)return Promise.resolve(g);if(g instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){const f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return f.status==="aborted"?Ie:(f.status==="dirty"&&r.dirty(),u(f.value),{status:r.value,value:f.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(f=>f.status==="aborted"?Ie:(f.status==="dirty"&&r.dirty(),u(f.value).then(()=>({status:r.value,value:f.value}))))}if(i.type==="transform")if(s.common.async===!1){const u=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Bo(u))return Ie;const f=i.transform(u.value,c);if(f instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(u=>Bo(u)?Promise.resolve(i.transform(u.value,c)).then(f=>({status:r.value,value:f})):Ie);dt.assertNever(i)}}Ho.create=(t,n,r)=>new Ho({schema:t,typeName:Fe.ZodEffects,effect:n,...Ke(r)});Ho.createWithPreprocess=(t,n,r)=>new Ho({schema:n,effect:{type:"preprocess",transform:t},typeName:Fe.ZodEffects,...Ke(r)});class qr extends it{_parse(n){return this._getType(n)===Te.undefined?la(void 0):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}qr.create=(t,n)=>new qr({innerType:t,typeName:Fe.ZodOptional,...Ke(n)});class Vo extends it{_parse(n){return this._getType(n)===Te.null?la(null):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Vo.create=(t,n)=>new Vo({innerType:t,typeName:Fe.ZodNullable,...Ke(n)});class gh extends it{_parse(n){const{ctx:r}=this._processInputParams(n);let s=r.data;return r.parsedType===Te.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gh.create=(t,n)=>new gh({innerType:t,typeName:Fe.ZodDefault,defaultValue:typeof n.default=="function"?n.default:()=>n.default,...Ke(n)});class vh extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return wu(i)?i.then(c=>({status:"valid",value:c.status==="valid"?c.value:this._def.catchValue({get error(){return new lr(s.common.issues)},input:s.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new lr(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}vh.create=(t,n)=>new vh({innerType:t,typeName:Fe.ZodCatch,catchValue:typeof n.catch=="function"?n.catch:()=>n.catch,...Ke(n)});class d0 extends it{_parse(n){if(this._getType(n)!==Te.nan){const s=this._getOrReturnCtx(n);return Ee(s,{code:xe.invalid_type,expected:Te.nan,received:s.parsedType}),Ie}return{status:"valid",value:n.data}}}d0.create=t=>new d0({typeName:Fe.ZodNaN,...Ke(t)});class Y3 extends it{_parse(n){const{ctx:r}=this._processInputParams(n),s=r.data;return this._def.type._parse({data:s,path:r.path,parent:r})}unwrap(){return this._def.type}}class vp extends it{_parse(n){const{status:r,ctx:s}=this._processInputParams(n);if(s.common.async)return(async()=>{const c=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?Ie:c.status==="dirty"?(r.dirty(),Ki(c.value)):this._def.out._parseAsync({data:c.value,path:s.path,parent:s})})();{const i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?Ie:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(n,r){return new vp({in:n,out:r,typeName:Fe.ZodPipeline})}}class yh extends it{_parse(n){const r=this._def.innerType._parse(n),s=i=>(Bo(i)&&(i.value=Object.freeze(i.value)),i);return wu(r)?r.then(i=>s(i)):s(r)}unwrap(){return this._def.innerType}}yh.create=(t,n)=>new yh({innerType:t,typeName:Fe.ZodReadonly,...Ke(n)});var Fe;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Fe||(Fe={}));const Yt=Ir.create,Ta=mh.create;Zr.create;const Z3=Ma.create,Xo=Gt.create;Eu.create;_u.create;Rs.create;const X3=ph.create;Po.create;Cu.create;qr.create;Vo.create;const f0=(t,n,r)=>{if(t&&"reportValidity"in t){const s=Ce(r,n);t.setCustomValidity(s&&s.message||""),t.reportValidity()}},bh=(t,n)=>{for(const r in n.fields){const s=n.fields[r];s&&s.ref&&"reportValidity"in s.ref?f0(s.ref,r,t):s&&s.refs&&s.refs.forEach(i=>f0(i,r,t))}},m0=(t,n)=>{n.shouldUseNativeValidation&&bh(t,n);const r={};for(const s in t){const i=Ce(n.fields,s),c=Object.assign(t[s]||{},{ref:i&&i.ref});if(K3(n.names||Object.keys(t),s)){const u=Object.assign({},Ce(r,s));xt(u,"root",c),xt(r,s,u)}else xt(r,s,c)}return r},K3=(t,n)=>{const r=h0(n);return t.some(s=>h0(s).match(`^${r}\\.\\d+`))};function h0(t){return t.replace(/\]|\[/g,"")}function tE(t,n,r){function s(f,g){var p;Object.defineProperty(f,"_zod",{value:f._zod??{},enumerable:!1}),(p=f._zod).traits??(p.traits=new Set),f._zod.traits.add(t),n(f,g);for(const y in u.prototype)y in f||Object.defineProperty(f,y,{value:u.prototype[y].bind(f)});f._zod.constr=u,f._zod.def=g}const i=(r==null?void 0:r.Parent)??Object;class c extends i{}Object.defineProperty(c,"name",{value:t});function u(f){var g;const p=r!=null&&r.Parent?new c:this;s(p,f),(g=p._zod).deferred??(g.deferred=[]);for(const y of p._zod.deferred)y();return p}return Object.defineProperty(u,"init",{value:s}),Object.defineProperty(u,Symbol.hasInstance,{value:f=>{var g,p;return r!=null&&r.Parent&&f instanceof r.Parent?!0:(p=(g=f==null?void 0:f._zod)==null?void 0:g.traits)==null?void 0:p.has(t)}}),Object.defineProperty(u,"name",{value:t}),u}class Q3 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const W3={};function nE(t){return W3}function J3(t,n){return typeof n=="bigint"?n.toString():n}const aE=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Fc(t){return typeof t=="string"?t:t==null?void 0:t.message}function rE(t,n,r){var i,c,u,f,g,p;const s={...t,path:t.path??[]};if(!t.message){const y=Fc((u=(c=(i=t.inst)==null?void 0:i._zod.def)==null?void 0:c.error)==null?void 0:u.call(c,t))??Fc((f=n==null?void 0:n.error)==null?void 0:f.call(n,t))??Fc((g=r.customError)==null?void 0:g.call(r,t))??Fc((p=r.localeError)==null?void 0:p.call(r,t))??"Invalid input";s.message=y}return delete s.inst,delete s.continue,n!=null&&n.reportInput||delete s.input,s}const sE=(t,n)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:n,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(n,J3,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},e5=tE("$ZodError",sE),oE=tE("$ZodError",sE,{Parent:Error}),t5=t=>(n,r,s,i)=>{const c=s?Object.assign(s,{async:!1}):{async:!1},u=n._zod.run({value:r,issues:[]},c);if(u instanceof Promise)throw new Q3;if(u.issues.length){const f=new((i==null?void 0:i.Err)??t)(u.issues.map(g=>rE(g,c,nE())));throw aE(f,i==null?void 0:i.callee),f}return u.value},n5=t5(oE),a5=t=>async(n,r,s,i)=>{const c=s?Object.assign(s,{async:!0}):{async:!0};let u=n._zod.run({value:r,issues:[]},c);if(u instanceof Promise&&(u=await u),u.issues.length){const f=new((i==null?void 0:i.Err)??t)(u.issues.map(g=>rE(g,c,nE())));throw aE(f,i==null?void 0:i.callee),f}return u.value},r5=a5(oE);function p0(t,n){try{var r=t()}catch(s){return n(s)}return r&&r.then?r.then(void 0,n):r}function s5(t,n){for(var r={};t.length;){var s=t[0],i=s.code,c=s.message,u=s.path.join(".");if(!r[u])if("unionErrors"in s){var f=s.unionErrors[0].errors[0];r[u]={message:f.message,type:f.code}}else r[u]={message:c,type:i};if("unionErrors"in s&&s.unionErrors.forEach(function(y){return y.errors.forEach(function(v){return t.push(v)})}),n){var g=r[u].types,p=g&&g[s.code];r[u]=up(u,n,r,i,p?[].concat(p,s.message):s.message)}t.shift()}return r}function o5(t,n){for(var r={};t.length;){var s=t[0],i=s.code,c=s.message,u=s.path.join(".");if(!r[u])if(s.code==="invalid_union"&&s.errors.length>0){var f=s.errors[0][0];r[u]={message:f.message,type:f.code}}else r[u]={message:c,type:i};if(s.code==="invalid_union"&&s.errors.forEach(function(y){return y.forEach(function(v){return t.push(v)})}),n){var g=r[u].types,p=g&&g[s.code];r[u]=up(u,n,r,i,p?[].concat(p,s.message):s.message)}t.shift()}return r}function Io(t,n,r){if(r===void 0&&(r={}),(function(s){return"_def"in s&&typeof s._def=="object"&&"typeName"in s._def})(t))return function(s,i,c){try{return Promise.resolve(p0(function(){return Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](s,n)).then(function(u){return c.shouldUseNativeValidation&&bh({},c),{errors:{},values:r.raw?Object.assign({},s):u}})},function(u){if((function(f){return Array.isArray(f==null?void 0:f.issues)})(u))return{values:{},errors:m0(s5(u.errors,!c.shouldUseNativeValidation&&c.criteriaMode==="all"),c)};throw u}))}catch(u){return Promise.reject(u)}};if((function(s){return"_zod"in s&&typeof s._zod=="object"})(t))return function(s,i,c){try{return Promise.resolve(p0(function(){return Promise.resolve((r.mode==="sync"?n5:r5)(t,s,n)).then(function(u){return c.shouldUseNativeValidation&&bh({},c),{errors:{},values:r.raw?Object.assign({},s):u}})},function(u){if((function(f){return f instanceof e5})(u))return{values:{},errors:m0(o5(u.issues,!c.shouldUseNativeValidation&&c.criteriaMode==="all"),c)};throw u}))}catch(u){return Promise.reject(u)}};throw new Error("Invalid input: not a Zod schema")}const i5=()=>{const{login:t,checkLicense:n,setApiUrl:r,setApiKey:s,isAuthenticated:i,licenseState:c,apiUrl:u}=zu(),f=Xr(),[g,p]=b.useState(!1),[y,v]=b.useState("");b.useEffect(()=>{i&&c==="licensed"&&f("/manager",{replace:!0})},[i,c,f]);const w=window.location.origin,C=Xo({apiUrl:Yt().min(1,{message:"URL da API é obrigatória"}).url({message:`URL inválida. Use o formato: ${w}`}).refine(E=>E.startsWith("http://")||E.startsWith("https://"),{message:"URL deve começar com http:// ou https://"}),apiKey:Yt().min(1,{message:"API Key é obrigatória"}).min(10,{message:"API Key deve ter pelo menos 10 caracteres"})}),S=Lo({resolver:Io(C),defaultValues:{apiUrl:u,apiKey:""}}),_=async E=>{p(!0),v("");try{const R=E.apiUrl.replace(/\/$/,"");if(Ze.info("Verificando licenca..."),await n(R,E.apiKey)!=="licensed"){Ze.info("Licenca necessaria",{description:"Redirecionando para registro de licenca..."});const A=`${window.location.origin}/manager/license/callback`,D=await TO(A,R,E.apiKey);if(!D.register_url){Ze.error("Erro",{description:D.message||"Falha ao iniciar registro de licenca."}),v(D.message||"Falha ao iniciar registro.");return}r(R),s(E.apiKey),window.location.href=D.register_url;return}await t(E.apiUrl,E.apiKey),Ze.success("Conectado com sucesso!",{description:"Licenca valida. Bem-vindo!"}),f("/manager",{replace:!0})}catch(R){console.error("Erro ao fazer login:",R);const k=R instanceof Error?R.message:"Erro ao conectar. Verifique a URL e API Key.";Ze.error("Erro",{description:k}),v(k)}finally{p(!1)}};return h.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-gradient-to-t from-primary/20 via-background/95 to-background relative",children:h.jsxs("div",{className:"w-full max-w-md space-y-6",children:[h.jsx("div",{className:"text-center",children:h.jsx("h1",{className:"text-3xl font-bold text-primary",children:"Evolution GO"})}),h.jsxs("div",{className:"bg-background/80 backdrop-blur-sm border rounded-lg p-6 shadow-lg",children:[h.jsxs("div",{className:"space-y-2 mb-6",children:[h.jsx("h2",{className:"text-2xl font-bold",children:"Entrar na sua conta"}),h.jsx("p",{className:"text-muted-foreground",children:"Digite suas credenciais para acessar o sistema"})]}),y&&h.jsxs(o3,{variant:"destructive",className:"mb-4",children:[h.jsx(nR,{className:"h-4 w-4"}),h.jsx(i3,{children:"Erro"}),h.jsx(l3,{children:y})]}),h.jsxs("form",{onSubmit:S.handleSubmit(_),className:"space-y-4",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"login-apiUrl",children:"URL da API Evolution GO"}),h.jsx(Ra,{id:"login-apiUrl",type:"text",placeholder:w,disabled:g,...S.register("apiUrl")}),S.formState.errors.apiUrl&&h.jsx("p",{className:"text-destructive text-sm",children:S.formState.errors.apiUrl.message})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"login-apiKey",children:"API Key (GLOBAL_API_KEY)"}),h.jsx(Ra,{id:"login-apiKey",type:"password",placeholder:"Sua chave de API",disabled:g,...S.register("apiKey")}),S.formState.errors.apiKey&&h.jsx("p",{className:"text-destructive text-sm",children:S.formState.errors.apiKey.message})]}),h.jsx("div",{className:"text-xs text-muted-foreground",children:h.jsxs("p",{children:[h.jsx("strong",{children:"Dica:"})," A API Key é o valor da variável"," ",h.jsx("code",{className:"relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs",children:"GLOBAL_API_KEY"})," ","configurada no arquivo .env do Evolution GO."]})}),h.jsx(ut,{type:"submit",disabled:g,className:"w-full",children:g?"Conectando...":"Entrar"})]})]}),h.jsx("div",{className:"text-center text-xs text-muted-foreground",children:h.jsxs("p",{children:["Ao continuar, você concorda com nossos"," ",h.jsx("a",{href:"#",className:"underline hover:text-primary",children:"Termos de Serviço"})," ","e"," ",h.jsx("a",{href:"#",className:"underline hover:text-primary",children:"Política de Privacidade"}),"."]})})]})})};function l5(){return h.jsxs("div",{className:"p-6",children:[h.jsx("h1",{className:"mb-4 text-2xl font-bold text-foreground",children:"Dashboard"}),h.jsx("p",{className:"text-muted-foreground",children:"Dashboard content will be implemented here..."})]})}const iE=t=>{const n=t.connected?"open":"close";let r;if(t.qrcode){const s=t.qrcode.split("|");r={base64:s[0]||void 0,code:s[1]||void 0}}return{id:t.id,instanceName:t.name,status:n,apikey:t.token,owner:t.jid?t.jid.split("@")[0]:"",profileName:t.name,connected:t.connected,qrcode:r,webhook:t.webhook||void 0,rabbitmqEnable:t.rabbitmqEnable||void 0,websocketEnable:t.websocketEnable||void 0,natsEnable:t.natsEnable||void 0,events:t.events||void 0,disconnectReason:t.disconnect_reason||void 0,createdAt:t.createdAt,alwaysOnline:t.alwaysOnline,rejectCall:t.rejectCall,readMessages:t.readMessages,ignoreGroups:t.ignoreGroups,ignoreStatus:t.ignoreStatus}},c5=async()=>(await hn.get("/instance/all")).data.data.map(iE),$c=async t=>{const n=await hn.get(`/instance/info/${t}`);return iE(n.data.data)},u5=async t=>(await hn.post("/instance/create",t)).data,xh=async(t,n)=>{const r={webhookUrl:(n==null?void 0:n.webhookUrl)||"",subscribe:(n==null?void 0:n.subscribe)||[],rabbitmqEnable:(n==null?void 0:n.rabbitmqEnable)||"",websocketEnable:(n==null?void 0:n.websocketEnable)||"",natsEnable:(n==null?void 0:n.natsEnable)||""};return(await hn.post("/instance/connect",r,{headers:{apikey:t}})).data.data},d5=async(t,n)=>({pairingCode:(await hn.post("/instance/pair",{subscribe:n.subscribe,phone:n.phone},{headers:{apikey:t}})).data.data.PairingCode}),lE=async(t,n,r)=>{await hn.put(`/instance/${t}/advanced-settings`,r,{headers:{apikey:n}})},Im=async t=>{const n=await hn.get("/instance/qr",{headers:{apikey:t}});return{qrcode:n.data.data.Qrcode,code:n.data.data.Code}},cE=async t=>{await hn.delete("/instance/logout",{headers:{apikey:t}})},uE=async t=>{await hn.delete(`/instance/delete/${t}`)},f5=async(t,n)=>(await hn.post("/send/text",n,{headers:{apikey:t}})).data,dE=r1()(t=>({instances:[],isLoading:!1,error:null,fetchInstances:async()=>{t({isLoading:!0,error:null});try{const n=await c5();t({instances:n,isLoading:!1})}catch(n){console.error("Failed to fetch instances:",n),t({error:n instanceof Error?n.message:"Erro ao buscar instâncias",isLoading:!1})}},addInstance:n=>{t(r=>({instances:[...r.instances,n]}))},updateInstance:(n,r)=>{t(s=>({instances:s.instances.map(i=>i.instanceName===n?{...i,...r}:i)}))},removeInstance:n=>{t(r=>({instances:r.instances.filter(s=>s.instanceName!==n)}))},setLoading:n=>{t({isLoading:n})},setError:n=>{t({error:n})},clearError:()=>{t({error:null})}})),m5=t=>t==="open"?h.jsx(pu,{className:"bg-green-500/10 text-green-500 hover:bg-green-500/20",children:"Conectado"}):h.jsx(pu,{className:"bg-red-500/10 text-red-500 hover:bg-red-500/20",children:"Desconectado"});function h5({instance:t,isDeleting:n,onSettings:r,onDelete:s,onConnect:i,onDisconnect:c,onSendMessage:u}){const f=t.status==="open";return h.jsx(d3,{className:"group relative bg-sidebar border-sidebar-border hover:bg-sidebar-accent/30 transition-all duration-300 hover:shadow-lg hover:shadow-black/10 overflow-hidden",children:h.jsxs(f3,{className:"p-0",children:[h.jsxs("div",{className:"flex items-center gap-3 p-4 border-b border-sidebar-border",children:[t.profilePicUrl&&h.jsx("div",{className:"flex-shrink-0 dark",children:h.jsx("div",{className:"rounded-lg bg-gray-900 flex items-center justify-center w-14 h-14 overflow-hidden",children:h.jsx("img",{src:t.profilePicUrl,alt:t.profileName||t.instanceName,className:"w-12 h-12 object-cover rounded-lg",onError:g=>{const p=g.target;p.style.display="none"}})})}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("h3",{className:"font-semibold text-base truncate text-sidebar-foreground",children:t.profileName||t.instanceName}),h.jsx("p",{className:"text-xs text-sidebar-foreground/60 truncate",children:t.instanceName})]}),h.jsx("div",{className:"flex-shrink-0",children:m5(t.status)})]}),h.jsxs("div",{className:"px-4 py-3 text-xs text-sidebar-foreground/70 space-y-1",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{children:"Status"}),h.jsx("span",{className:"font-mono",children:t.status})]}),t.profileStatus&&h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{children:"Recado"}),h.jsx("span",{className:"font-mono truncate ml-2 max-w-[150px]",children:t.profileStatus})]}),t.owner&&h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{children:"Proprietário"}),h.jsx("span",{className:"font-mono truncate ml-2 max-w-[150px]",children:t.owner})]})]}),h.jsxs("div",{className:"flex border-t border-sidebar-border opacity-0 group-hover:opacity-100 transition-opacity duration-200",children:[!f&&h.jsxs(ut,{variant:"ghost",className:"flex-1 rounded-none h-12 text-green-500 hover:text-green-400 hover:bg-green-500/10",onClick:()=>i(t),children:[h.jsx(V0,{className:"h-4 w-4 mr-2"}),"Conectar"]}),f&&h.jsxs(ut,{variant:"ghost",className:"flex-1 rounded-none h-12 text-yellow-500 hover:text-yellow-400 hover:bg-yellow-500/10",onClick:()=>c(t),children:[h.jsx(jR,{className:"h-4 w-4 mr-2"}),"Desconectar"]}),h.jsx("div",{className:"w-px bg-sidebar-border"}),f&&u&&h.jsxs(h.Fragment,{children:[h.jsx(ut,{variant:"ghost",className:"rounded-none h-12 px-4 text-blue-500 hover:text-blue-400 hover:bg-blue-500/10",onClick:()=>u(t),children:h.jsx(NR,{className:"h-4 w-4"})}),h.jsx("div",{className:"w-px bg-sidebar-border"})]}),h.jsx(ut,{variant:"ghost",className:"rounded-none h-12 px-4 text-gray-500 hover:text-gray-300 hover:bg-gray-500/10",onClick:()=>r(t),children:h.jsx(PR,{className:"h-4 w-4"})}),h.jsx("div",{className:"w-px bg-sidebar-border"}),h.jsx(ut,{variant:"ghost",className:"rounded-none h-12 px-4 text-red-500 hover:text-red-400 hover:bg-red-500/10",disabled:n===t.instanceName,onClick:()=>s(t),children:h.jsx(Th,{className:"h-4 w-4"})})]})]})})}function p5({title:t,subtitle:n,searchValue:r,onSearchChange:s,searchPlaceholder:i="Buscar...",primaryAction:c,secondaryActions:u=[],moreActions:f=[],filters:g=[],onFilterClick:p,showFilters:y=!1,selectedCount:v=0,onClearSelection:w,bulkActions:C=[],className:S="",children:_}){const E=v>0,R=u.filter(A=>A.show!==!1),k=f.filter(A=>A.show!==!1);return h.jsxs("div",{className:`space-y-6 ${S} mb-4`,children:[h.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[h.jsxs("div",{className:"flex-1",children:[h.jsx("h1",{className:"text-2xl font-bold tracking-tight text-sidebar-foreground mb-2 dark:text-gray-200",children:t}),n&&h.jsx("p",{className:"text-sm text-sidebar-foreground/70 dark:text-gray-400",children:n})]}),c&&c.show!==!1&&h.jsx("div",{className:"flex-shrink-0",children:h.jsxs(ut,{onClick:c.onClick,variant:c.variant||"default",className:c.className,children:[c.icon&&h.jsx("span",{className:"mr-2",children:c.icon}),c.label]})})]}),h.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[h.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[s&&h.jsxs("div",{className:"relative flex-1 max-w-md",children:[h.jsx(UR,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-sidebar-foreground/60 dark:text-gray-200"}),h.jsx(Ra,{type:"search",placeholder:i,value:r,onChange:A=>s(A.target.value),className:"pl-9 bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50 focus:border-sidebar-border dark:text-gray-400 dark:placeholder:text-gray-400"})]}),y&&p&&h.jsxs(ut,{variant:"outline",size:"sm",onClick:p,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent whitespace-nowrap dark:text-gray-400 dark:hover:bg-sidebar-accent",children:[h.jsx(pR,{className:"h-4 w-4 mr-2"}),"Filtros",g.length>0&&h.jsx(pu,{variant:"secondary",className:"ml-2 h-5 px-1.5 text-xs bg-sidebar-accent",children:g.length})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[R.map((A,D)=>h.jsxs(ut,{variant:A.variant||"outline",size:"sm",onClick:A.onClick,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:[A.icon&&h.jsx("span",{className:"mr-2",children:A.icon}),A.label]},D)),k.length>0&&h.jsxs(p3,{children:[h.jsx(g3,{asChild:!0,children:h.jsx(ut,{variant:"outline",size:"sm",className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:h.jsx(cR,{className:"h-4 w-4"})})}),h.jsx(v3,{align:"end",className:"bg-sidebar border-sidebar-border text-sidebar-foreground dark:text-gray-400",children:k.map((A,D)=>h.jsxs(y3,{onClick:A.onClick,className:`hover:bg-sidebar-accent ${A.variant==="destructive"?"text-red-400":""} dark:text-gray-400`,children:[A.icon&&h.jsx("span",{className:"mr-2",children:A.icon}),A.label]},D))})]})]})]}),E&&h.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-sidebar-accent/50 border border-sidebar-border px-4 py-2",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsxs("span",{className:"text-sm font-medium text-sidebar-foreground dark:text-gray-400",children:[v," selecionado",v>1?"s":""]}),w&&h.jsxs(ut,{variant:"ghost",size:"sm",onClick:w,className:"h-7 px-2 text-sidebar-foreground/70 hover:text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:text-gray-400 dark:hover:bg-sidebar-accent",children:[h.jsx(el,{className:"h-3 w-3 mr-1"}),"Limpar"]})]}),C.length>0&&h.jsx("div",{className:"flex items-center gap-2",children:C.map((A,D)=>h.jsxs(ut,{variant:A.variant||"outline",size:"sm",onClick:A.onClick,className:"h-7 bg-sidebar-accent border-sidebar-border text-sidebar-foreground hover:bg-sidebar dark:text-gray-400 dark:hover:bg-sidebar",children:[A.icon&&h.jsx("span",{className:"mr-1.5",children:A.icon}),A.label]},D))})]}),g.length>0&&h.jsx("div",{className:"flex flex-wrap gap-2",children:g.map((A,D)=>h.jsxs(pu,{variant:"secondary",className:"pl-2 pr-1 py-1 bg-sidebar-accent text-sidebar-foreground hover:bg-sidebar dark:text-gray-400 dark:hover:bg-sidebar dark:bg-sidebar-accent/50",children:[A.label,": ",A.value,h.jsx(ut,{variant:"ghost",size:"sm",onClick:A.onRemove,className:"ml-1 h-4 w-4 p-0 hover:bg-transparent text-sidebar-foreground/60 hover:text-sidebar-foreground dark:text-gray-400 dark:hover:text-gray-400",children:h.jsx(el,{className:"h-3 w-3"})})]},D))}),_]})}function g5({totalCount:t,selectedCount:n,searchValue:r,onSearchChange:s,onNewInstance:i,onClearSelection:c}){const u={label:"Nova Instância",icon:h.jsx(Xm,{className:"h-4 w-4"}),onClick:i};return h.jsx(p5,{title:"Instâncias",subtitle:"Gerencie suas instâncias WhatsApp do Evolution GO",totalCount:t,selectedCount:n,searchValue:r,onSearchChange:s,searchPlaceholder:"Buscar instâncias...",primaryAction:u,onClearSelection:c,showFilters:!1,className:"mb-4"})}const un=[];for(let t=0;t<256;++t)un.push((t+256).toString(16).slice(1));function v5(t,n=0){return(un[t[n+0]]+un[t[n+1]]+un[t[n+2]]+un[t[n+3]]+"-"+un[t[n+4]]+un[t[n+5]]+"-"+un[t[n+6]]+un[t[n+7]]+"-"+un[t[n+8]]+un[t[n+9]]+"-"+un[t[n+10]]+un[t[n+11]]+un[t[n+12]]+un[t[n+13]]+un[t[n+14]]+un[t[n+15]]).toLowerCase()}let qm;const y5=new Uint8Array(16);function b5(){if(!qm){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qm=crypto.getRandomValues.bind(crypto)}return qm(y5)}const x5=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),g0={randomUUID:x5};function w5(t,n,r){var i;if(g0.randomUUID&&!t)return g0.randomUUID();t=t||{};const s=t.random??((i=t.rng)==null?void 0:i.call(t))??b5();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,v5(s)}const S5=Xo({instanceName:Yt().min(1,"Nome da instância é obrigatório").min(3,"Nome deve ter pelo menos 3 caracteres").max(50,"Nome deve ter no máximo 50 caracteres").regex(/^[a-zA-Z0-9-_]+$/,"Nome deve conter apenas letras, números, hífen e underscore"),token:Yt().optional(),proxyHost:Yt().optional(),proxyPort:Yt().optional(),proxyUsername:Yt().optional(),proxyPassword:Yt().optional()});function E5({open:t,onOpenChange:n}){const[r,s]=b.useState(!1),[i,c]=b.useState(!1),{addInstance:u,fetchInstances:f}=dE(),{register:g,handleSubmit:p,reset:y,formState:{errors:v}}=Lo({resolver:Io(S5),defaultValues:{instanceName:"",token:"",proxyHost:"",proxyPort:"",proxyUsername:"",proxyPassword:""}}),w=async S=>{s(!0);try{const _={name:S.instanceName,token:S.token||w5()};S.proxyHost&&S.proxyPort&&(_.proxy={host:S.proxyHost,port:S.proxyPort,username:S.proxyUsername,password:S.proxyPassword});const E=await u5(_);u(E),Ze.success("Instância criada com sucesso!",{description:`A instância "${S.instanceName}" foi criada.`}),await f(),n(!1),y()}catch(_){console.error("Erro ao criar instância:",_),Ze.error(_ instanceof Error?_.message:"Erro ao criar instância. Tente novamente.")}finally{s(!1)}},C=()=>{r||(n(!1),y(),c(!1))};return h.jsx(gu,{open:t,onOpenChange:C,children:h.jsxs(vu,{className:"sm:max-w-md",children:[h.jsxs(yu,{children:[h.jsxs(bu,{className:"flex items-center gap-2",children:[h.jsx(Xm,{className:"h-5 w-5 text-primary"}),"Nova Instância"]}),h.jsx(xu,{className:"text-sidebar-foreground/70",children:"Crie uma nova instância WhatsApp para gerenciar suas conversas"})]}),h.jsxs("form",{onSubmit:p(w),className:"space-y-4",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsxs(Pr,{htmlFor:"instanceName",children:["Nome da Instância ",h.jsx("span",{className:"text-red-500",children:"*"})]}),h.jsx(Ra,{id:"instanceName",type:"text",placeholder:"ex: minha-instancia",disabled:r,...g("instanceName"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.instanceName&&h.jsx("p",{className:"text-destructive text-sm",children:v.instanceName.message}),h.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Use apenas letras, números, hífen (-) e underscore (_)"})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"token",children:"Token (Opcional)"}),h.jsx(Ra,{id:"token",type:"text",placeholder:"Token personalizado (UUID)",disabled:r,...g("token"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.token&&h.jsx("p",{className:"text-destructive text-sm",children:v.token.message}),h.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Se não informado, será gerado um UUID automaticamente"})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsxs(ut,{type:"button",variant:"outline",onClick:()=>c(!i),disabled:r,className:"w-full justify-between bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:[h.jsx("span",{children:"Configuração de Proxy (Opcional)"}),i?h.jsx(eR,{className:"h-4 w-4"}):h.jsx(Zm,{className:"h-4 w-4"})]}),i&&h.jsxs("div",{className:"space-y-4 pt-2 border-t border-sidebar-border",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"proxyHost",children:"Host do Proxy"}),h.jsx(Ra,{id:"proxyHost",type:"text",placeholder:"ex: proxy.example.com",disabled:r,...g("proxyHost"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.proxyHost&&h.jsx("p",{className:"text-destructive text-sm",children:v.proxyHost.message})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"proxyPort",children:"Porta do Proxy"}),h.jsx(Ra,{id:"proxyPort",type:"text",placeholder:"ex: 8080",disabled:r,...g("proxyPort"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.proxyPort&&h.jsx("p",{className:"text-destructive text-sm",children:v.proxyPort.message})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"proxyUsername",children:"Usuário (Opcional)"}),h.jsx(Ra,{id:"proxyUsername",type:"text",placeholder:"Usuário do proxy",disabled:r,...g("proxyUsername"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.proxyUsername&&h.jsx("p",{className:"text-destructive text-sm",children:v.proxyUsername.message})]}),h.jsxs("div",{className:"space-y-2",children:[h.jsx(Pr,{htmlFor:"proxyPassword",children:"Senha (Opcional)"}),h.jsx(Ra,{id:"proxyPassword",type:"password",placeholder:"Senha do proxy",disabled:r,...g("proxyPassword"),className:"bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50"}),v.proxyPassword&&h.jsx("p",{className:"text-destructive text-sm",children:v.proxyPassword.message})]})]})]}),h.jsxs(QS,{className:"flex gap-2 sm:gap-0",children:[h.jsx(ut,{type:"button",variant:"outline",onClick:C,disabled:r,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:"Cancelar"}),h.jsx(ut,{type:"submit",disabled:r,children:r?h.jsxs(h.Fragment,{children:[h.jsx(H0,{className:"mr-2 h-4 w-4 animate-spin"}),"Criando..."]}):h.jsxs(h.Fragment,{children:[h.jsx(Xm,{className:"mr-2 h-4 w-4"}),"Criar Instância"]})})]})]})]})})}function _5({instance:t,open:n,onOpenChange:r,onRefresh:s}){var f,g;const[i,c]=b.useState(!1);b.useEffect(()=>{if(!n||!t||t.connected)return;const p=setInterval(()=>{s&&(console.log("Auto-refreshing QR Code and checking connection..."),s().catch(y=>{console.error("Auto-refresh failed:",y)}))},1e4);return()=>clearInterval(p)},[n,t,s]);const u=async()=>{if(s){c(!0);try{await s(),Ze.success("QR Code atualizado!")}catch(p){console.error("Erro ao atualizar QR Code:",p),Ze.error("Erro ao atualizar QR Code")}finally{c(!1)}}};return t?t.connected?h.jsx(gu,{open:n,onOpenChange:r,children:h.jsxs(vu,{className:"sm:max-w-md",children:[h.jsxs(yu,{children:[h.jsxs(bu,{className:"flex items-center gap-2 text-green-500",children:[h.jsx(kb,{className:"h-5 w-5"}),"Conectado com Sucesso!"]}),h.jsxs(xu,{className:"text-sidebar-foreground/70",children:["A instância ",t.instanceName," foi conectada ao WhatsApp."]})]}),h.jsxs("div",{className:"flex flex-col items-center gap-4 py-6",children:[h.jsx("div",{className:"rounded-full bg-green-500/10 p-4",children:h.jsx(kb,{className:"h-12 w-12 text-green-500"})}),t.profileName&&h.jsxs("div",{className:"text-center",children:[h.jsx("p",{className:"text-sm text-sidebar-foreground/60",children:"Conectado como"}),h.jsx("p",{className:"text-lg font-semibold text-sidebar-foreground",children:t.profileName})]})]}),h.jsx("div",{className:"flex justify-end",children:h.jsx(ut,{onClick:()=>r(!1),className:"w-full sm:w-auto",children:"Fechar"})})]})}):h.jsx(gu,{open:n,onOpenChange:r,children:h.jsxs(vu,{className:"sm:max-w-md",children:[h.jsxs(yu,{children:[h.jsxs(bu,{className:"flex items-center gap-2",children:[h.jsx(Mb,{className:"h-5 w-5 text-primary"}),"Conectar WhatsApp"]}),h.jsxs(xu,{className:"text-sidebar-foreground/70",children:["Escaneie o QR Code abaixo com seu WhatsApp para conectar a instância"," ",h.jsx("strong",{children:t.instanceName})]})]}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"flex flex-col items-center gap-4",children:[(f=t.qrcode)!=null&&f.base64?h.jsx("div",{className:"rounded-lg border-2 border-sidebar-border bg-white p-4",children:h.jsx("img",{src:t.qrcode.base64,alt:"QR Code",className:"h-64 w-64"})}):h.jsx("div",{className:"flex h-64 w-64 items-center justify-center rounded-lg border-2 border-dashed border-sidebar-border bg-sidebar",children:h.jsxs("div",{className:"text-center",children:[h.jsx(Mb,{className:"mx-auto h-12 w-12 text-sidebar-foreground/40"}),h.jsx("p",{className:"mt-2 text-sm text-sidebar-foreground/60",children:"Aguardando QR Code..."})]})}),((g=t.qrcode)==null?void 0:g.pairingCode)&&h.jsxs("div",{className:"w-full rounded-lg bg-sidebar-accent p-3 text-center",children:[h.jsx("p",{className:"text-xs text-sidebar-foreground/60",children:"Código de Pareamento"}),h.jsx("p",{className:"mt-1 font-mono text-lg font-semibold text-sidebar-foreground",children:t.qrcode.pairingCode})]})]}),h.jsxs("div",{className:"rounded-lg bg-sidebar-accent p-4",children:[h.jsx("p",{className:"text-sm font-medium text-sidebar-foreground",children:"Como conectar:"}),h.jsxs("ol",{className:"mt-2 space-y-1 text-sm text-sidebar-foreground/70",children:[h.jsx("li",{children:"1. Abra o WhatsApp no seu celular"}),h.jsx("li",{children:"2. Toque em Menu ou Configurações"}),h.jsx("li",{children:"3. Toque em Dispositivos conectados"}),h.jsx("li",{children:"4. Toque em Conectar um dispositivo"}),h.jsx("li",{children:"5. Aponte seu celular para esta tela para capturar o código"})]})]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx(ut,{variant:"outline",onClick:u,disabled:i,className:"flex-1 bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:i?h.jsxs(h.Fragment,{children:[h.jsx(Db,{className:"mr-2 h-4 w-4 animate-spin"}),"Atualizando..."]}):h.jsxs(h.Fragment,{children:[h.jsx(Db,{className:"mr-2 h-4 w-4"}),"Atualizar QR Code"]})}),h.jsx(ut,{variant:"outline",onClick:()=>r(!1),className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent",children:h.jsx(el,{className:"h-4 w-4"})})]})]})]})}):null}const C5=Xo({webhookUrl:Yt().optional(),phone:Yt().optional(),rabbitmqEnable:Yt().optional(),websocketEnable:Yt().optional(),natsEnable:Yt().optional(),alwaysOnline:Ta().optional(),rejectCall:Ta().optional(),readMessages:Ta().optional(),ignoreGroups:Ta().optional(),ignoreStatus:Ta().optional()}),N5=["ALL","MESSAGE","READ_RECEIPT","PRESENCE","HISTORY_SYNC","CHAT_PRESENCE","CALL","CONNECTION","QRCODE","LABEL","CONTACT","GROUP","NEWSLETTER"];function R5({open:t,onClose:n,instance:r,onConfirm:s}){const[i,c]=b.useState([]),[u,f]=b.useState(!1),[g,p]=b.useState(!1),{register:y,handleSubmit:v,formState:{errors:w},reset:C}=Lo({resolver:Io(C5)}),S=async A=>{const D={webhookUrl:A.webhookUrl||"",subscribe:i,phone:A.phone||"",rabbitmqEnable:A.rabbitmqEnable||"",websocketEnable:A.websocketEnable||"",natsEnable:A.natsEnable||"",alwaysOnline:A.alwaysOnline,rejectCall:A.rejectCall,readMessages:A.readMessages,ignoreGroups:A.ignoreGroups,ignoreStatus:A.ignoreStatus};s(D),_()},_=()=>{C(),c([]),f(!1),p(!1),n()},E=A=>{c(D=>A==="ALL"?D.includes("ALL")?[]:["ALL"]:D.includes("ALL")?[A]:D.includes(A)?D.filter(H=>H!==A):[...D,A])},R=()=>{c(["ALL"])},k=()=>{c([])};return!t||!r?null:h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:h.jsxs("div",{className:"w-full max-w-2xl rounded-lg bg-card p-6 shadow-lg max-h-[90vh] overflow-y-auto",children:[h.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[h.jsxs("h2",{className:"text-xl font-semibold text-foreground",children:["Configurar Conexão - ",r.instanceName]}),h.jsx("button",{onClick:_,className:"rounded-md p-1 hover:bg-accent",children:h.jsx(el,{className:"h-5 w-5"})})]}),h.jsxs("form",{onSubmit:v(S),className:"space-y-4",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"webhookUrl",className:"mb-1 block text-sm font-medium text-foreground",children:"Webhook URL (opcional)"}),h.jsx("input",{id:"webhookUrl",type:"url",placeholder:"https://seu-servidor.com/webhook",...y("webhookUrl"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),w.webhookUrl&&h.jsx("p",{className:"mt-1 text-sm text-destructive",children:w.webhookUrl.message})]}),h.jsxs("div",{children:[h.jsxs("button",{type:"button",onClick:()=>p(!g),className:"flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary",children:[g?h.jsx(Zm,{className:"h-4 w-4"}):h.jsx(jb,{className:"h-4 w-4"}),"Eventos para Webhook (",i.length," selecionados)"]}),g&&h.jsxs("div",{className:"mt-2 space-y-2 rounded-md border border-input p-3",children:[h.jsxs("div",{className:"flex gap-2 mb-2",children:[h.jsx("button",{type:"button",onClick:R,className:"text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90",children:"Selecionar ALL"}),h.jsx("button",{type:"button",onClick:k,className:"text-xs px-2 py-1 rounded border border-input hover:bg-accent",children:"Limpar"})]}),h.jsx("div",{className:"mb-3 p-3 rounded-md bg-primary/10 border border-primary/20",children:h.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:i.includes("ALL"),onChange:()=>E("ALL"),className:"rounded border-input w-4 h-4"}),h.jsxs("div",{className:"flex-1",children:[h.jsx("span",{className:"text-sm font-semibold text-primary",children:"ALL"}),h.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Seleciona todos os eventos (recomendado)"})]})]})}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Eventos Individuais:"}),h.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-48 overflow-y-auto",children:N5.filter(A=>A!=="ALL").map(A=>h.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer hover:bg-accent p-2 rounded",children:[h.jsx("input",{type:"checkbox",checked:i.includes(A)||i.includes("ALL"),onChange:()=>E(A),disabled:i.includes("ALL"),className:"rounded border-input"}),h.jsx("span",{className:i.includes("ALL")?"text-muted-foreground":"text-foreground",children:A})]},A))})]})]})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"phone",className:"mb-1 block text-sm font-medium text-foreground",children:"Telefone para Pairing Code (opcional)"}),h.jsx("input",{id:"phone",type:"tel",placeholder:"5511999999999",...y("phone"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),h.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Se fornecido, será gerado um código de pareamento (pairing code)"})]}),h.jsxs("div",{children:[h.jsxs("button",{type:"button",onClick:()=>f(!u),className:"flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary",children:[u?h.jsx(Zm,{className:"h-4 w-4"}):h.jsx(jb,{className:"h-4 w-4"}),"Configurações Avançadas"]}),u&&h.jsxs("div",{className:"mt-2 space-y-4 rounded-md border border-input p-4",children:[h.jsxs("div",{className:"space-y-3",children:[h.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Comportamento"}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"alwaysOnline",className:"text-sm font-medium text-foreground cursor-pointer",children:"Always Online"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Manter sempre online no WhatsApp"})]}),h.jsx("input",{id:"alwaysOnline",type:"checkbox",...y("alwaysOnline"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"rejectCall",className:"text-sm font-medium text-foreground cursor-pointer",children:"Reject Call"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Rejeitar chamadas automaticamente"})]}),h.jsx("input",{id:"rejectCall",type:"checkbox",...y("rejectCall"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"readMessages",className:"text-sm font-medium text-foreground cursor-pointer",children:"Read Messages"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Marcar mensagens como lidas"})]}),h.jsx("input",{id:"readMessages",type:"checkbox",...y("readMessages"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"ignoreGroups",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Groups"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar mensagens de grupos"})]}),h.jsx("input",{id:"ignoreGroups",type:"checkbox",...y("ignoreGroups"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"ignoreStatus",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Status"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar atualizações de status"})]}),h.jsx("input",{id:"ignoreStatus",type:"checkbox",...y("ignoreStatus"),className:"rounded border-input w-4 h-4"})]})]}),h.jsxs("div",{className:"space-y-3 pt-3 border-t border-input",children:[h.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Produtores de Eventos"}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"rabbitmqEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"RabbitMQ"}),h.jsxs("select",{id:"rabbitmqEnable",...y("rabbitmqEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"websocketEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"WebSocket"}),h.jsxs("select",{id:"websocketEnable",...y("websocketEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"natsEnable",className:"mb-1 block text-sm font-medium text-foreground",children:"NATS"}),h.jsxs("select",{id:"natsEnable",...y("natsEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]})]})]})]}),h.jsxs("div",{className:"flex gap-2 pt-4",children:[h.jsx("button",{type:"button",onClick:_,className:"flex-1 rounded-md border border-input px-4 py-2 text-sm font-medium text-foreground hover:bg-accent",children:"Cancelar"}),h.jsx("button",{type:"submit",className:"flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90",children:"Conectar"})]})]})]})})}const A5=Xo({number:Yt().min(1,"Número é obrigatório"),message:Yt().min(1,"Mensagem é obrigatória")});function T5({open:t,onClose:n,instance:r}){const{register:s,handleSubmit:i,formState:{errors:c,isSubmitting:u},reset:f}=Lo({resolver:Io(A5)}),g=async y=>{if(!(r!=null&&r.apikey)){Ze.error("Token da instância não encontrado");return}try{await f5(r.apikey,{number:y.number,text:y.message}),Ze.success("Mensagem enviada com sucesso!"),f(),n()}catch(v){console.error("Send message error:",v),Ze.error("Erro ao enviar mensagem")}},p=()=>{f(),n()};return!t||!r?null:h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:h.jsxs("div",{className:"w-full max-w-md rounded-lg bg-card p-6 shadow-lg",children:[h.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[h.jsxs("h2",{className:"text-xl font-semibold text-foreground",children:["Enviar Mensagem - ",r.instanceName]}),h.jsx("button",{onClick:p,className:"rounded-md p-1 hover:bg-accent",children:h.jsx(el,{className:"h-5 w-5"})})]}),h.jsxs("form",{onSubmit:i(g),className:"space-y-4",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"number",className:"mb-1 block text-sm font-medium text-foreground",children:"Número (com DDI)"}),h.jsx("input",{id:"number",type:"text",placeholder:"5511999999999",...s("number"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),c.number&&h.jsx("p",{className:"mt-1 text-sm text-destructive",children:c.number.message})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"message",className:"mb-1 block text-sm font-medium text-foreground",children:"Mensagem"}),h.jsx("textarea",{id:"message",rows:4,placeholder:"Digite sua mensagem...",...s("message"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),c.message&&h.jsx("p",{className:"mt-1 text-sm text-destructive",children:c.message.message})]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{type:"button",onClick:p,disabled:u,className:"flex-1 rounded-md border border-input px-4 py-2 text-sm font-medium text-foreground hover:bg-accent disabled:opacity-50",children:"Cancelar"}),h.jsx("button",{type:"submit",disabled:u,className:"flex-1 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:u?"Enviando...":"Enviar"})]})]})]})})}function O5({icon:t,title:n,description:r,action:s,className:i}){return h.jsxs("div",{className:Qm("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[h.jsx("div",{className:"rounded-full bg-sidebar-accent/50 p-6 mb-4 dark:bg-sidebar-accent/50 dark:text-gray-400",children:h.jsx(t,{className:"h-12 w-12 text-sidebar-foreground/60 dark:text-gray-400"})}),h.jsx("h3",{className:"text-lg font-semibold text-sidebar-foreground mb-2 dark:text-gray-400",children:n}),h.jsx("p",{className:"text-sm text-sidebar-foreground/60 mb-6 max-w-md dark:text-gray-400",children:r}),s&&h.jsx(ut,{onClick:s.onClick,children:s.label})]})}function j5(){var L,Y,J,ie,pe;const t=Xr(),{instances:n,isLoading:r,fetchInstances:s,removeInstance:i}=dE(),[c,u]=b.useState(""),[f,g]=b.useState(!1),[p,y]=b.useState({isOpen:!1,instance:null}),[v]=b.useState(1),[w]=b.useState(24),[C,S]=b.useState(null),[_,E]=b.useState({isOpen:!1,instance:null,confirmationText:""}),[R,k]=b.useState({isOpen:!1,instance:null}),[A,D]=b.useState({isOpen:!1,instance:null}),H=b.useRef(!1);b.useEffect(()=>{H.current||(s(),H.current=!0);const Q=setInterval(()=>{s()},5e3);return()=>clearInterval(Q)},[s]);const{paginatedInstances:$,totalCount:U}=b.useMemo(()=>{const Q=c?n.filter(Me=>{var be,je,at;const ze=c.toLowerCase();return((be=Me.instanceName)==null?void 0:be.toLowerCase().includes(ze))||((je=Me.profileName)==null?void 0:je.toLowerCase().includes(ze))||((at=Me.owner)==null?void 0:at.toLowerCase().includes(ze))}):n,oe=(v-1)*w,Re=oe+w;return{paginatedInstances:Q.slice(oe,Re),totalCount:Q.length}},[n,c,v,w]),F=b.useCallback(()=>{g(!0)},[]),de=b.useCallback(Q=>{t(`/manager/instances/${Q.id}/settings`)},[t]),fe=b.useCallback(Q=>{D({isOpen:!0,instance:Q})},[]),me=b.useCallback(async(Q,oe)=>{try{if(!Q.apikey){Ze.error("Token da instância não encontrado");return}if(Ze.info(`Conectando ${Q.instanceName}...`),oe.alwaysOnline!==void 0||oe.rejectCall!==void 0||oe.readMessages!==void 0||oe.ignoreGroups!==void 0||oe.ignoreStatus!==void 0){const Me={alwaysOnline:oe.alwaysOnline,rejectCall:oe.rejectCall,readMessages:oe.readMessages,ignoreGroups:oe.ignoreGroups,ignoreStatus:oe.ignoreStatus};await lE(Q.id,Q.apikey,Me)}if(oe.phone&&oe.phone.trim()!==""){let Me=oe.phone.trim();Me.startsWith("+")||(Me=`+${Me}`),await xh(Q.apikey,{...oe,phone:void 0}),await new Promise(be=>setTimeout(be,1e3));const ze=await d5(Q.apikey,{subscribe:oe.subscribe||[],phone:Me});try{const be=await Im(Q.apikey),je={...Q,qrcode:{base64:be.qrcode,code:be.code,pairingCode:ze.pairingCode}};y({isOpen:!0,instance:je}),Ze.success(`QR Code e Pairing Code gerados para ${Q.instanceName}!`)}catch{const be={...Q,qrcode:{pairingCode:ze.pairingCode}};y({isOpen:!0,instance:be}),Ze.success(`Pairing Code gerado para ${Q.instanceName}!`)}}else{await xh(Q.apikey,oe),await new Promise(Me=>setTimeout(Me,2e3));try{const Me=await Im(Q.apikey),ze={...Q,qrcode:{base64:Me.qrcode,code:Me.code}};y({isOpen:!0,instance:ze}),Ze.success(`QR Code gerado para ${Q.instanceName}!`)}catch(Me){console.error("Erro ao buscar QR Code:",Me),Ze.error("QR Code ainda não disponível, aguarde alguns segundos..."),await s();const ze=n.find(be=>be.instanceName===Q.instanceName);ze&&y({isOpen:!0,instance:ze})}}}catch(Re){console.error("Erro ao conectar instância:",Re),Ze.error(Re instanceof Error?Re.message:"Erro ao conectar instância")}},[s,n]),se=b.useCallback(async Q=>{try{if(!Q.apikey){Ze.error("Token da instância não encontrado");return}Ze.info(`Desconectando ${Q.instanceName}...`),await cE(Q.apikey),await s(),Ze.success(`${Q.instanceName} desconectada!`)}catch(oe){console.error("Erro ao desconectar instância:",oe),Ze.error(oe instanceof Error?oe.message:"Erro ao desconectar instância")}},[s]),G=Q=>{E({isOpen:!0,instance:Q,confirmationText:""})},he=()=>{E({isOpen:!1,instance:null,confirmationText:""})},ve=()=>{y({isOpen:!1,instance:null})},T=Q=>{k({isOpen:!0,instance:Q})},K=()=>{k({isOpen:!1,instance:null})},te=()=>{D({isOpen:!1,instance:null})},le=b.useCallback(Q=>{A.instance&&me(A.instance,Q)},[A.instance,me]),ne=b.useCallback(async()=>{if(!(!p.instance||!p.instance.apikey))try{await s();const Q=n.find(oe=>{var Re;return oe.id===((Re=p.instance)==null?void 0:Re.id)});if(!Q)return;if(Q.connected){y({isOpen:!0,instance:Q});return}try{const oe=await Im(p.instance.apikey),Re={...Q,qrcode:{base64:oe.qrcode,code:oe.code}};y({isOpen:!0,instance:Re})}catch{y({isOpen:!0,instance:Q})}}catch(Q){throw console.error("Erro ao atualizar QR Code:",Q),Q}},[p.instance,s,n]),j=async()=>{if(!_.instance)return;const Q=_.instance.instanceName,oe=_.instance.id;S(Q);try{await uE(oe),i(Q),Ze.success(`Instância ${Q} removida com sucesso!`),he()}catch(Re){console.error("Erro ao remover instância:",Re),Ze.error((Re==null?void 0:Re.message)||"Erro ao remover instância"),await s()}finally{S(null)}},X=_.confirmationText===((L=_.instance)==null?void 0:L.instanceName);return h.jsxs("div",{className:"h-full flex flex-col p-4",children:[h.jsx(g5,{totalCount:U,selectedCount:0,searchValue:c,onSearchChange:u,onNewInstance:F,onClearSelection:()=>{}}),h.jsx("div",{className:"flex-1 overflow-auto",children:r?h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Q,oe)=>h.jsx(x3,{className:"h-48"},oe))}):U===0?h.jsx(O5,{icon:bR,title:"Nenhuma instância encontrada",description:"Crie sua primeira instância para começar a usar o Evolution GO",action:{label:"Nova Instância",onClick:F},className:"h-full"}):h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:$.map(Q=>h.jsx(h5,{instance:Q,isDeleting:C,onSettings:de,onDelete:G,onConnect:fe,onDisconnect:se,onSendMessage:T},Q.instanceName))})}),h.jsx(E5,{open:f,onOpenChange:g}),h.jsx(_5,{instance:p.instance,open:p.isOpen,onOpenChange:ve,onRefresh:ne}),h.jsx(R5,{instance:A.instance,open:A.isOpen,onClose:te,onConfirm:le}),h.jsx(T5,{instance:R.instance,open:R.isOpen,onClose:K}),h.jsx(gu,{open:_.isOpen,onOpenChange:he,children:h.jsxs(vu,{className:"sm:max-w-md",children:[h.jsxs(yu,{children:[h.jsxs(bu,{className:"flex items-center gap-2 text-red-400 dark:text-red-500",children:[h.jsx(Th,{className:"h-5 w-5"}),"Remover Instância"]}),h.jsxs(xu,{className:"text-sidebar-foreground/70 dark:text-gray-400",children:["Você está prestes a remover a instância"," ",h.jsx("strong",{children:(Y=_.instance)==null?void 0:Y.instanceName}),". Esta ação não pode ser desfeita."]})]}),h.jsx("div",{className:"space-y-4",children:h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-sidebar-foreground dark:text-gray-400",children:"Digite o nome da instância para confirmar:"}),h.jsx(Ra,{placeholder:((J=_.instance)==null?void 0:J.instanceName)||"",value:_.confirmationText,onChange:Q=>E(oe=>({...oe,confirmationText:Q.target.value})),className:"mt-2 bg-sidebar border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50 dark:text-gray-400 dark:placeholder:text-gray-400"})]})}),h.jsxs(QS,{className:"flex gap-2",children:[h.jsx(ut,{variant:"outline",onClick:he,className:"bg-sidebar border-sidebar-border text-sidebar-foreground hover:bg-sidebar-accent dark:text-gray-400 dark:hover:bg-sidebar-accent",children:"Cancelar"}),h.jsx(ut,{variant:"destructive",onClick:j,disabled:!X||C===((ie=_.instance)==null?void 0:ie.instanceName),className:"bg-red-600 hover:bg-red-700 text-white dark:bg-red-600 dark:hover:bg-red-700",children:C===((pe=_.instance)==null?void 0:pe.instanceName)?"Removendo...":"Remover Instância"})]})]})})]})}const k5=Xo({webhookUrl:Yt().url("URL inválida").optional().or(X3("")),subscribe:Z3(Yt()).optional(),rabbitmqEnable:Yt().optional(),websocketEnable:Yt().optional(),natsEnable:Yt().optional()}),M5=Xo({alwaysOnline:Ta().optional(),rejectCall:Ta().optional(),readMessages:Ta().optional(),ignoreGroups:Ta().optional(),ignoreStatus:Ta().optional()}),D5=["ALL","MESSAGE","READ_RECEIPT","PRESENCE","HISTORY_SYNC","CHAT_PRESENCE","CALL","CONNECTION","QRCODE","LABEL","CONTACT","GROUP","NEWSLETTER"];function z5(){const{instanceId:t}=bN(),n=Xr(),[r,s]=b.useState(null),[i,c]=b.useState([]),[u,f]=b.useState(!1),[g,p]=b.useState(!0),[y,v]=b.useState(!1),w=b.useRef(!1),C=b.useRef(!1),{register:S,handleSubmit:_,formState:{errors:E},reset:R}=Lo({resolver:Io(k5)}),{register:k,handleSubmit:A,reset:D}=Lo({resolver:Io(M5)});b.useEffect(()=>{(async()=>{if(!(!t||C.current)){C.current=!0;try{p(!0);const me=await $c(t);s(me)}catch(me){console.error("Erro ao buscar instância:",me),Ze.error("Erro ao carregar dados da instância")}finally{p(!1)}}})()},[t]),b.useEffect(()=>{if(!(!r||w.current)){if(R({webhookUrl:r.webhook||"",rabbitmqEnable:r.rabbitmqEnable||"",websocketEnable:r.websocketEnable||"",natsEnable:r.natsEnable||""}),D({alwaysOnline:r.alwaysOnline||!1,rejectCall:r.rejectCall||!1,readMessages:r.readMessages||!1,ignoreGroups:r.ignoreGroups||!1,ignoreStatus:r.ignoreStatus||!1}),r.events){const fe=r.events.split(",").map(me=>me.trim()).filter(Boolean);c(fe)}else c([]);w.current=!0}},[r,R,D]);const H=fe=>{c(me=>fe==="ALL"?me.includes("ALL")?[]:["ALL"]:me.includes("ALL")?[fe]:me.includes(fe)?me.filter(se=>se!==fe):[...me,fe])},$=async fe=>{if(!(r!=null&&r.apikey)||!t){Ze.error("Token da instância não encontrado");return}try{f(!0);const me={webhookUrl:fe.webhookUrl||"",subscribe:i,rabbitmqEnable:fe.rabbitmqEnable||"",websocketEnable:fe.websocketEnable||"",natsEnable:fe.natsEnable||""};await xh(r.apikey,me),Ze.success("Configurações de webhook atualizadas!");const se=await $c(t);s(se)}catch(me){console.error("Erro ao atualizar webhook:",me),Ze.error(me instanceof Error?me.message:"Erro ao atualizar webhook")}finally{f(!1)}},U=async fe=>{if(!(r!=null&&r.apikey)||!(r!=null&&r.id)||!t){Ze.error("Token da instância não encontrado");return}try{f(!0),await lE(r.id,r.apikey,fe),Ze.success("Configurações avançadas atualizadas!");const me=await $c(t);s(me)}catch(me){console.error("Erro ao atualizar configurações:",me),Ze.error(me instanceof Error?me.message:"Erro ao atualizar configurações")}finally{f(!1)}},F=async()=>{if(!(r!=null&&r.apikey)||!t){Ze.error("Token da instância não encontrado");return}try{Ze.info(`Desconectando ${r.instanceName}...`),await cE(r.apikey);const fe=await $c(t);s(fe),Ze.success(`${r.instanceName} desconectada!`)}catch(fe){console.error("Erro ao desconectar instância:",fe),Ze.error(fe instanceof Error?fe.message:"Erro ao desconectar instância")}},de=async()=>{if(!(r!=null&&r.id)){Ze.error("ID da instância não encontrado");return}if(window.confirm(`Tem certeza que deseja deletar a instância ${r.instanceName}? Esta ação não pode ser desfeita.`))try{Ze.info(`Deletando ${r.instanceName}...`),await uE(r.id),Ze.success(`${r.instanceName} deletada!`),n("/manager/instances")}catch(me){console.error("Erro ao deletar instância:",me),Ze.error(me instanceof Error?me.message:"Erro ao deletar instância")}};return g?h.jsx("div",{className:"flex h-full items-center justify-center",children:h.jsx("div",{className:"text-center",children:h.jsx("p",{className:"text-muted-foreground",children:"Carregando..."})})}):r?h.jsxs("div",{className:"h-full flex flex-col",children:[h.jsx("div",{className:"border-b border-sidebar-border bg-sidebar p-6",children:h.jsx("div",{className:"flex items-center justify-between",children:h.jsxs("div",{className:"flex items-center gap-4",children:[h.jsx(ut,{variant:"ghost",size:"icon",onClick:()=>n("/manager/instances"),className:"text-sidebar-foreground hover:bg-sidebar-accent",children:h.jsx(Ob,{className:"h-5 w-5"})}),h.jsxs("div",{children:[h.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Configurações"}),h.jsx("p",{className:"text-sm text-muted-foreground",children:r.instanceName})]})]})})}),h.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:h.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[h.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[h.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Informações da Instância"}),h.jsx("div",{className:"space-y-4",children:h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-foreground",children:"Nome da Instância"}),h.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.instanceName})]}),h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-foreground",children:"Token da Instância"}),h.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[h.jsx("p",{className:"text-sm text-muted-foreground font-mono",children:y?r.apikey||"":"•".repeat((r.apikey||"").length)}),h.jsx("button",{type:"button",onClick:()=>v(!y),className:"text-muted-foreground hover:text-foreground transition-colors",title:y?"Ocultar token":"Mostrar token",children:y?h.jsx(dR,{size:18}):h.jsx(mR,{size:18})})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-foreground",children:"Status"}),h.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.status==="open"?"Conectado":"Desconectado"})]}),r.owner&&h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-foreground",children:"Número"}),h.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.owner})]}),r.profileName&&h.jsxs("div",{children:[h.jsx("label",{className:"text-sm font-medium text-foreground",children:"Nome do Perfil"}),h.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.profileName})]})]})})]}),h.jsx("form",{onSubmit:_($),children:h.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[h.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Configurações de Webhook"}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"webhookUrl",className:"block text-sm font-medium text-foreground mb-1",children:"URL do Webhook"}),h.jsx("input",{id:"webhookUrl",type:"url",placeholder:"https://seu-servidor.com/webhook",...S("webhookUrl"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),E.webhookUrl&&h.jsx("p",{className:"mt-1 text-sm text-destructive",children:E.webhookUrl.message}),h.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"URL que receberá os eventos do WhatsApp"})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Eventos para Webhook"}),h.jsxs("div",{className:"space-y-2 rounded-md border border-input p-3 max-h-60 overflow-y-auto",children:[h.jsx("div",{className:"p-2 rounded-md bg-primary/10 border border-primary/20",children:h.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[h.jsx("input",{type:"checkbox",checked:i.includes("ALL"),onChange:()=>H("ALL"),className:"rounded border-input w-4 h-4"}),h.jsx("span",{className:"text-sm font-semibold text-primary",children:"ALL"})]})}),h.jsx("div",{className:"grid grid-cols-2 gap-2",children:D5.filter(fe=>fe!=="ALL").map(fe=>h.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer hover:bg-accent p-2 rounded",children:[h.jsx("input",{type:"checkbox",checked:i.includes(fe)||i.includes("ALL"),onChange:()=>H(fe),disabled:i.includes("ALL"),className:"rounded border-input"}),h.jsx("span",{className:i.includes("ALL")?"text-muted-foreground":"text-foreground",children:fe})]},fe))})]})]}),h.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"rabbitmqEnable",className:"block text-sm font-medium text-foreground mb-1",children:"RabbitMQ"}),h.jsxs("select",{id:"rabbitmqEnable",...S("rabbitmqEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"websocketEnable",className:"block text-sm font-medium text-foreground mb-1",children:"WebSocket"}),h.jsxs("select",{id:"websocketEnable",...S("websocketEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]}),h.jsxs("div",{children:[h.jsx("label",{htmlFor:"natsEnable",className:"block text-sm font-medium text-foreground mb-1",children:"NATS"}),h.jsxs("select",{id:"natsEnable",...S("natsEnable"),className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[h.jsx("option",{value:"",children:"Padrão"}),h.jsx("option",{value:"enabled",children:"Habilitado"}),h.jsx("option",{value:"disabled",children:"Desabilitado"})]})]})]}),h.jsx("div",{className:"flex justify-end",children:h.jsxs(ut,{type:"submit",disabled:u,className:"gap-2",children:[h.jsx(zb,{className:"h-4 w-4"}),u?"Salvando...":"Salvar Webhook"]})})]})]})}),h.jsx("form",{onSubmit:A(U),children:h.jsxs("div",{className:"rounded-lg border border-sidebar-border bg-card p-6",children:[h.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Configurações Avançadas"}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"alwaysOnline",className:"text-sm font-medium text-foreground cursor-pointer",children:"Always Online"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Manter sempre online no WhatsApp"})]}),h.jsx("input",{id:"alwaysOnline",type:"checkbox",...k("alwaysOnline"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"rejectCall",className:"text-sm font-medium text-foreground cursor-pointer",children:"Reject Call"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Rejeitar chamadas automaticamente"})]}),h.jsx("input",{id:"rejectCall",type:"checkbox",...k("rejectCall"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"readMessages",className:"text-sm font-medium text-foreground cursor-pointer",children:"Read Messages"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Marcar mensagens como lidas"})]}),h.jsx("input",{id:"readMessages",type:"checkbox",...k("readMessages"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"ignoreGroups",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Groups"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar mensagens de grupos"})]}),h.jsx("input",{id:"ignoreGroups",type:"checkbox",...k("ignoreGroups"),className:"rounded border-input w-4 h-4"})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("label",{htmlFor:"ignoreStatus",className:"text-sm font-medium text-foreground cursor-pointer",children:"Ignore Status"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Ignorar atualizações de status"})]}),h.jsx("input",{id:"ignoreStatus",type:"checkbox",...k("ignoreStatus"),className:"rounded border-input w-4 h-4"})]}),h.jsx("div",{className:"flex justify-end",children:h.jsxs(ut,{type:"submit",disabled:u,className:"gap-2",children:[h.jsx(zb,{className:"h-4 w-4"}),u?"Salvando...":"Salvar Avançadas"]})})]})]})}),h.jsxs("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-6",children:[h.jsx("h2",{className:"text-lg font-semibold text-destructive mb-4",children:"Zona de Perigo"}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Desconectar Instância"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Desconecta a instância do WhatsApp"})]}),h.jsxs(ut,{variant:"destructive",onClick:F,className:"gap-2",children:[h.jsx(V0,{className:"h-4 w-4"}),"Desconectar"]})]}),h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("div",{children:[h.jsx("h3",{className:"text-sm font-medium text-foreground",children:"Deletar Instância"}),h.jsx("p",{className:"text-xs text-muted-foreground",children:"Remove permanentemente esta instância"})]}),h.jsxs(ut,{variant:"destructive",onClick:de,className:"gap-2",children:[h.jsx(Th,{className:"h-4 w-4"}),"Deletar"]})]})]})]})]})})]}):h.jsx("div",{className:"flex h-full items-center justify-center",children:h.jsxs("div",{className:"text-center",children:[h.jsx("h2",{className:"text-xl font-semibold text-foreground mb-2",children:"Instância não encontrada"}),h.jsxs("p",{className:"text-muted-foreground mb-4",children:['A instância "',t,'" não foi encontrada.']}),h.jsxs(ut,{onClick:()=>n("/manager/instances"),children:[h.jsx(Ob,{className:"h-4 w-4 mr-2"}),"Voltar para Instâncias"]})]})})}function L5(){return h.jsxs("div",{className:"p-6",children:[h.jsx("h1",{className:"mb-4 text-2xl font-bold text-gray-900",children:"Mensagens"}),h.jsx("p",{className:"text-gray-600",children:"Messages sending will be implemented here..."})]})}function U5(){return h.jsxs("div",{className:"p-6",children:[h.jsx("h1",{className:"mb-4 text-2xl font-bold text-foreground",children:"Eventos"}),h.jsx("p",{className:"text-muted-foreground",children:"Events monitor will be implemented here..."})]})}function B5(){return h.jsxs("div",{className:"p-6",children:[h.jsx("h1",{className:"mb-4 text-2xl font-bold text-gray-900",children:"Configurações"}),h.jsx("p",{className:"text-gray-600",children:"Settings will be implemented here..."})]})}const P5=()=>{const[t]=u2(),n=Xr(),{setLicenseState:r,apiUrl:s,apiKey:i}=zu(),[c,u]=b.useState("activating"),[f,g]=b.useState(""),p=t.get("code"),y=b.useCallback(async()=>{if(!p){u("error"),g("Codigo de autorizacao nao encontrado na URL.");return}u("activating"),g("");try{const v=await OO(p,s,i);v.status==="active"?(u("success"),r("licensed"),Ze.success("Licenca ativada com sucesso!"),setTimeout(()=>{n("/manager/login",{replace:!0})},2e3)):(u("error"),g(v.message||"Falha ao ativar licenca."))}catch(v){u("error");const w=v instanceof Error?v.message:v==null?void 0:v.message;g(w||"Erro ao ativar licenca.")}},[p,s,i,n,r]);return b.useEffect(()=>{y()},[y]),h.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-gradient-to-t from-primary/20 via-background/95 to-background",children:h.jsxs("div",{className:"w-full max-w-md space-y-6",children:[h.jsx("div",{className:"text-center",children:h.jsx("h1",{className:"text-3xl font-bold text-primary",children:"Evolution GO"})}),h.jsxs("div",{className:"bg-background/80 backdrop-blur-sm border rounded-lg p-8 shadow-lg text-center space-y-4",children:[c==="activating"&&h.jsxs(h.Fragment,{children:[h.jsx(H0,{className:"h-12 w-12 animate-spin text-primary mx-auto"}),h.jsx("h2",{className:"text-xl font-semibold",children:"Ativando licenca..."}),h.jsx("p",{className:"text-muted-foreground",children:"Aguarde enquanto ativamos sua licenca."})]}),c==="success"&&h.jsxs(h.Fragment,{children:[h.jsx(rR,{className:"h-12 w-12 text-green-500 mx-auto"}),h.jsx("h2",{className:"text-xl font-semibold",children:"Licenca ativada!"}),h.jsx("p",{className:"text-muted-foreground",children:"Redirecionando para o login..."})]}),c==="error"&&h.jsxs(h.Fragment,{children:[h.jsx(iR,{className:"h-12 w-12 text-destructive mx-auto"}),h.jsx("h2",{className:"text-xl font-semibold",children:"Erro na ativacao"}),h.jsx("p",{className:"text-muted-foreground",children:f}),h.jsxs("div",{className:"flex gap-2 justify-center pt-2",children:[h.jsx(ut,{variant:"outline",onClick:()=>n("/manager/login",{replace:!0}),children:"Voltar ao login"}),h.jsx(ut,{onClick:y,children:"Tentar novamente"})]})]})]})]})})};function H5(){const{isAuthenticated:t,licenseState:n}=zu(),r=t&&n==="licensed";return h.jsx(kO,{children:h.jsxs(WR,{children:[h.jsx(o2,{children:h.jsxs(zN,{children:[h.jsx(Hn,{path:"/",element:h.jsx(w3,{})}),h.jsx(Hn,{path:"/manager/login",element:r?h.jsx(ym,{to:"/manager",replace:!0}):h.jsx(i5,{})}),h.jsx(Hn,{path:"/manager/license/callback",element:h.jsx(P5,{})}),r?h.jsxs(Hn,{path:"/manager",element:h.jsx(zO,{}),children:[h.jsx(Hn,{index:!0,element:h.jsx(l5,{})}),h.jsx(Hn,{path:"instances",element:h.jsx(j5,{})}),h.jsx(Hn,{path:"instances/:instanceId/settings",element:h.jsx(z5,{})}),h.jsx(Hn,{path:"messages",element:h.jsx(L5,{})}),h.jsx(Hn,{path:"events",element:h.jsx(U5,{})}),h.jsx(Hn,{path:"settings",element:h.jsx(B5,{})})]}):h.jsx(Hn,{path:"/manager/*",element:h.jsx(ym,{to:"/manager/login",replace:!0})}),h.jsx(Hn,{path:"*",element:h.jsx(ym,{to:"/",replace:!0})})]})}),h.jsx(I2,{position:"top-right",richColors:!0})]})})}DC.createRoot(document.getElementById("root")).render(h.jsx(b.StrictMode,{children:h.jsx(H5,{})}));diff --git a/manager/dist/index.html b/manager/dist/index.htmlnew file mode 100644index 0000000..127cf0c--- /dev/null+++ b/manager/dist/index.html@@ -0,0 +1,14 @@+<!doctype html>+<html lang="pt-BR">+ <head>+ <meta charset="UTF-8" />+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Evolution GO Manager</title>+ <script type="module" crossorigin src="/assets/index-CRnVAbpY.js"></script>+ <link rel="stylesheet" crossorigin href="/assets/index-BsMXpWP7.css">+ </head>+ <body>+ <div id="root"></div>+ </body>+</html>diff --git a/pkg/call/handler/call_handler.go b/pkg/call/handler/call_handler.gonew file mode 100644index 0000000..81ec10a--- /dev/null+++ b/pkg/call/handler/call_handler.go@@ -0,0 +1,60 @@+package call_handler++import (+ "net/http"++ call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ "github.com/gin-gonic/gin"+)++type CallHandler interface {+ RejectCall(ctx *gin.Context)+}++type callHandler struct {+ callService call_service.CallService+}++// Reject call+// @Summary Reject call+// @Description Reject call+// @Tags Call+// @Accept json+// @Produce json+// @Param message body call_service.RejectCallStruct true "Call data"+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /call/reject [post]+func (g *callHandler) RejectCall(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *call_service.RejectCallStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ err = g.callService.RejectCall(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++func NewCallHandler(+ callService call_service.CallService,+) CallHandler {+ return &callHandler{+ callService: callService,+ }+}diff --git a/pkg/call/service/call_service.go b/pkg/call/service/call_service.gonew file mode 100644index 0000000..38928db--- /dev/null+++ b/pkg/call/service/call_service.go@@ -0,0 +1,95 @@+package call_service++import (+ "context"+ "errors"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "github.com/gomessguii/logger"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+)++type CallService interface {+ RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error+}++type callService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type RejectCallStruct struct {+ CallCreator types.JID `json:"callCreator"`+ CallID string `json:"callId"`+}++func (c *callService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := c.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (c *callService) RejectCall(data *RejectCallStruct, instance *instance_model.Instance) error {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ err = client.RejectCall(context.Background(), data.CallCreator, data.CallID)+ if err != nil {+ logger.LogError("[%s] error reject call: %v", instance.Id, err)+ return err+ }++ return nil+}++func NewCallService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) CallService {+ return &callService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/chat/handler/chat_handler.go b/pkg/chat/handler/chat_handler.gonew file mode 100644index 0000000..8240bc7--- /dev/null+++ b/pkg/chat/handler/chat_handler.go@@ -0,0 +1,337 @@+package chat_handler++import (+ "net/http"++ chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ "github.com/gin-gonic/gin"+)++type ChatHandler interface {+ ChatPin(ctx *gin.Context)+ ChatUnpin(ctx *gin.Context)+ ChatArchive(ctx *gin.Context)+ ChatUnarchive(ctx *gin.Context)+ ChatMute(ctx *gin.Context)+ ChatUnmute(ctx *gin.Context)+ HistorySyncRequest(ctx *gin.Context)+}++type chatHandler struct {+ chatService chat_service.ChatService+}++// Pin a chat+// @Summary Pin a chat+// @Description Pin a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/pin [post]+func (c *chatHandler) ChatPin(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatPin(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Unpin a chat+// @Summary Unpin a chat+// @Description Unpin a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/unpin [post]+func (c *chatHandler) ChatUnpin(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatUnpin(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Archive a chat+// @Summary Archive a chat+// @Description Archive a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/archive [post]+func (c *chatHandler) ChatArchive(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatArchive(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Unarchive a chat+// @Summary Unarchive a chat+// @Description Unarchive a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/unarchive [post]+func (c *chatHandler) ChatUnarchive(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatUnarchive(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Mute a chat+// @Summary Mute a chat+// @Description Mute a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/mute [post]+func (c *chatHandler) ChatMute(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatMute(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Unmute a chat+// @Summary Unmute a chat+// @Description Unmute a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.BodyStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/unmute [post]+func (c *chatHandler) ChatUnmute(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.BodyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ ts, err := c.chatService.ChatUnmute(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// HistorySyncRequest a chat+// @Summary HistorySyncRequest a chat+// @Description HistorySyncRequest a chat+// @Tags Chat+// @Accept json+// @Produce json+// @Param message body chat_service.HistorySyncRequestStruct true "Chat"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /chat/history-sync-request [post]+func (c *chatHandler) HistorySyncRequest(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *chat_service.HistorySyncRequestStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ resp, err := c.chatService.HistorySyncRequest(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++func NewChatHandler(+ chatService chat_service.ChatService,+) ChatHandler {+ return &chatHandler{+ chatService: chatService,+ }+}diff --git a/pkg/chat/service/chat_service.go b/pkg/chat/service/chat_service.gonew file mode 100644index 0000000..0255c82--- /dev/null+++ b/pkg/chat/service/chat_service.go@@ -0,0 +1,256 @@+package chat_service++import (+ "context"+ "errors"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/appstate"+ "go.mau.fi/whatsmeow/types"+)++type ChatService interface {+ ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error)+ ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error)+ ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error)+ ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error)+ ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error)+ ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error)+ HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error)+}++type chatService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type BodyStruct struct {+ Chat string `json:"chat"`+}++type HistorySyncRequestStruct struct {+ MessageInfo *types.MessageInfo `json:"messageInfo"`+ Count int `json:"count"`+}++func (c *chatService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := c.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (c *chatService) ChatPin(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, true))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error pin chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) ChatUnpin(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildPin(recipient, false))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unpin chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) ChatArchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, true, time.Time{}, nil))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error archive chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) ChatUnarchive(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildArchive(recipient, false, time.Time{}, nil))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unarchive chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) ChatMute(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, true, 1*time.Hour))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) ChatUnmute(data *BodyStruct, instance *instance_model.Instance) (string, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.SendAppState(context.Background(), appstate.BuildMute(recipient, false, 0*time.Hour))+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmute chat: %v", instance.Id, err)+ return "", err+ }++ return ts.String(), nil+}++func (c *chatService) HistorySyncRequest(data *HistorySyncRequestStruct, instance *instance_model.Instance) (*whatsmeow.SendResponse, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ messageInfo := types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: data.MessageInfo.Chat,+ IsFromMe: data.MessageInfo.IsFromMe,+ IsGroup: data.MessageInfo.IsGroup,+ },+ ID: data.MessageInfo.ID,+ Timestamp: data.MessageInfo.Timestamp,+ }++ histRequest := client.BuildHistorySyncRequest(&messageInfo, data.Count)++ res, err := client.SendMessage(context.Background(), messageInfo.Chat, histRequest, whatsmeow.SendRequestExtra{Peer: true})+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error history sync request: %v", instance.Id, err)+ return nil, err+ }++ return &res, nil+}++func NewChatService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) ChatService {+ return &chatService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/community/handler/community_handler.go b/pkg/community/handler/community_handler.gonew file mode 100644index 0000000..a60a8b1--- /dev/null+++ b/pkg/community/handler/community_handler.go@@ -0,0 +1,160 @@+package community_handler++import (+ "net/http"++ community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ "github.com/gin-gonic/gin"+)++type CommunityHandler interface {+ CreateCommunity(ctx *gin.Context)+ CommunityAdd(ctx *gin.Context)+ CommunityRemove(ctx *gin.Context)+}++type communityHandler struct {+ communityService community_service.CommunityService+}++// Create community+// @Summary Create community+// @Description Create community+// @Tags Community+// @Accept json+// @Produce json+// @Param message body community_service.CreateCommunityStruct true "Community data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /community/create [post]+func (c *communityHandler) CreateCommunity(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *community_service.CreateCommunityStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.CommunityName == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "community name is required"})+ return+ }++ community, err := c.communityService.CreateCommunity(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": community})+}++// Add participant to community+// @Summary Add participant to community+// @Description Add participant to community+// @Tags Community+// @Accept json+// @Produce json+// @Param message body community_service.AddParticipantStruct true "Participant data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /community/add [post]+func (c *communityHandler) CommunityAdd(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *community_service.AddParticipantStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.CommunityJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})+ return+ }++ if len(data.GroupJID) == 0 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})+ return+ }++ resp, err := c.communityService.CommunityAdd(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Remove participant from community+// @Summary Remove participant from community+// @Description Remove participant from community+// @Tags Community+// @Accept json+// @Produce json+// @Param message body community_service.AddParticipantStruct true "Participant data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /community/remove [post]+func (c *communityHandler) CommunityRemove(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *community_service.AddParticipantStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.CommunityJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "community jid is required"})+ return+ }++ if len(data.GroupJID) == 0 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "group jid is required"})+ return+ }++ resp, err := c.communityService.CommunityRemove(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++func NewCommunityHandler(+ communityService community_service.CommunityService,+) CommunityHandler {+ return &communityHandler{+ communityService: communityService,+ }+}diff --git a/pkg/community/service/community_service.go b/pkg/community/service/community_service.gonew file mode 100644index 0000000..ed9f9e6--- /dev/null+++ b/pkg/community/service/community_service.go@@ -0,0 +1,169 @@+package community_service++import (+ "context"+ "errors"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "github.com/gin-gonic/gin"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+)++type CommunityService interface {+ CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error)+ CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)+ CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error)+}++type communityService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type CreateCommunityStruct struct {+ CommunityName string `json:"communityName"`+}++type AddParticipantStruct struct {+ CommunityJID string `json:"communityJid"`+ GroupJID []string `json:"groupJid"`+}++func (c *communityService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := c.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = c.clientPointer[instanceId]+ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ c.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ c.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (c *communityService) CreateCommunity(data *CreateCommunityStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{+ Name: data.CommunityName,+ GroupParent: types.GroupParent{+ IsParent: true,+ },+ })+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create community: %v", instance.Id, err)+ return nil, err+ }++ return resp, nil+}++func (c *communityService) CommunityAdd(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ communityJID, ok := utils.ParseJID(data.CommunityJID)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return nil, errors.New("error parse community jid")+ }++ var successList []string+ var failedList []string++ for _, participant := range data.GroupJID {+ groupJID, _ := utils.ParseJID(participant)+ err := client.LinkGroup(context.Background(), communityJID, groupJID)+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)+ failedList = append(failedList, groupJID.String())+ }+ successList = append(failedList, groupJID.String())+ }++ return gin.H{+ "success": successList,+ "failed": failedList,+ }, nil+}++func (c *communityService) CommunityRemove(data *AddParticipantStruct, instance *instance_model.Instance) (gin.H, error) {+ client, err := c.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ communityJID, ok := utils.ParseJID(data.CommunityJID)+ if !ok {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return nil, errors.New("error parse community jid")+ }++ var successList []string+ var failedList []string++ for _, participant := range data.GroupJID {+ groupJID, _ := utils.ParseJID(participant)+ err := client.UnlinkGroup(context.Background(), communityJID, groupJID)+ if err != nil {+ c.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error link group: %v", instance.Id, err)+ failedList = append(failedList, groupJID.String())+ }+ successList = append(failedList, groupJID.String())+ }++ return gin.H{+ "success": successList,+ "failed": failedList,+ }, nil+}++func NewCommunityService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) CommunityService {+ return &communityService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/config/config.go b/pkg/config/config.gonew file mode 100644index 0000000..a7a540a--- /dev/null+++ b/pkg/config/config.go@@ -0,0 +1,455 @@+package config++import (+ "database/sql"+ "fmt"+ "net/url"+ "os"+ "strconv"+ "strings"+ "time"++ "github.com/gomessguii/logger"+ "gorm.io/driver/postgres"+ "gorm.io/gorm"++ config_env "github.com/EvolutionAPI/evolution-go/pkg/config/env"+)++type Config struct {+ PostgresAuthDB string+ postgresUsersDB string+ PostgresHost string+ PostgresPort string+ PostgresUser string+ PostgresPassword string+ PostgresDB string+ DatabaseSaveMessages bool+ GlobalApiKey string+ WaDebug string+ LogType string+ WebhookFiles bool+ ConnectOnStartup bool+ OsName string+ AmqpUrl string+ AmqpGlobalEnabled bool+ WebhookUrl string+ ClientName string+ ApiAudioConverter string+ ApiAudioConverterKey string+ MinioEndpoint string+ MinioAccessKey string+ MinioSecretKey string+ MinioBucket string+ MinioUseSSL bool+ MinioEnabled bool+ MinioRegion string+ WhatsappVersionMajor int+ WhatsappVersionMinor int+ WhatsappVersionPatch int+ ProxyHost string+ ProxyPort string+ ProxyUsername string+ ProxyPassword string+ AmqpGlobalEvents []string+ AmqpSpecificEvents []string+ NatsUrl string+ NatsGlobalEnabled bool+ NatsGlobalEvents []string+ EventIgnoreGroup bool+ EventIgnoreStatus bool+ QrcodeMaxCount int+ CheckUserExists bool++ // Logger configurations+ LogMaxSize int+ LogMaxBackups int+ LogMaxAge int+ LogDirectory string+ LogCompress bool++}++// EnsureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.+func (c *Config) EnsureDBExists(dsn string) error {+ return ensureDBExists(dsn)+}++// ensureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.+func ensureDBExists(dsn string) error {+ dbName, adminDSN, err := extractDBNameAndAdminDSN(dsn)+ if err != nil {+ return err+ }++ db, err := sql.Open("postgres", adminDSN)+ if err != nil {+ return fmt.Errorf("failed to connect to postgres for auto-setup: %v", err)+ }+ defer db.Close()++ var exists bool+ err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", dbName).Scan(&exists)+ if err != nil {+ return fmt.Errorf("failed to check database existence: %v", err)+ }++ if !exists {+ logger.LogInfo("[CONFIG] Database %q not found, creating it automatically...", dbName)+ _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %q", dbName))+ if err != nil {+ return fmt.Errorf("failed to create database %q: %v", dbName, err)+ }+ logger.LogInfo("[CONFIG] Database %q created successfully", dbName)+ }++ return nil+}++// extractDBNameAndAdminDSN parses a DSN (URL or key=value) and returns the database name+// and a DSN pointing to the "postgres" maintenance database.+func extractDBNameAndAdminDSN(dsn string) (string, string, error) {+ // Try URL format: postgres://user:pass@host:port/dbname?...+ if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {+ u, err := url.Parse(dsn)+ if err != nil {+ return "", "", fmt.Errorf("failed to parse DSN URL: %v", err)+ }+ dbName := strings.TrimPrefix(u.Path, "/")+ u.Path = "/postgres"+ return dbName, u.String(), nil+ }++ // Key=value format: host=... user=... password=... dbname=... sslmode=...+ parts := strings.Fields(dsn)+ kvMap := make(map[string]string, len(parts))+ for _, p := range parts {+ kv := strings.SplitN(p, "=", 2)+ if len(kv) == 2 {+ kvMap[kv[0]] = kv[1]+ }+ }+ dbName, ok := kvMap["dbname"]+ if !ok || dbName == "" {+ return "", "", fmt.Errorf("could not extract dbname from DSN")+ }+ kvMap["dbname"] = "postgres"+ adminParts := make([]string, 0, len(kvMap))+ for k, v := range kvMap {+ adminParts = append(adminParts, k+"="+v)+ }+ return dbName, strings.Join(adminParts, " "), nil+}++func (c *Config) CreateUsersDB() (*gorm.DB, error) {+ logger.LogDebug("Connecting to database on: %s", c.postgresUsersDB)++ dbDSN := c.postgresUsersDB++ if c.postgresUsersDB == "" {+ dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)+ }++ if err := ensureDBExists(dbDSN); err != nil {+ logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)+ }++ db, err := gorm.Open(+ postgres.Open(dbDSN),+ &gorm.Config{},+ )+ if err != nil {+ return nil, err+ }++ // Configurar pool de conexões no GORM+ sqlDB, err := db.DB()+ if err != nil {+ return nil, fmt.Errorf("erro ao obter sql.DB do GORM: %v", err)+ }++ // Configurar pool de conexões para evitar conexões ociosas não fechadas+ sqlDB.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente+ sqlDB.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool+ sqlDB.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts+ sqlDB.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto++ return db, nil+}++func (c *Config) CreateAuthDB() (*sql.DB, error) {+ dbDSN := c.postgresUsersDB++ if c.postgresUsersDB == "" {+ dbDSN = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.PostgresHost, c.PostgresPort, c.PostgresUser, c.PostgresPassword, c.PostgresDB)+ }++ if err := ensureDBExists(dbDSN); err != nil {+ logger.LogWarn("[CONFIG] Auto-setup failed (will try connecting anyway): %v", err)+ }++ db, err := sql.Open("postgres", dbDSN)+ if err != nil {+ return nil, err+ }++ // Configurar pool de conexões para evitar conexões ociosas não fechadas+ db.SetMaxOpenConns(25) // Máximo de 25 conexões abertas simultaneamente+ db.SetMaxIdleConns(5) // Máximo de 5 conexões ociosas no pool+ db.SetConnMaxLifetime(5 * time.Minute) // Reconectar após 5 minutos para evitar timeouts+ db.SetConnMaxIdleTime(1 * time.Minute) // Fechar conexões ociosas após 1 minuto++ // Testar a conexão+ err = db.Ping()+ if err != nil {+ return nil, fmt.Errorf("erro ao testar conexão PostgreSQL AUTH: %v", err)+ }++ return db, nil+}++func Load() *Config {+ postgresAuthDB := os.Getenv(config_env.POSTGRES_AUTH_DB)++ postgresUsersDB := os.Getenv(config_env.POSTGRES_USERS_DB)++ postgresHost := os.Getenv(config_env.POSTGRES_HOST)+ postgresPort := os.Getenv(config_env.POSTGRES_PORT)+ postgresUser := os.Getenv(config_env.POSTGRES_USER)+ postgresPassword := os.Getenv(config_env.POSTGRES_PASSWORD)+ postgresDB := os.Getenv(config_env.POSTGRES_DB)++ if postgresUsersDB == "" && (postgresHost == "" || postgresPort == "" || postgresUser == "" || postgresPassword == "" || postgresDB == "") {+ logger.LogFatal("[CONFIG] required database configuration variables are missing. Please check your environment configuration.")+ }++ databaseSaveMessages := os.Getenv(config_env.DATABASE_SAVE_MESSAGES)+ panicIfEmpty(config_env.DATABASE_SAVE_MESSAGES, databaseSaveMessages)++ globalApiKey := os.Getenv(config_env.GLOBAL_API_KEY)+ panicIfEmpty(config_env.GLOBAL_API_KEY, globalApiKey)++ clientName := os.Getenv(config_env.CLIENT_NAME)++ waDebug := os.Getenv(config_env.WA_DEBUG)++ logType := os.Getenv(config_env.LOGTYPE)++ webhookFiles := os.Getenv(config_env.WEBHOOKFILES)+ if webhookFiles == "" {+ webhookFiles = "true"+ }++ connectOnStartup := os.Getenv(config_env.CONNECT_ON_STARTUP)+ if connectOnStartup == "" {+ connectOnStartup = "false"+ }++ osName := os.Getenv(config_env.OS_NAME)++ amqpUrl := os.Getenv(config_env.AMQP_URL)++ // Validate AMQP URL format+ if err := validateAMQPURL(amqpUrl); err != nil {+ logger.LogFatal("[CONFIG] AMQP URL validation failed: %v", err)+ }++ amqpGlobalEnabled := os.Getenv(config_env.AMQP_GLOBAL_ENABLED)++ webhookUrl := os.Getenv(config_env.WEBHOOK_URL)++ apiAudioConverter := os.Getenv(config_env.API_AUDIO_CONVERTER)+ apiAudioConverterKey := os.Getenv(config_env.API_AUDIO_CONVERTER_KEY)++ whatsappVersionMajor := os.Getenv(config_env.WHATSAPP_VERSION_MAJOR)+ whatsappVersionMinor := os.Getenv(config_env.WHATSAPP_VERSION_MINOR)+ whatsappVersionPatch := os.Getenv(config_env.WHATSAPP_VERSION_PATCH)++ proxyHost := os.Getenv(config_env.PROXY_HOST)+ proxyPort := os.Getenv(config_env.PROXY_PORT)+ proxyUsername := os.Getenv(config_env.PROXY_USERNAME)+ proxyPassword := os.Getenv(config_env.PROXY_PASSWORD)++ eventIgnoreGroup := os.Getenv(config_env.EVENT_IGNORE_GROUP)+ eventIgnoreStatus := os.Getenv(config_env.EVENT_IGNORE_STATUS)+ qrcodeMaxCount := os.Getenv(config_env.QRCODE_MAX_COUNT)+ checkUserExists := os.Getenv(config_env.CHECK_USER_EXISTS)++ if checkUserExists == "" {+ checkUserExists = "true"+ }++ // Convertendo para int com valores padrão caso estejam vazios+ major := 0+ if whatsappVersionMajor != "" {+ major, _ = strconv.Atoi(whatsappVersionMajor)+ }+ minor := 0+ if whatsappVersionMinor != "" {+ minor, _ = strconv.Atoi(whatsappVersionMinor)+ }+ patch := 0+ if whatsappVersionPatch != "" {+ patch, _ = strconv.Atoi(whatsappVersionPatch)+ }++ qrMaxCount := 5 // Valor padrão+ if qrcodeMaxCount != "" {+ qrMaxCount, _ = strconv.Atoi(qrcodeMaxCount)+ }++ amqpGlobalEvents := strings.Split(os.Getenv(config_env.AMQP_GLOBAL_EVENTS), ",")+ if len(amqpGlobalEvents) == 1 && amqpGlobalEvents[0] == "" {+ amqpGlobalEvents = []string{}+ }++ amqpSpecificEvents := strings.Split(os.Getenv(config_env.AMQP_SPECIFIC_EVENTS), ",")+ if len(amqpSpecificEvents) == 1 && amqpSpecificEvents[0] == "" {+ amqpSpecificEvents = []string{}+ }++ natsUrl := os.Getenv(config_env.NATS_URL)+ natsGlobalEnabled := os.Getenv(config_env.NATS_GLOBAL_ENABLED)+ natsGlobalEvents := strings.Split(os.Getenv(config_env.NATS_GLOBAL_EVENTS), ",")+ if len(natsGlobalEvents) == 1 && natsGlobalEvents[0] == "" {+ natsGlobalEvents = []string{}+ }++ // Logger configurations+ logMaxSize, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_SIZE))+ if logMaxSize == 0 {+ logMaxSize = 100 // Default 100MB+ }++ logMaxBackups, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_BACKUPS))+ if logMaxBackups == 0 {+ logMaxBackups = 5 // Default 5 backups+ }++ logMaxAge, _ := strconv.Atoi(os.Getenv(config_env.LOG_MAX_AGE))+ if logMaxAge == 0 {+ logMaxAge = 30 // Default 30 days+ }++ logDirectory := os.Getenv(config_env.LOG_DIRECTORY)+ if logDirectory == "" {+ logDirectory = "./logs" // Default logs directory+ }++ logCompress := os.Getenv(config_env.LOG_COMPRESS) == "true"+ if os.Getenv(config_env.LOG_COMPRESS) == "" {+ logCompress = true // Default compression enabled+ }++ config := &Config{+ PostgresAuthDB: postgresAuthDB,+ postgresUsersDB: postgresUsersDB,+ DatabaseSaveMessages: databaseSaveMessages == "true",+ GlobalApiKey: globalApiKey,+ WaDebug: waDebug,+ LogType: logType,+ WebhookFiles: webhookFiles == "true",+ ConnectOnStartup: connectOnStartup == "true",+ OsName: osName,+ AmqpUrl: amqpUrl,+ AmqpGlobalEnabled: amqpGlobalEnabled == "true",+ WebhookUrl: webhookUrl,+ ClientName: clientName,+ ApiAudioConverter: apiAudioConverter,+ ApiAudioConverterKey: apiAudioConverterKey,+ PostgresHost: postgresHost,+ PostgresPort: postgresPort,+ PostgresUser: postgresUser,+ PostgresPassword: postgresPassword,+ PostgresDB: postgresDB,+ WhatsappVersionMajor: major,+ WhatsappVersionMinor: minor,+ WhatsappVersionPatch: patch,+ ProxyHost: proxyHost,+ ProxyPort: proxyPort,+ ProxyUsername: proxyUsername,+ ProxyPassword: proxyPassword,+ EventIgnoreGroup: eventIgnoreGroup == "true",+ EventIgnoreStatus: eventIgnoreStatus == "true",+ QrcodeMaxCount: qrMaxCount,+ CheckUserExists: checkUserExists != "false", // Default true, set to false to disable+ AmqpGlobalEvents: amqpGlobalEvents,+ AmqpSpecificEvents: amqpSpecificEvents,+ NatsUrl: natsUrl,+ NatsGlobalEnabled: natsGlobalEnabled == "true",+ NatsGlobalEvents: natsGlobalEvents,+ LogMaxSize: logMaxSize,+ LogMaxBackups: logMaxBackups,+ LogMaxAge: logMaxAge,+ LogDirectory: logDirectory,+ LogCompress: logCompress,+ }++ minioEnabled := os.Getenv(config_env.MINIO_ENABLED) == "true"+ if minioEnabled {+ config.MinioEnabled = true+ loadMinioConfig(config)+ }++ return config+}++func loadMinioConfig(config *Config) {+ minioEndpoint := os.Getenv(config_env.MINIO_ENDPOINT)+ panicIfEmpty(config_env.MINIO_ENDPOINT, minioEndpoint)++ minioAccessKey := os.Getenv(config_env.MINIO_ACCESS_KEY)+ panicIfEmpty(config_env.MINIO_ACCESS_KEY, minioAccessKey)++ minioSecretKey := os.Getenv(config_env.MINIO_SECRET_KEY)+ panicIfEmpty(config_env.MINIO_SECRET_KEY, minioSecretKey)++ minioBucket := os.Getenv(config_env.MINIO_BUCKET)+ panicIfEmpty(config_env.MINIO_BUCKET, minioBucket)++ minioUseSSL := os.Getenv(config_env.MINIO_USE_SSL) == "true"++ minioRegion := os.Getenv(config_env.MINIO_REGION)++ config.MinioEndpoint = minioEndpoint+ config.MinioAccessKey = minioAccessKey+ config.MinioSecretKey = minioSecretKey+ config.MinioBucket = minioBucket+ config.MinioUseSSL = minioUseSSL+ config.MinioRegion = minioRegion+}++func panicIfEmpty(key, value string) {+ if value == "" {+ if os.Getenv("DEBUG_ENABLED") != "1" {+ logger.LogInfo("You are NOT on development mode")+ }+ logger.LogFatal("[CONFIG] required configuration variable is missing. Please check your environment configuration.")+ }+}++// validateAMQPURL validates if the AMQP URL has the correct scheme and format+func validateAMQPURL(amqpURL string) error {+ if amqpURL == "" {+ return nil // Empty URL is allowed (RabbitMQ disabled)+ }++ // Parse the URL+ parsedURL, err := url.Parse(amqpURL)+ if err != nil {+ return fmt.Errorf("invalid AMQP URL format: %v", err)+ }++ // Check if scheme is valid+ if parsedURL.Scheme != "amqp" && parsedURL.Scheme != "amqps" {+ return fmt.Errorf("AMQP scheme must be either 'amqp://' or 'amqps://', got: '%s://'", parsedURL.Scheme)+ }++ // Check if host is present+ if parsedURL.Host == "" {+ return fmt.Errorf("AMQP URL must include a host")+ }++ logger.LogInfo("[CONFIG] AMQP URL validation successful: %s://%s", parsedURL.Scheme, parsedURL.Host)+ return nil+}diff --git a/pkg/config/env/env.go b/pkg/config/env/env.gonew file mode 100644index 0000000..0fbd936--- /dev/null+++ b/pkg/config/env/env.go@@ -0,0 +1,54 @@+package config_env++const (+ POSTGRES_AUTH_DB = "POSTGRES_AUTH_DB"+ POSTGRES_USERS_DB = "POSTGRES_USERS_DB"+ POSTGRES_HOST = "POSTGRES_HOST"+ POSTGRES_PORT = "POSTGRES_PORT"+ POSTGRES_USER = "POSTGRES_USER"+ POSTGRES_PASSWORD = "POSTGRES_PASSWORD"+ POSTGRES_DB = "POSTGRES_DB"+ DATABASE_SAVE_MESSAGES = "DATABASE_SAVE_MESSAGES"+ GLOBAL_API_KEY = "GLOBAL_API_KEY"+ WA_DEBUG = "DEBUG_ENABLED"+ LOGTYPE = "LOG_TYPE"+ WEBHOOKFILES = "WEBHOOK_FILES"+ CONNECT_ON_STARTUP = "CONNECT_ON_STARTUP"+ OS_NAME = "OS_NAME"+ AMQP_URL = "AMQP_URL"+ AMQP_GLOBAL_ENABLED = "AMQP_GLOBAL_ENABLED"+ AMQP_GLOBAL_EVENTS = "AMQP_GLOBAL_EVENTS"+ AMQP_SPECIFIC_EVENTS = "AMQP_SPECIFIC_EVENTS"+ WEBHOOK_URL = "WEBHOOK_URL"+ CLIENT_NAME = "CLIENT_NAME"+ API_AUDIO_CONVERTER = "API_AUDIO_CONVERTER"+ API_AUDIO_CONVERTER_KEY = "API_AUDIO_CONVERTER_KEY"+ MINIO_ENDPOINT = "MINIO_ENDPOINT"+ MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY"+ MINIO_SECRET_KEY = "MINIO_SECRET_KEY"+ MINIO_BUCKET = "MINIO_BUCKET"+ MINIO_USE_SSL = "MINIO_USE_SSL"+ MINIO_ENABLED = "MINIO_ENABLED"+ MINIO_REGION = "MINIO_REGION"+ WHATSAPP_VERSION_MAJOR = "WHATSAPP_VERSION_MAJOR"+ WHATSAPP_VERSION_MINOR = "WHATSAPP_VERSION_MINOR"+ WHATSAPP_VERSION_PATCH = "WHATSAPP_VERSION_PATCH"+ PROXY_HOST = "PROXY_HOST"+ PROXY_PORT = "PROXY_PORT"+ PROXY_USERNAME = "PROXY_USERNAME"+ PROXY_PASSWORD = "PROXY_PASSWORD"+ NATS_URL = "NATS_URL"+ NATS_GLOBAL_ENABLED = "NATS_GLOBAL_ENABLED"+ NATS_GLOBAL_EVENTS = "NATS_GLOBAL_EVENTS"+ EVENT_IGNORE_GROUP = "EVENT_IGNORE_GROUP"+ EVENT_IGNORE_STATUS = "EVENT_IGNORE_STATUS"+ QRCODE_MAX_COUNT = "QRCODE_MAX_COUNT"+ CHECK_USER_EXISTS = "CHECK_USER_EXISTS"++ // Logger configurations+ LOG_MAX_SIZE = "LOG_MAX_SIZE"+ LOG_MAX_BACKUPS = "LOG_MAX_BACKUPS"+ LOG_MAX_AGE = "LOG_MAX_AGE"+ LOG_DIRECTORY = "LOG_DIRECTORY"+ LOG_COMPRESS = "LOG_COMPRESS"+)diff --git a/pkg/core/c0.go b/pkg/core/c0.gonew file mode 100644index 0000000..10f963a--- /dev/null+++ b/pkg/core/c0.go@@ -0,0 +1,837 @@+package core++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/rand"+ "crypto/sha256"+ "encoding/binary"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "github.com/gin-gonic/gin"+ "gorm.io/gorm"+ "io"+ "log"+ "net"+ "net/http"+ "os"+ "strconv"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++var (+ encodedEP string+ xorKey string+)++func _d0() string {+ if encodedEP != "" && xorKey != "" {+ return decodeXOR(encodedEP, xorKey)+ }+ parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"}+ var s string+ for _, p := range parts {+ s += p+ }+ return s+}++func decodeXOR(enc, key string) string {+ encBytes := hexDec(enc)+ keyBytes := hexDec(key)+ if len(keyBytes) == 0 {+ return ""+ }+ out := make([]byte, len(encBytes))+ for i, b := range encBytes {+ out[i] = b ^ keyBytes[i%len(keyBytes)]+ }+ return string(out)+}++func hexDec(s string) []byte {+ if len(s)%2 != 0 {+ return nil+ }+ b := make([]byte, len(s)/2)+ for i := 0; i < len(s); i += 2 {+ b[i/2] = hexVal(s[i])<<4 | hexVal(s[i+1])+ }+ return b+}++func hexVal(c byte) byte {+ switch {+ case c >= '0' && c <= '9':+ return c - '0'+ case c >= 'a' && c <= 'f':+ return c - 'a' + 10+ case c >= 'A' && c <= 'F':+ return c - 'A' + 10+ }+ return 0+}++var _h0 = &http.Client{Timeout: 10 * time.Second}++func _sg(body []byte, secret string) string {+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write(body)+ return hex.EncodeToString(mac.Sum(nil))+}++func _ps(path string, payload interface{}, _a0 string) (*http.Response, error) {+ body, err := json.Marshal(payload)+ if err != nil {+ return nil, err+ }++ url := _d0() + path+ req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Api-Key", _a0)+ req.Header.Set("X-Signature", _sg(body, _a0))++ return _h0.Do(req)+}++func _gu(path string) (*http.Response, error) {+ url := _d0() + path+ return _h0.Get(url)+}++func _pu(path string, payload interface{}) (*http.Response, error) {+ body, err := json.Marshal(payload)+ if err != nil {+ return nil, err+ }++ url := _d0() + path+ req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Content-Type", "application/json")+ return _h0.Do(req)+}++func _re(resp *http.Response) error {+ b, _ := io.ReadAll(resp.Body)+ var errBody struct {+ Message string `json:"message"`+ Error string `json:"error"`+ }+ if err := json.Unmarshal(b, &errBody); err == nil {+ msg := errBody.Message+ if msg == "" {+ msg = errBody.Error+ }+ if msg != "" {+ return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode)+ }+ }+ return fmt.Errorf("HTTP %d", resp.StatusCode)+}++type RuntimeConfig struct {+ ID uint `gorm:"primaryKey;autoIncrement" json:"id"`+ Key string `gorm:"uniqueIndex;size:100;not null" json:"key"`+ Value string `gorm:"type:text;not null" json:"value"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+}++func (RuntimeConfig) TableName() string {+ return "runtime_configs"+}++const (+ _ck0 = "instance_id"+ _ck1 = "api_key"+ _ck2 = "_a7"+ _ck3 = "customer_id"+)++var _db0 *gorm.DB++func SetDB(db *gorm.DB) {+ _db0 = db+}++func MigrateDB() error {+ if _db0 == nil {+ return fmt.Errorf("core: database not set, call SetDB first")+ }+ return _db0.AutoMigrate(&RuntimeConfig{})+}++func _gc(key string) (string, error) {+ if _db0 == nil {+ return "", fmt.Errorf("core: database not set")+ }+ var cfg RuntimeConfig+ result := _db0.Where("key = ?", key).First(&cfg)+ if result.Error != nil {+ return "", result.Error+ }+ return cfg.Value, nil+}++func _sc(key, value string) error {+ if _db0 == nil {+ return fmt.Errorf("core: database not set")+ }+ var cfg RuntimeConfig+ result := _db0.Where("key = ?", key).First(&cfg)+ if result.Error != nil {+ return _db0.Create(&RuntimeConfig{Key: key, Value: value}).Error+ }+ return _db0.Model(&cfg).Update("value", value).Error+}++func _dc(key string) {+ if _db0 == nil {+ return+ }+ _db0.Where("key = ?", key).Delete(&RuntimeConfig{})+}++type _rtd struct {+ APIKey string+ Tier string+ CustomerID int+}++func _lrd() (*_rtd, error) {+ _a0, err := _gc(_ck1)+ if err != nil || _a0 == "" {+ return nil, fmt.Errorf("no license found")+ }++ _a7, _ := _gc(_ck2)+ customerIDStr, _ := _gc(_ck3)+ customerID, _ := strconv.Atoi(customerIDStr)++ return &_rtd{+ APIKey: _a0,+ Tier: _a7,+ CustomerID: customerID,+ }, nil+}++func _srd(rd *_rtd) error {+ if err := _sc(_ck1, rd.APIKey); err != nil {+ return err+ }+ if err := _sc(_ck2, rd.Tier); err != nil {+ return err+ }+ if rd.CustomerID > 0 {+ if err := _sc(_ck3, strconv.Itoa(rd.CustomerID)); err != nil {+ return err+ }+ }+ return nil+}++func _rrd() {+ _dc(_ck1)+ _dc(_ck2)+ _dc(_ck3)+}++func _lid() (string, error) {+ id, err := _gc(_ck0)+ if err == nil && len(id) == 36 {+ return id, nil+ }++ id = _ghi()+ if id == "" {+ id, err = _uuid()+ if err != nil {+ return "", err+ }+ }++ if err := _sc(_ck0, id); err != nil {+ return "", err+ }+ return id, nil+}++func _ghi() string {+ hostname, _ := os.Hostname()+ macAddr := _gpm()+ if hostname == "" && macAddr == "" {+ return ""+ }++ seed := hostname + "|" + macAddr+ h := make([]byte, 16)+ copy(h, []byte(seed))+ for i := 16; i < len(seed); i++ {+ h[i%16] ^= seed[i]+ }+ h[6] = (h[6] & 0x0f) | 0x40 // _a8 4+ h[8] = (h[8] & 0x3f) | 0x80 // variant+ return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",+ h[0:4], h[4:6], h[6:8], h[8:10], h[10:16])+}++func _gpm() string {+ interfaces, err := net.Interfaces()+ if err != nil {+ return ""+ }+ for _, iface := range interfaces {+ if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {+ continue+ }+ if len(iface.HardwareAddr) > 0 {+ return iface.HardwareAddr.String()+ }+ }+ return ""+}++func _uuid() (string, error) {+ var b [16]byte+ if _, err := rand.Read(b[:]); err != nil {+ return "", err+ }+ b[6] = (b[6] & 0x0f) | 0x40+ b[8] = (b[8] & 0x3f) | 0x80+ return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",+ b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil+}+++var _s0 atomic.Value // set during activation++func init() {+ _s0.Store([]byte{0})+}++func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte {+ if rc == nil || !rc._a2.Load() {+ return nil // Will cause panic in caller — intentional+ }+ h := sha256.New()+ h.Write([]byte(instanceName))+ h.Write([]byte(rc._a0))+ salt, _ := _s0.Load().([]byte)+ h.Write(salt)+ return h.Sum(nil)[:16]+}++func ValidateRouteAccess(rc *RuntimeContext) uint64 {+ if rc == nil {+ return 0+ }+ h := rc.ContextHash()+ return binary.LittleEndian.Uint64(h[:8])+}++func DeriveInstanceToken(_a1 string, rc *RuntimeContext) string {+ if rc == nil || !rc._a2.Load() {+ return ""+ }+ h := sha256.Sum256([]byte(_a1 + rc._a0))+ return _he(h[:8])+}++func _he(b []byte) string {+ const hextable = "0123456789abcdef"+ dst := make([]byte, len(b)*2)+ for i, v := range b {+ dst[i*2] = hextable[v>>4]+ dst[i*2+1] = hextable[v&0x0f]+ }+ return string(dst)+}++func ActivateIntegrity(rc *RuntimeContext) {+ if rc == nil {+ return+ }+ h := sha256.Sum256([]byte(rc._a0 + rc._a1 + "ev0"))+ _s0.Store(h[:])+}++const (+ _p2 = 30 * time.Minute+)++type RuntimeContext struct {+ _a0 string+ _a9 string // GLOBAL_API_KEY from .env — used as token for licensing check+ _a1 string+ _a2 atomic.Bool+ _a3 [32]byte // Derived from activation — required by ValidateContext+ mu sync.RWMutex+ _a5 string // Registration URL shown to users before activation+ _a6 string // Registration token for polling+ _a7 string+ _a8 string+}++func (rc *RuntimeContext) ContextHash() [32]byte {+ rc.mu.RLock()+ defer rc.mu.RUnlock()+ return rc._a3+}++func (rc *RuntimeContext) IsActive() bool {+ return rc._a2.Load()+}++func (rc *RuntimeContext) RegistrationURL() string {+ rc.mu.RLock()+ defer rc.mu.RUnlock()+ return rc._a5+}++func (rc *RuntimeContext) APIKey() string {+ rc.mu.RLock()+ defer rc.mu.RUnlock()+ return rc._a0+}++func (rc *RuntimeContext) InstanceID() string {+ return rc._a1+}++func InitializeRuntime(_a7, _a8, _a9 string) *RuntimeContext {+ if _a7 == "" {+ _a7 = "evolution-go"+ }+ if _a8 == "" {+ _a8 = "unknown"+ }++ rc := &RuntimeContext{+ _a7: _a7,+ _a8: _a8,+ _a9: _a9,+ }++ id, err := _lid()+ if err != nil {+ log.Fatalf("[runtime] failed to initialize instance: %v", err)+ }+ rc._a1 = id++ rd, err := _lrd()+ if err == nil && rd.APIKey != "" {+ rc._a0 = rd.APIKey+ fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:])++ rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))+ rc._a2.Store(true)+ ActivateIntegrity(rc)+ fmt.Println(" ✓ License activated successfully")++ go func() {+ if err := _ai(rc, _a8); err != nil {+ fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err)+ }+ }()+ } else {+ fmt.Println()+ fmt.Println(" ╔══════════════════════════════════════════════════════════╗")+ fmt.Println(" ║ License Registration Required ║")+ fmt.Println(" ╚══════════════════════════════════════════════════════════╝")+ fmt.Println()+ fmt.Println(" Server starting without license.")+ fmt.Println(" API endpoints will return 503 until license is activated.")+ fmt.Println(" Use GET /license/register to get the registration URL.")+ fmt.Println()+ rc._a2.Store(false)+ }++ return rc+}++func (rc *RuntimeContext) _ca(authCodeOrKey, _a7 string, customerID int) error {+ _a0, err := _rk(authCodeOrKey)+ if err != nil {+ return fmt.Errorf("key exchange failed: %w", err)+ }++ rc.mu.Lock()+ rc._a0 = _a0+ rc._a5 = ""+ rc._a6 = ""+ rc.mu.Unlock()++ if err := _srd(&_rtd{+ APIKey: _a0,+ Tier: _a7,+ CustomerID: customerID,+ }); err != nil {+ fmt.Printf(" ⚠ Warning: could not save license: %v\n", err)+ }++ if err := _ai(rc, rc._a8); err != nil {+ return err+ }++ rc.mu.Lock()+ rc._a3 = sha256.Sum256([]byte(rc._a0 + rc._a1))+ rc.mu.Unlock()+ rc._a2.Store(true)+ ActivateIntegrity(rc)++ fmt.Printf(" ✓ License activated! Key: %s...%s (_a7: %s)\n",+ _a0[:8], _a0[len(_a0)-4:], _a7)++ go func() {+ if err := _hb(rc, 0); err != nil {+ fmt.Printf(" ⚠ First heartbeat failed: %v\n", err)+ }+ }()++ return nil+}++func ValidateContext(rc *RuntimeContext) (bool, string) {+ if rc == nil {+ return false, ""+ }+ if !rc._a2.Load() {+ return false, rc.RegistrationURL()+ }+ expected := sha256.Sum256([]byte(rc._a0 + rc._a1))+ actual := rc.ContextHash()+ if expected != actual {+ return false, ""+ }+ return true, ""+}++func GateMiddleware(rc *RuntimeContext) gin.HandlerFunc {+ return func(c *gin.Context) {+ path := c.Request.URL.Path++ if path == "/health" || path == "/server/ok" || path == "/favicon.ico" ||+ path == "/license/status" || path == "/license/register" || path == "/license/activate" ||+ strings.HasPrefix(path, "/manager") || strings.HasPrefix(path, "/assets") ||+ strings.HasPrefix(path, "/swagger") || path == "/ws" {+ c.Next()+ return+ }++ valid, _ := ValidateContext(rc)+ if !valid {+ scheme := "http"+ if c.Request.TLS != nil {+ scheme = "https"+ }+ managerURL := fmt.Sprintf("%s://%s/manager/login", scheme, c.Request.Host)++ c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{+ "error": "service not activated",+ "code": "LICENSE_REQUIRED",+ "register_url": managerURL,+ "message": "License required. Open the manager to activate your license.",+ })+ return+ }++ c.Set("_rch", rc.ContextHash())+ c.Next()+ }+}++func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) {+ lic := eng.Group("/license")+ {+ lic.GET("/status", func(c *gin.Context) {+ status := "inactive"+ if rc.IsActive() {+ status = "_a2"+ }++ resp := gin.H{+ "status": status,+ "instance_id": rc._a1,+ }++ rc.mu.RLock()+ if rc._a0 != "" {+ resp["api_key"] = rc._a0[:8] + "..." + rc._a0[len(rc._a0)-4:]+ }+ rc.mu.RUnlock()++ c.JSON(http.StatusOK, resp)+ })++ lic.GET("/register", func(c *gin.Context) {+ if rc.IsActive() {+ c.JSON(http.StatusOK, gin.H{+ "status": "_a2",+ "message": "License is already _a2",+ })+ return+ }++ rc.mu.RLock()+ existingURL := rc._a5+ rc.mu.RUnlock()++ if existingURL != "" {+ c.JSON(http.StatusOK, gin.H{+ "status": "pending",+ "register_url": existingURL,+ })+ return+ }++ payload := map[string]string{+ "_a7": rc._a7,+ "_a8": rc._a8,+ "instance_id": rc._a1,+ }+ if redirectURI := c.Query("redirect_uri"); redirectURI != "" {+ payload["redirect_uri"] = redirectURI+ }++ resp, err := _pu("/v1/register/init", payload)+ if err != nil {+ c.JSON(http.StatusBadGateway, gin.H{+ "error": "Failed to contact licensing server",+ "details": err.Error(),+ })+ return+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ errBody := _re(resp)+ c.JSON(resp.StatusCode, gin.H{+ "error": "Licensing server error",+ "details": errBody.Error(),+ })+ return+ }++ var initResult struct {+ RegisterURL string `json:"register_url"`+ Token string `json:"token"`+ }+ json.NewDecoder(resp.Body).Decode(&initResult)++ rc.mu.Lock()+ rc._a5 = initResult.RegisterURL+ rc._a6 = initResult.Token+ rc.mu.Unlock()++ fmt.Printf(" → Registration URL: %s\n", initResult.RegisterURL)++ c.JSON(http.StatusOK, gin.H{+ "status": "pending",+ "register_url": initResult.RegisterURL,+ })+ })++ lic.GET("/activate", func(c *gin.Context) {+ if rc.IsActive() {+ c.JSON(http.StatusOK, gin.H{+ "status": "_a2",+ "message": "License is already _a2",+ })+ return+ }++ code := c.Query("code")+ if code == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "Missing code parameter",+ "message": "Provide ?code=AUTHORIZATION_CODE from the registration callback.",+ })+ return+ }++ exchangeResp, err := _pu("/v1/register/exchange", map[string]string{+ "authorization_code": code,+ "instance_id": rc._a1,+ })+ if err != nil {+ c.JSON(http.StatusBadGateway, gin.H{+ "error": "Failed to contact licensing server",+ "details": err.Error(),+ })+ return+ }+ defer exchangeResp.Body.Close()++ if exchangeResp.StatusCode != http.StatusOK {+ errBody := _re(exchangeResp)+ c.JSON(exchangeResp.StatusCode, gin.H{+ "error": "Exchange failed",+ "details": errBody.Error(),+ })+ return+ }++ var result struct {+ APIKey string `json:"api_key"`+ Tier string `json:"_a7"`+ CustomerID int `json:"customer_id"`+ }+ json.NewDecoder(exchangeResp.Body).Decode(&result)++ if result.APIKey == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "Invalid or expired code",+ "message": "The authorization code is invalid or has expired.",+ })+ return+ }++ if err := rc._ca(result.APIKey, result.Tier, result.CustomerID); err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "error": "Activation failed",+ "details": err.Error(),+ })+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "status": "_a2",+ "message": "License activated successfully!",+ })+ })+ }+}++func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time) {+ go func() {+ ticker := time.NewTicker(_p2)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if !rc.IsActive() {+ continue+ }+ uptime := int64(time.Since(startTime).Seconds())+ if err := _hb(rc, uptime); err != nil {+ fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err)+ }+ }+ }+ }()+}++func Shutdown(rc *RuntimeContext) {+ if rc == nil || rc._a0 == "" {+ return+ }+ _sd(rc)+}+++func exchangeCode(code string) (_a0 string, err error) {+ resp, err := _pu("/v1/register/exchange", map[string]string{+ "authorization_code": code,+ })+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return "", _re(resp)+ }++ var result struct {+ APIKey string `json:"api_key"`+ }+ json.NewDecoder(resp.Body).Decode(&result)+ if result.APIKey == "" {+ return "", fmt.Errorf("exchange returned empty api_key")+ }+ return result.APIKey, nil+}++func _rk(authCodeOrKey string) (string, error) {+ _a0, err := exchangeCode(authCodeOrKey)+ if err == nil && _a0 != "" {+ return _a0, nil+ }+ return authCodeOrKey, nil+}++func _ai(rc *RuntimeContext, _a8 string) error {+ resp, err := _ps("/v1/activate", map[string]string{+ "instance_id": rc._a1,+ "_a8": _a8,+ }, rc._a0)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return _re(resp)+ }++ var result struct {+ Status string `json:"status"`+ }+ json.NewDecoder(resp.Body).Decode(&result)++ if result.Status != "_a2" {+ return fmt.Errorf("activation returned status: %s", result.Status)+ }+ return nil+}++func _hb(rc *RuntimeContext, uptimeSeconds int64) error {+ resp, err := _ps("/v1/heartbeat", map[string]any{+ "instance_id": rc._a1,+ "uptime_seconds": uptimeSeconds,+ "_a8": rc._a8,+ }, rc._a0)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return _re(resp)+ }+ return nil+}++func _sd(rc *RuntimeContext) {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ body, _ := json.Marshal(map[string]string{+ "instance_id": rc._a1,+ })++ url := _d0() + "/v1/deactivate"+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Api-Key", rc._a0)+ req.Header.Set("X-Signature", _sg(body, rc._a0))+ _h0.Do(req)+}diff --git a/pkg/events/interfaces/producer.go b/pkg/events/interfaces/producer.gonew file mode 100644index 0000000..dbb0a61--- /dev/null+++ b/pkg/events/interfaces/producer.go@@ -0,0 +1,6 @@+package producer_interfaces++type Producer interface {+ Produce(queueName string, payload []byte, webhookUrl string, userID string) error+ CreateGlobalQueues() error+}diff --git a/pkg/events/nats/nats_producer.go b/pkg/events/nats/nats_producer.gonew file mode 100644index 0000000..9fa4c65--- /dev/null+++ b/pkg/events/nats/nats_producer.go@@ -0,0 +1,81 @@+package nats_producer++import (+ producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/gomessguii/logger"+ "github.com/nats-io/nats.go"+)++type natsProducer struct {+ conn *nats.Conn+ natsGlobalEnabled bool+ natsGlobalEvents []string+ loggerWrapper *logger_wrapper.LoggerManager+}++func NewNatsProducer(+ url string,+ natsGlobalEnabled bool,+ natsGlobalEvents []string,+ loggerWrapper *logger_wrapper.LoggerManager,+) producer_interfaces.Producer {+ conn, err := nats.Connect(url)+ if err != nil {+ logger.LogError("Failed to connect to NATS: %v", err)+ return &natsProducer{+ conn: nil,+ natsGlobalEnabled: false,+ natsGlobalEvents: nil,+ loggerWrapper: loggerWrapper,+ }+ }++ return &natsProducer{+ conn: conn,+ natsGlobalEnabled: natsGlobalEnabled,+ natsGlobalEvents: natsGlobalEvents,+ loggerWrapper: loggerWrapper,+ }+}++func (p *natsProducer) Produce(+ queueName string,+ payload []byte,+ natsEnable string,+ userID string,+) error {+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Starting produce for subject: %s", userID, queueName)+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] NATS Producer - Global enabled: %v", userID, p.natsGlobalEnabled)++ if p.conn == nil {+ p.loggerWrapper.GetLogger(userID).LogWarn("[%s] NATS connection is nil", userID)+ return nil+ }++ if natsEnable == "global" {+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Publishing to global subject: %s", userID, queueName)+ err := p.conn.Publish(queueName, payload)+ if err != nil {+ p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to subject %s: %v", userID, queueName, err)+ return err+ }+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to subject: %s", userID, queueName)+ }++ if natsEnable == "enabled" {+ err := p.conn.Publish(queueName, payload)+ if err != nil {+ p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to publish message to instance subject %s: %v", userID, queueName, err)+ return err+ }+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Message published successfully to instance subject: %s", userID, queueName)+ }++ return nil+}++// CreateGlobalQueues não faz nada para NATS producer pois os subjects são criados dinamicamente+func (p *natsProducer) CreateGlobalQueues() error {+ return nil+}diff --git a/pkg/events/rabbitmq/rabbitmq_producer.go b/pkg/events/rabbitmq/rabbitmq_producer.gonew file mode 100644index 0000000..57486d6--- /dev/null+++ b/pkg/events/rabbitmq/rabbitmq_producer.go@@ -0,0 +1,319 @@+package rabbitmq_producer++import (+ "fmt"+ "net/url"+ "strings"+ "time"++ producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/gomessguii/logger"+ amqp "github.com/rabbitmq/amqp091-go"+)++type rabbitMQProducer struct {+ conn *amqp.Connection+ amqpGlobalEnabled bool+ amqpGlobalEvents []string+ amqpSpecificEvents []string+ connStr string+ maxRetries int+ loggerWrapper *logger_wrapper.LoggerManager+}++func NewRabbitMQProducer(+ conn *amqp.Connection,+ amqpGlobalEnabled bool,+ amqpGlobalEvents []string,+ amqpSpecificEvents []string,+ connStr string,+ loggerWrapper *logger_wrapper.LoggerManager,+) producer_interfaces.Producer {+ producer := &rabbitMQProducer{+ conn: conn,+ amqpGlobalEnabled: amqpGlobalEnabled,+ amqpGlobalEvents: amqpGlobalEvents,+ amqpSpecificEvents: amqpSpecificEvents,+ connStr: connStr,+ maxRetries: 3,+ loggerWrapper: loggerWrapper,+ }++ return producer+}++// maskConnectionString masks sensitive information in the connection string for logging+func (p *rabbitMQProducer) maskConnectionString(connStr string) string {+ if connStr == "" {+ return "empty"+ }++ parsedURL, err := url.Parse(connStr)+ if err != nil {+ return "invalid-url"+ }++ // Mask password if present+ if parsedURL.User != nil {+ if _, hasPassword := parsedURL.User.Password(); hasPassword {+ parsedURL.User = url.UserPassword(parsedURL.User.Username(), "***")+ }+ }++ return parsedURL.String()+}++// handleConnectionClose monitors connection close events and logs them+func (p *rabbitMQProducer) handleConnectionClose() {+ if p.conn == nil {+ return+ }++ closeChan := make(chan *amqp.Error)+ p.conn.NotifyClose(closeChan)++ closeErr := <-closeChan+ if closeErr != nil {+ logger.LogWarn("RabbitMQ connection closed unexpectedly: %v", closeErr)+ logger.LogInfo("Connection will be re-established on next message send")+ } else {+ logger.LogInfo("RabbitMQ connection closed gracefully")+ }+}++func (p *rabbitMQProducer) reconnect() error {+ if p.connStr == "" {+ return fmt.Errorf("connection string is empty - RabbitMQ URL not configured")+ }++ logger.LogInfo("Starting RabbitMQ reconnection process with URL: %s", p.maskConnectionString(p.connStr))++ var err error+ for i := 0; i < 3; i++ {+ logger.LogInfo("Tentando reconectar ao RabbitMQ (tentativa %d/3)", i+1)++ // Create connection with heartbeat to prevent timeouts+ config := amqp.Config{+ Heartbeat: 30 * time.Second, // Send heartbeat every 30 seconds+ Locale: "en_US",+ }++ p.conn, err = amqp.DialConfig(p.connStr, config)+ if err == nil {+ logger.LogInfo("Reconectado com sucesso ao RabbitMQ com heartbeat de 30s")++ // Set up connection close notification+ go p.handleConnectionClose()+ return nil+ }++ logger.LogError("Falha na tentativa %d/3 de reconexão: %v", i+1, err)+ if i < 2 { // Don't sleep on the last attempt+ time.Sleep(time.Second * 2)+ }+ }+ return fmt.Errorf("falha ao reconectar após 3 tentativas: %v", err)+}++func (p *rabbitMQProducer) ensureConnection() error {+ if p.conn == nil || p.conn.IsClosed() {+ return p.reconnect()+ }+ return nil+}++func (p *rabbitMQProducer) publishWithRetry(+ channel *amqp.Channel,+ queueName string,+ payload []byte,+ userID string,+) error {+ var err error+ for i := 0; i < p.maxRetries; i++ {+ err = channel.Publish(+ "", // exchange+ queueName, // routing key+ false, // mandatory+ false, // immediate+ amqp.Publishing{+ ContentType: "application/json",+ Body: payload,+ DeliveryMode: amqp.Persistent, // Garante persistência da mensagem+ })++ if err == nil {+ return nil+ }++ logger.LogWarn("[%s] Falha ao publicar mensagem (tentativa %d/%d): %v",+ userID, i+1, p.maxRetries, err)++ // Se o erro for de conexão, tenta reconectar+ if err.Error() == "Exception (504) Reason: \"channel/connection is not open\"" {+ if err := p.ensureConnection(); err != nil {+ continue+ }++ // Cria novo canal após reconexão+ channel, err = p.conn.Channel()+ if err != nil {+ continue+ }+ }++ time.Sleep(time.Second * time.Duration(i+1))+ }+ return err+}++func (p *rabbitMQProducer) Produce(+ queueName string,+ payload []byte,+ rabbitmqEnable string,+ userID string,+) error {+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] RabbitMQ Producer - Starting produce for queue: %s", userID, queueName)++ if p.connStr == "" {+ return fmt.Errorf("RabbitMQ connection string is empty - check AMQP_URL configuration")+ }++ if err := p.ensureConnection(); err != nil {+ p.loggerWrapper.GetLogger(userID).LogError("[%s] Failed to ensure RabbitMQ connection: %v", userID, err)+ return fmt.Errorf("falha ao garantir conexão: %v", err)+ }++ channel, err := p.conn.Channel()+ if err != nil {+ return fmt.Errorf("falha ao abrir canal: %v", err)+ }+ defer channel.Close()++ // Configura confirmação de publicação+ if err := channel.Confirm(false); err != nil {+ return fmt.Errorf("falha ao configurar confirms do canal: %v", err)+ }++ args := amqp.Table{+ "x-queue-type": "quorum",+ "x-ha-policy": "all", // Alta disponibilidade+ }++ if rabbitmqEnable == "global" || rabbitmqEnable == "enabled" {+ _, err = channel.QueueDeclare(+ queueName, // name+ true, // durable+ false, // delete when unused+ false, // exclusive+ false, // no-wait+ args, // arguments+ )+ if err != nil {+ return fmt.Errorf("falha ao declarar fila %s: %v", queueName, err)+ }++ err = p.publishWithRetry(channel, queueName, payload, userID)+ if err != nil {+ return fmt.Errorf("falha ao publicar mensagem após todas as tentativas: %v", err)+ }++ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] Mensagem publicada com sucesso na fila: %s", userID, queueName)+ }++ return nil+}++// CreateGlobalQueues cria todas as filas globais no startup da aplicação+func (p *rabbitMQProducer) CreateGlobalQueues() error {+ if !p.amqpGlobalEnabled {+ return nil+ }++ p.loggerWrapper.GetLogger("system").LogInfo("Creating global queues for enabled events")++ if err := p.ensureConnection(); err != nil {+ return fmt.Errorf("failed to ensure connection: %v", err)+ }++ channel, err := p.conn.Channel()+ if err != nil {+ return fmt.Errorf("failed to open channel: %v", err)+ }+ defer channel.Close()++ args := amqp.Table{+ "x-queue-type": "quorum",+ "x-ha-policy": "all", // Alta disponibilidade+ }++ createdQueues := 0++ // AMQP_SPECIFIC_EVENTS tem prioridade sobre AMQP_GLOBAL_EVENTS+ if len(p.amqpSpecificEvents) > 0 {+ p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_SPECIFIC_EVENTS (priority over AMQP_GLOBAL_EVENTS)")++ // Cria filas diretas para eventos específicos+ for _, eventName := range p.amqpSpecificEvents {+ queueName := strings.ToLower(eventName)++ _, err = channel.QueueDeclare(+ queueName, // name+ true, // durable+ false, // delete when unused+ false, // exclusive+ false, // no-wait+ args, // arguments+ )+ if err != nil {+ p.loggerWrapper.GetLogger("system").LogError("Failed to create specific queue %s: %v", queueName, err)+ return fmt.Errorf("failed to create specific queue %s: %v", queueName, err)+ }+ p.loggerWrapper.GetLogger("system").LogInfo("Specific queue created: %s", queueName)+ createdQueues+++ }+ } else {+ p.loggerWrapper.GetLogger("system").LogInfo("Using AMQP_GLOBAL_EVENTS (fallback mode)")++ // Mapeia eventos globais para os eventos originais que precisam de filas (modo antigo)+ eventMap := map[string][]string{+ "MESSAGE": {"message"},+ "SEND_MESSAGE": {"sendmessage"},+ "READ_RECEIPT": {"receipt"},+ "PRESENCE": {"presence"},+ "HISTORY_SYNC": {"historysync"},+ "CHAT_PRESENCE": {"chatpresence", "archive"},+ "CALL": {"calloffer", "callaccept", "callterminate", "calloffernotice", "callrelaylatency"},+ "CONNECTION": {"connected", "pairsuccess", "temporaryban", "loggedout", "connectfailure", "disconnected"},+ "LABEL": {"labeledit", "labelassociationchat", "labelassociationmessage"},+ "CONTACT": {"contact", "pushname"},+ "GROUP": {"groupinfo", "joinedgroup"},+ "NEWSLETTER": {"newsletterjoin", "newsletterleave"},+ "QRCODE": {"qrcode", "qrtimeout", "qrsuccess"},+ }++ for _, globalEvent := range p.amqpGlobalEvents {+ if queueNames, exists := eventMap[globalEvent]; exists {+ for _, queueName := range queueNames {+ _, err = channel.QueueDeclare(+ queueName, // name+ true, // durable+ false, // delete when unused+ false, // exclusive+ false, // no-wait+ args, // arguments+ )+ if err != nil {+ p.loggerWrapper.GetLogger("system").LogError("Failed to create global queue %s: %v", queueName, err)+ return fmt.Errorf("failed to create global queue %s: %v", queueName, err)+ }+ p.loggerWrapper.GetLogger("system").LogInfo("Global queue created: %s", queueName)+ createdQueues+++ }+ }+ }+ }++ p.loggerWrapper.GetLogger("system").LogInfo("Successfully created %d global queues", createdQueues)+ return nil+}diff --git a/pkg/events/webhook/webhook_producer.go b/pkg/events/webhook/webhook_producer.gonew file mode 100644index 0000000..433fa3b--- /dev/null+++ b/pkg/events/webhook/webhook_producer.go@@ -0,0 +1,97 @@+package webhook_producer++import (+ "bytes"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+)++type webhookProducer struct {+ url string+ loggerWrapper *logger_wrapper.LoggerManager+}++func NewWebhookProducer(+ url string,+ loggerWrapper *logger_wrapper.LoggerManager,+) producer_interfaces.Producer {+ return &webhookProducer{+ url: url,+ loggerWrapper: loggerWrapper,+ }+}++func (p *webhookProducer) Produce(+ queueName string,+ payload []byte,+ webhookUrl string,+ userID string,+) error {+ splitQueue := strings.Split(queueName, ".")++ if len(splitQueue) < 2 {+ return nil+ }++ if p.url != "" {+ go p.sendWebhookWithRetry(p.url, payload, 5, 30*time.Second, userID)+ }+ if webhookUrl != "" {+ go p.sendWebhookWithRetry(webhookUrl, payload, 5, 30*time.Second, userID)+ }++ return nil+}++func (p *webhookProducer) sendWebhookWithRetry(url string, body []byte, maxRetries int, retryInterval time.Duration, userID string) {+ for i := 0; i < maxRetries; i++ {+ err, responseBody, statusCode := p.sendWebhook(url, body, userID)+ if err == nil {+ p.loggerWrapper.GetLogger(userID).LogInfo("[%s] webhook sent successfully - url: %s, status: %d, response: %s", userID, url, statusCode, string(responseBody))+ return+ }+ p.loggerWrapper.GetLogger(userID).LogWarn("[%s] webhook failed - url: %s, attempt: %d, error: %v", userID, url, i+1, err)++ time.Sleep(retryInterval)+ }+ p.loggerWrapper.GetLogger(userID).LogError("[%s] webhook failed after maximum retries - url: %s", userID, url)+}++func (p *webhookProducer) sendWebhook(url string, body []byte, userID string) (error, []byte, int) {+ req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))+ if err != nil {+ return err, nil, 0+ }++ req.Header.Set("Content-Type", "application/json")++ client := &http.Client{}+ resp, err := client.Do(req)+ if err != nil {+ return err, nil, 0+ }+ defer resp.Body.Close()++ responseBody, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("erro ao ler resposta: %v", err), nil, 0+ }++ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return errors.New("received non-2xx response: " + resp.Status), responseBody, resp.StatusCode+ }++ return nil, responseBody, resp.StatusCode+}++// CreateGlobalQueues não faz nada para webhook producer+func (p *webhookProducer) CreateGlobalQueues() error {+ return nil+}diff --git a/pkg/events/websocket/websocket_producer.go b/pkg/events/websocket/websocket_producer.gonew file mode 100644index 0000000..00b5487--- /dev/null+++ b/pkg/events/websocket/websocket_producer.go@@ -0,0 +1,140 @@+package websocket_producer++import (+ "net/http"+ "strings"+ "sync"++ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/gomessguii/logger"+ "github.com/gorilla/websocket"+)++var upgrader = websocket.Upgrader{+ ReadBufferSize: 1024,+ WriteBufferSize: 1024,+ CheckOrigin: func(r *http.Request) bool {+ logger.LogInfo("Verificando origem da conexão WebSocket")+ return true+ },+}++type websocketProducer struct {+ clients map[string]*websocket.Conn // conexões específicas por instância+ broadcast []*websocket.Conn // conexões que recebem todos os eventos+ clientsMux sync.RWMutex+ loggerWrapper *logger_wrapper.LoggerManager+}++func NewWebsocketProducer(loggerWrapper *logger_wrapper.LoggerManager) *websocketProducer {+ return &websocketProducer{+ clients: make(map[string]*websocket.Conn),+ broadcast: make([]*websocket.Conn, 0),+ clientsMux: sync.RWMutex{},+ loggerWrapper: loggerWrapper,+ }+}++// ServeWs lida com as requisições de upgrade para websocket+func ServeWs(w http.ResponseWriter, r *http.Request, instanceId string, producer *websocketProducer) {+ logger.LogInfo("Iniciando upgrade da conexão WebSocket")+ conn, err := upgrader.Upgrade(w, r, nil)+ if err != nil {+ logger.LogError("Erro ao fazer upgrade da conexão websocket: %v", err)+ return+ }++ logger.LogInfo("Conexão WebSocket estabelecida com sucesso")++ if instanceId == "" {+ producer.AddBroadcastClient(conn)+ } else {+ producer.AddClient(instanceId, conn)+ }++ // Goroutine para limpar conexão quando fechada+ go func() {+ for {+ _, _, err := conn.ReadMessage()+ if err != nil {+ if instanceId == "" {+ producer.RemoveBroadcastClient(conn)+ } else {+ producer.RemoveClient(instanceId)+ }+ conn.Close()+ break+ }+ }+ }()+}++func (p *websocketProducer) AddBroadcastClient(conn *websocket.Conn) {+ p.clientsMux.Lock()+ defer p.clientsMux.Unlock()+ p.broadcast = append(p.broadcast, conn)+ logger.LogInfo("Cliente broadcast websocket adicionado")+}++func (p *websocketProducer) RemoveBroadcastClient(conn *websocket.Conn) {+ p.clientsMux.Lock()+ defer p.clientsMux.Unlock()+ for i, c := range p.broadcast {+ if c == conn {+ p.broadcast = append(p.broadcast[:i], p.broadcast[i+1:]...)+ break+ }+ }+ logger.LogInfo("Cliente broadcast websocket removido")+}++func (p *websocketProducer) AddClient(instanceID string, conn *websocket.Conn) {+ p.clientsMux.Lock()+ defer p.clientsMux.Unlock()+ p.clients[instanceID] = conn+ p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket adicionado para instância: %s", instanceID)+}++func (p *websocketProducer) RemoveClient(instanceID string) {+ p.clientsMux.Lock()+ defer p.clientsMux.Unlock()+ delete(p.clients, instanceID)+ p.loggerWrapper.GetLogger(instanceID).LogInfo("Cliente websocket removido para instância: %s", instanceID)+}++func (p *websocketProducer) Produce(queueName string, payload []byte, instanceID string, _ string) error {+ message := map[string]interface{}{+ "queue": strings.ToLower(queueName),+ "payload": string(payload),+ }++ p.clientsMux.RLock()+ defer p.clientsMux.RUnlock()++ // Envia para cliente específico da instância+ if client, exists := p.clients[instanceID]; exists {+ err := client.WriteJSON(message)+ if err != nil {+ p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem websocket para %s: %v", instanceID, err)+ // Não remove o cliente aqui pois estamos com o RLock+ return err+ }+ p.loggerWrapper.GetLogger(instanceID).LogInfo("Mensagem websocket enviada com sucesso para instância %s na fila %s", instanceID, queueName)+ }++ // Envia para todos os clientes broadcast+ for _, conn := range p.broadcast {+ err := conn.WriteJSON(message)+ if err != nil {+ p.loggerWrapper.GetLogger(instanceID).LogError("Erro ao enviar mensagem broadcast websocket: %v", err)+ continue+ }+ }++ return nil+}++// CreateGlobalQueues não faz nada para websocket producer+func (p *websocketProducer) CreateGlobalQueues() error {+ return nil+}diff --git a/pkg/group/handler/group_handler.go b/pkg/group/handler/group_handler.gonew file mode 100644index 0000000..4136266--- /dev/null+++ b/pkg/group/handler/group_handler.go@@ -0,0 +1,486 @@+package group_handler++import (+ "net/http"++ group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ "github.com/gin-gonic/gin"+)++type GroupHandler interface {+ ListGroups(ctx *gin.Context)+ GetGroupInfo(ctx *gin.Context)+ GetGroupInviteLink(ctx *gin.Context)+ SetGroupPhoto(ctx *gin.Context)+ SetGroupName(ctx *gin.Context)+ SetGroupDescription(ctx *gin.Context)+ CreateGroup(ctx *gin.Context)+ UpdateParticipant(ctx *gin.Context)+ GetMyGroups(ctx *gin.Context)+ JoinGroupLink(ctx *gin.Context)+ LeaveGroup(ctx *gin.Context)+}++type groupHandler struct {+ groupService group_service.GroupService+}++// List groups+// @Summary List groups+// @Description List groups+// @Tags Group+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/list [get]+func (g *groupHandler) ListGroups(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ resp, err := g.groupService.ListGroups(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Get group info+// @Summary Get group info+// @Description Get group info+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.GetGroupInfoStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/info [post]+func (g *groupHandler) GetGroupInfo(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.GetGroupInfoStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})+ return+ }++ resp, err := g.groupService.GetGroupInfo(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Get group invite link+// @Summary Get group invite link+// @Description Get group invite link+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.GetGroupInviteLinkStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/invitelink [post]+func (g *groupHandler) GetGroupInviteLink(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.GetGroupInviteLinkStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})+ return+ }++ resp, err := g.groupService.GetGroupInviteLink(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Set group photo+// @Summary Set group photo+// @Description Set group photo+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.SetGroupPhotoStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/photo [post]+func (g *groupHandler) SetGroupPhoto(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.SetGroupPhotoStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})+ return+ }++ if data.Image == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})+ return+ }++ resp, err := g.groupService.SetGroupPhoto(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Set group name+// @Summary Set group name+// @Description Set group name+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.SetGroupNameStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/name [post]+func (g *groupHandler) SetGroupName(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.SetGroupNameStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ err = g.groupService.SetGroupName(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Set group description+// @Summary Set group description+// @Description Set group description+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.SetGroupDescriptionStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/description [post]+func (g *groupHandler) SetGroupDescription(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.SetGroupDescriptionStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJID is required"})+ return+ }++ // Description can be empty to clear the group description+ // No validation needed for Description field++ err = g.groupService.SetGroupDescription(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Create group+// @Summary Create group+// @Description Create group+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.CreateGroupStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/create [post]+func (g *groupHandler) CreateGroup(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.CreateGroupStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupName == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupName is required"})+ return+ }++ if len(data.Participants) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})+ return+ }++ group, err := g.groupService.CreateGroup(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": group})+}++// Update participant+// @Summary Update participant+// @Description Update participant+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.AddParticipantStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/participant [post]+func (g *groupHandler) UpdateParticipant(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.AddParticipantStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID.String() == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})+ return+ }++ if data.Action == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})+ return+ }++ if len(data.Participants) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "participants are required"})+ return+ }++ err = g.groupService.UpdateParticipant(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Get my groups+// @Summary Get my groups+// @Description Get my groups+// @Tags Group+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/myall [get]+func (g *groupHandler) GetMyGroups(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ groups, err := g.groupService.GetMyGroups(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": groups})+}++// Join group link+// @Summary Join group link+// @Description Join group link+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.JoinGroupStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/join [post]+func (g *groupHandler) JoinGroupLink(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.JoinGroupStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Code == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})+ return+ }++ err = g.groupService.JoinGroupLink(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Leave group+// @Summary Leave group+// @Description Leave group+// @Tags Group+// @Accept json+// @Produce json+// @Param message body group_service.LeaveGroupStruct true "Group data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /group/leave [post]+func (g *groupHandler) LeaveGroup(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *group_service.LeaveGroupStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.GroupJID.String() == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})+ return+ }++ err = g.groupService.LeaveGroup(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++func NewGroupHandler(+ groupService group_service.GroupService,+) GroupHandler {+ return &groupHandler{+ groupService: groupService,+ }+}diff --git a/pkg/group/service/group_service.go b/pkg/group/service/group_service.gonew file mode 100644index 0000000..227fef2--- /dev/null+++ b/pkg/group/service/group_service.go@@ -0,0 +1,654 @@+package group_service++import (+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "github.com/gin-gonic/gin"+ "github.com/vincent-petithory/dataurl"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+)++type GroupService interface {+ ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error)+ GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error)+ GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error)+ SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error)+ SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error+ SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error+ CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error)+ UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error+ UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error+ GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error)+ UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error)+ GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error)+ JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error+ LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error+}++type groupService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type SimpleGroupInfo struct {+ JID types.JID `json:"jid"`+ GroupName string `json:"groupName"`+}++type GroupCollection struct {+ Groups []SimpleGroupInfo+}++type GetGroupInfoStruct struct {+ GroupJID string `json:"groupJid"`+}++type GetGroupInviteLinkStruct struct {+ GroupJID string `json:"groupJid"`+ Reset bool `json:"reset"`+}++type SetGroupPhotoStruct struct {+ GroupJID string `json:"groupJid"`+ Image string `json:"image"`+}++type SetGroupNameStruct struct {+ GroupJID string `json:"groupJid"`+ Name string `json:"name"`+}++type SetGroupDescriptionStruct struct {+ GroupJID string `json:"groupJid"`+ Description string `json:"description"`+}++type CreateGroupStruct struct {+ GroupName string `json:"groupName"`+ Participants []string `json:"participants"`+}++type AddParticipantStruct struct {+ GroupJID types.JID `json:"groupJid"`+ Participants []string `json:"participants"`+ Action whatsmeow.ParticipantChange `json:"action"`+}++type JoinGroupStruct struct {+ Code string `json:"code"`+}++type LeaveGroupStruct struct {+ GroupJID types.JID `json:"groupJid"`+}++type UpdateGroupSettingsStruct struct {+ GroupJID string `json:"groupJid"`+ Action string `json:"action"` // announcement, not_announcement, locked, unlocked+}++type GetGroupRequestParticipantsStruct struct {+ GroupJID string `json:"groupJid"`+}++// Estrutura enriquecida com PushName+type EnrichedGroupParticipantRequest struct {+ JID types.JID `json:"JID"`+ RequestedAt time.Time `json:"RequestedAt"`+ PushName string `json:"PushName"`+}++type UpdateGroupRequestParticipantsStruct struct {+ GroupJID string `json:"groupJid"`+ Action string `json:"action"` // approve, reject+ Participants []string `json:"participants"`+}+++func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := g.clientPointer[instanceId]+ g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := g.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = g.clientPointer[instanceId]+ g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ g.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ g.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (g *groupService) ListGroups(instance *instance_model.Instance) ([]*types.GroupInfo, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ resp, err := client.GetJoinedGroups(context.Background())+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting groups: %v", instance.Id, err)+ return nil, err+ }++ gc := new(GroupCollection)+ for _, info := range resp {+ simpleGroup := SimpleGroupInfo{+ JID: info.JID,+ GroupName: info.GroupName.Name,+ }+ gc.Groups = append(gc.Groups, simpleGroup)+ }++ return resp, nil+}++func (g *groupService) GetGroupInfo(data *GetGroupInfoStruct, instance *instance_model.Instance) (*types.GroupInfo, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return nil, errors.New("invalid group jid")+ }++ resp, err := client.GetGroupInfo(context.Background(), recipient)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)+ return nil, err+ }++ return resp, nil+}++func (g *groupService) GetGroupInviteLink(data *GetGroupInviteLinkStruct, instance *instance_model.Instance) (string, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid group jid")+ }++ resp, err := client.GetGroupInviteLink(context.Background(), recipient, data.Reset)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error mute chat: %v", instance.Id, err)+ return "", err+ }++ return resp, nil+}++func (g *groupService) SetGroupPhoto(data *SetGroupPhotoStruct, instance *instance_model.Instance) (string, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid group jid")+ }++ var fileData []byte++ if strings.HasPrefix(data.Image, "http://") || strings.HasPrefix(data.Image, "https://") {+ resp, err := http.Get(data.Image)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not download image from URL", instance.Id)+ return "", fmt.Errorf("failed to fetch image from URL: %v", err)+ }+ defer resp.Body.Close()++ fileData, err = io.ReadAll(resp.Body)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not read image data from URL", instance.Id)+ return "", fmt.Errorf("failed to read image data: %v", err)+ }++ } else if strings.HasPrefix(data.Image, "data:image/jpeg;base64,") || strings.HasPrefix(data.Image, "data:image/png;base64,") {+ dataURL, err := dataurl.DecodeString(data.Image)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not decode base64 encoded data from payload", instance.Id)+ return "", err+ }+ fileData = dataURL.Data+ } else {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Image data should start with \"data:image/jpeg;base64,\" or be a valid URL", instance.Id)+ return "", errors.New("image data should be a valid URL or start with \"data:image/jpeg;base64,\"")+ }++ pictureID, err := client.SetGroupPhoto(context.Background(), recipient, fileData)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error setting group photo: %v", instance.Id, err)+ return "", err+ }++ return pictureID, nil+}++func (g *groupService) SetGroupName(data *SetGroupNameStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return errors.New("invalid group jid")+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group name for %s", instance.Id, recipient.String())++ err = client.SetGroupName(context.Background(), recipient, data.Name)+ if err != nil {+ // Log mais detalhado para erro 409+ if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {+ g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting name. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)+ }+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group name: %v", instance.Id, err)+ return err+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group name set successfully", instance.Id)+ return nil+}++func (g *groupService) SetGroupDescription(data *SetGroupDescriptionStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return errors.New("invalid group jid")+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Attempting to set group description for %s", instance.Id, recipient.String())++ // Use SetGroupTopic instead of SetGroupDescription (proper WhatsApp method)+ // Empty strings for previousID and newID will be auto-filled by the library+ err = client.SetGroupTopic(context.Background(), recipient, "", "", data.Description)+ if err != nil {+ // Log mais detalhado para erro 409+ if strings.Contains(err.Error(), "409") || strings.Contains(err.Error(), "conflict") {+ g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] WhatsApp returned 409 conflict when setting description. This usually means: rate limit, duplicate content, or insufficient permissions", instance.Id)+ }+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error setting group description: %v", instance.Id, err)+ return err+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group description set successfully", instance.Id)+ return nil+}++func (g *groupService) CreateGroup(data *CreateGroupStruct, instance *instance_model.Instance) (gin.H, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ var participants []types.JID+ for _, participant := range data.Participants {+ recipient, ok := utils.ParseJID(participant)+ participants = append(participants, recipient)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return nil, errors.New("invalid phone number")+ }+ }++ resp, err := client.CreateGroup(context.Background(), whatsmeow.ReqCreateGroup{+ Name: data.GroupName,+ Participants: participants,+ })+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)+ return nil, err+ }++ var failed []types.JID+ for _, participant := range resp.Participants {+ if participant.Error != 0 {+ failed = append(failed, participant.JID)+ }+ }++ var added []types.JID+ infoResp, err := client.GetGroupInfo(context.Background(), resp.JID)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error get group info: %v", instance.Id, err)+ return nil, err+ }+ for _, add := range infoResp.Participants {+ added = append(added, add.JID)+ }++ response := gin.H{+ "jid": resp.JID,+ "name": resp.Name,+ "owner": resp.OwnerJID,+ "added": added,+ "failed": failed,+ }++ return response, nil+}++func (g *groupService) UpdateParticipant(data *AddParticipantStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ var participants []types.JID+ for _, participant := range data.Participants {+ recipient, ok := utils.ParseJID(participant)+ participants = append(participants, recipient)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return errors.New("invalid phone number")+ }+ }++ _, err = client.UpdateGroupParticipants(context.Background(), data.GroupJID, participants, data.Action)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)+ return err+ }++ return nil+}++func (g *groupService) GetMyGroups(instance *instance_model.Instance) ([]types.GroupInfo, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ resp, err := client.GetJoinedGroups(context.Background())+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)+ return nil, err+ }++ var jid string = client.Store.ID.String()+ var jidClear = strings.Split(jid, ".")[0]+ jidOfAdmin, ok := utils.ParseJID(jidClear)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return nil, errors.New("invalid phone number")+ }+ var adminGroups []types.GroupInfo+ for _, group := range resp {+ if group.OwnerJID == jidOfAdmin {+ adminGroups = append(adminGroups, *group)+ _ = adminGroups+ }+ }++ return adminGroups, nil+}++func (g *groupService) JoinGroupLink(data *JoinGroupStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ _, err = client.JoinGroupWithLink(context.Background(), data.Code)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create group: %v", instance.Id, err)+ return err+ }++ return nil+}++func (g *groupService) LeaveGroup(data *LeaveGroupStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ err = client.LeaveGroup(context.Background(), data.GroupJID)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error leave group: %v", instance.Id, err)+ return err+ }++ return nil+}++func (g *groupService) UpdateGroupSettings(data *UpdateGroupSettingsStruct, instance *instance_model.Instance) error {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)+ return errors.New("invalid group jid")+ }++ // Validate action+ validActions := map[string]bool{+ "announcement": true,+ "not_announcement": true,+ "locked": true,+ "unlocked": true,+ "approval_on": true,+ "approval_off": true,+ "admin_add": true,+ "all_member_add": true,+ }++ if !validActions[data.Action] {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)+ return errors.New("invalid action. Valid actions: announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add")+ }++ // Apply settings based on action+ switch data.Action {+ case "announcement":+ err = client.SetGroupAnnounce(context.Background(), recipient, true)+ case "not_announcement":+ err = client.SetGroupAnnounce(context.Background(), recipient, false)+ case "locked":+ err = client.SetGroupLocked(context.Background(), recipient, true)+ case "unlocked":+ err = client.SetGroupLocked(context.Background(), recipient, false)+ case "approval_on":+ err = client.SetGroupJoinApprovalMode(context.Background(), recipient, true)+ case "approval_off":+ err = client.SetGroupJoinApprovalMode(context.Background(), recipient, false)+ case "admin_add":+ err = client.SetGroupMemberAddMode(context.Background(), recipient, "admin_add")+ case "all_member_add":+ err = client.SetGroupMemberAddMode(context.Background(), recipient, "all_member_add")+ }++ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group settings: %v", instance.Id, err)+ return err+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Group settings updated successfully: %s", instance.Id, data.Action)+ return nil+}++func (g *groupService) GetGroupRequestParticipants(data *GetGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]EnrichedGroupParticipantRequest, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)+ return nil, errors.New("invalid group jid")+ }++ requests, err := client.GetGroupRequestParticipants(context.Background(), recipient)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error getting group request participants: %v", instance.Id, err)+ return nil, err+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Retrieved %d pending group requests", instance.Id, len(requests))++ // Enriquecer com informações de usuário (PushName)+ enrichedRequests := make([]EnrichedGroupParticipantRequest, len(requests))+ jidsToFetch := make([]types.JID, 0, len(requests))++ for _, req := range requests {+ if req.JID.User != "" {+ jidsToFetch = append(jidsToFetch, req.JID)+ }+ }++ // Buscar informações de usuário em lote+ userInfoMap := make(map[types.JID]types.UserInfo)+ if len(jidsToFetch) > 0 {+ userInfoMap, err = client.GetUserInfo(context.Background(), jidsToFetch)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Could not fetch user info: %v", instance.Id, err)+ // Continuar sem pushName se falhar+ }+ }++ // Montar resposta enriquecida+ for i, req := range requests {+ enrichedRequests[i] = EnrichedGroupParticipantRequest{+ JID: req.JID,+ RequestedAt: req.RequestedAt,+ PushName: "",+ }++ // Tentar obter PushName+ lookupJID := req.JID++ if userInfo, found := userInfoMap[lookupJID]; found {+ // VerifiedName é ponteiro, verificar se não é nil+ if userInfo.VerifiedName != nil && userInfo.VerifiedName.Details.GetVerifiedName() != "" {+ enrichedRequests[i].PushName = userInfo.VerifiedName.Details.GetVerifiedName()+ }+ }++ // Tentar obter do store de contatos se não tiver VerifiedName+ if enrichedRequests[i].PushName == "" && client.Store.Contacts != nil {+ if contactInfo, err := client.Store.Contacts.GetContact(context.Background(), lookupJID); err == nil && contactInfo.PushName != "" {+ enrichedRequests[i].PushName = contactInfo.PushName+ } else if contactInfo.FullName != "" {+ enrichedRequests[i].PushName = contactInfo.FullName+ }+ }+ }++ return enrichedRequests, nil+}++func (g *groupService) UpdateGroupRequestParticipants(data *UpdateGroupRequestParticipantsStruct, instance *instance_model.Instance) ([]types.GroupParticipant, error) {+ client, err := g.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ recipient, ok := utils.ParseJID(data.GroupJID)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating group jid", instance.Id)+ return nil, errors.New("invalid group jid")+ }++ // Validate action+ var action whatsmeow.ParticipantRequestChange+ switch data.Action {+ case "approve":+ action = whatsmeow.ParticipantChangeApprove+ case "reject":+ action = whatsmeow.ParticipantChangeReject+ default:+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Invalid action: %s", instance.Id, data.Action)+ return nil, errors.New("invalid action. Valid actions: approve, reject")+ }++ // Parse participants JIDs+ var participants []types.JID+ for _, participant := range data.Participants {+ participantJID, ok := utils.ParseJID(participant)+ if !ok {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating participant jid: %s", instance.Id, participant)+ return nil, errors.New("invalid participant jid: " + participant)+ }+ participants = append(participants, participantJID)+ }++ results, err := client.UpdateGroupRequestParticipants(context.Background(), recipient, participants, action)+ if err != nil {+ g.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error updating group request participants: %v", instance.Id, err)+ return nil, err+ }++ g.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Successfully %sd %d participants", instance.Id, data.Action, len(participants))+ return results, nil+}++func NewGroupService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) GroupService {+ return &groupService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/instance/handler/instance_handler.go b/pkg/instance/handler/instance_handler.gonew file mode 100644index 0000000..ebf8406--- /dev/null+++ b/pkg/instance/handler/instance_handler.go@@ -0,0 +1,644 @@+package instance_handler++import (+ "net/http"+ "time"++ "github.com/gin-gonic/gin"++ config "github.com/EvolutionAPI/evolution-go/pkg/config"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"+)++type InstanceHandler interface {+ Create(ctx *gin.Context)+ Connect(ctx *gin.Context)+ Reconnect(ctx *gin.Context)+ Disconnect(ctx *gin.Context)+ Logout(ctx *gin.Context)+ Delete(ctx *gin.Context)+ Status(ctx *gin.Context)+ Qr(ctx *gin.Context)+ All(ctx *gin.Context)+ Info(ctx *gin.Context)+ Pair(ctx *gin.Context)+ SetProxy(ctx *gin.Context)+ DeleteProxy(ctx *gin.Context)+ ForceReconnect(ctx *gin.Context)+ GetLogs(ctx *gin.Context)+ GetAdvancedSettings(ctx *gin.Context)+ UpdateAdvancedSettings(ctx *gin.Context)+}++type instanceHandler struct {+ config *config.Config+ instanceService instance_service.InstanceService+}++// Create a new instance+// @Summary Create a new instance+// @Description Creates a new instance with the provided data including optional advanced settings+// @Tags Instance+// @Accept json+// @Produce json+// @Param instance body instance_service.CreateStruct true "Instance data with optional advanced settings"+// @Success 200 {object} gin.H "Instance created successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/create [post]+func (i *instanceHandler) Create(ctx *gin.Context) {+ var data *instance_service.CreateStruct+ err := ctx.ShouldBindJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ if data.Token == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})+ return+ }++ if data.Proxy != nil {+ if data.Proxy.Port == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy port is required"})+ return+ }++ if data.Proxy.Password == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy password is required"})+ return+ }++ if data.Proxy.Username == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy username is required"})+ return+ }++ if data.Proxy.Host == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "proxy host is required"})+ return+ }+ } else {+ if i.config.ProxyHost != "" && i.config.ProxyPort != "" && i.config.ProxyUsername != "" && i.config.ProxyPassword != "" {+ data.Proxy = &instance_service.ProxyConfig{+ Host: i.config.ProxyHost,+ Port: i.config.ProxyPort,+ Username: i.config.ProxyUsername,+ Password: i.config.ProxyPassword,+ }+ }+ }++ createdInstance, err := i.instanceService.Create(data)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": createdInstance})+}++// Connect to instance+// @Summary Connect to instance+// @Description Connect to instance with the provided data+// @Tags Instance+// @Accept json+// @Produce json+// @Param instance body instance_service.ConnectStruct true "Instance data"+// @Success 200 {object} gin.H "Instance connected successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/connect [post]+func (i *instanceHandler) Connect(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *instance_service.ConnectStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ instance, jid, eventString, err := i.instanceService.Connect(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.Set("instance", instance)++ responseData := gin.H{+ "jid": jid,+ "webhookUrl": instance.Webhook,+ "eventString": eventString,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Reconnect to instance+// @Summary Reconnect to instance+// @Description Reconnect to instance+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "Instance reconnected successfully"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/reconnect [post]+func (i *instanceHandler) Reconnect(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ err := i.instanceService.Reconnect(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Disconnect from instance+// @Summary Disconnect from instance+// @Description Disconnect from instance+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "Instance disconnected successfully"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/disconnect [post]+func (i *instanceHandler) Disconnect(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ updateInstance, err := i.instanceService.Disconnect(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.Set("instance", updateInstance)++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Logout from instance+// @Summary Logout from instance+// @Description Logout from instance+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "Instance logged out successfully"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/logout [delete]+func (i *instanceHandler) Logout(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})+ return+ }++ updateInstance, err := i.instanceService.Logout(instance)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.Set("instance", updateInstance)++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Get instance status+// @Summary Get instance status+// @Description Get instance status+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "Instance status"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/status [get]+func (i *instanceHandler) Status(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})+ return+ }++ status, err := i.instanceService.Status(instance)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": status})+}++// Get instance QR code+// @Summary Get instance QR code+// @Description Get instance QR code+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "Instance QR code"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/qr [get]+func (i *instanceHandler) Qr(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "instance not found"})+ return+ }++ qrcode, err := i.instanceService.GetQr(instance)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": qrcode})+}++// Request pairing code+// @Summary Request pairing code+// @Description Request pairing code+// @Tags Instance+// @Accept json+// @Produce json+// @Param instance body instance_service.PairStruct true "Instance data"+// @Success 200 {object} gin.H "Pairing code"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/pair [post]+func (i *instanceHandler) Pair(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *instance_service.PairStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Phone == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone is required"})+ return+ }++ pairingCode, err := i.instanceService.Pair(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pairingCode})+}++// Get all instances+// @Summary Get all instances+// @Description Get all instances+// @Tags Instance+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "All instances"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/all [get]+func (i *instanceHandler) All(ctx *gin.Context) {+ instances, err := i.instanceService.GetAll()+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instances})+}++// Get instance+// @Summary Get instance+// @Description Get instance+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance Id"+// @Success 200 {object} gin.H "Instance"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/get/{instanceId} [get]+func (i *instanceHandler) Info(ctx *gin.Context) {+ instanceId := ctx.Param("instanceId")++ if instanceId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ instance, err := i.instanceService.Info(instanceId)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": instance})+}++// Delete instance+// @Summary Delete instance+// @Description Delete instance+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance Id"+// @Success 200 {object} gin.H "Instance deleted successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/delete/{instanceId} [delete]+func (i *instanceHandler) Delete(ctx *gin.Context) {+ instanceId := ctx.Param("instanceId")++ if instanceId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ err := i.instanceService.Delete(instanceId)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Set proxy+// @Summary Set proxy configuration+// @Description Set proxy configuration for an instance+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance id"+// @Param proxy body instance_service.SetProxyStruct true "Proxy configuration"+// @Success 200 {object} gin.H "Proxy set successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/proxy/{instanceId} [post]+func (i *instanceHandler) SetProxy(ctx *gin.Context) {+ instanceId := ctx.Param("instanceId")++ if instanceId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ var data *instance_service.SetProxyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Validate required fields+ if data.Host == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "host is required"})+ return+ }++ if data.Port == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "port is required"})+ return+ }++ err = i.instanceService.SetProxyFromStruct(instanceId, data)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "host": data.Host,+ "port": data.Port,+ "hasAuth": data.Username != "" && data.Password != "",+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Delete proxy+// @Summary Delete proxy+// @Description Delete proxy+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance id"+// @Success 200 {object} gin.H "Proxy deleted successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/proxy/{instanceId} [delete]+func (i *instanceHandler) DeleteProxy(ctx *gin.Context) {+ instanceId := ctx.Param("instanceId")++ if instanceId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})+ return+ }++ err := i.instanceService.RemoveProxy(instanceId)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Force reconnect+// @Summary Force reconnect+// @Description Force reconnect+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance Id"+// @Param instance body instance_service.ForceReconnectStruct true "Instance data"+// @Success 200 {object} gin.H "Instance force reconnected successfully"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/forcereconnect/{instanceId} [post]+func (i *instanceHandler) ForceReconnect(ctx *gin.Context) {+ instanceId := ctx.Param("instanceId")++ if instanceId == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ var data *instance_service.ForceReconnectStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ var number string+ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "number is required"})+ return+ }++ number = data.Number++ err = i.instanceService.ForceReconnect(instanceId, number)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++type GetLogsQuery struct {+ StartDate string `form:"start_date"`+ EndDate string `form:"end_date"`+ Level string `form:"level"`+ Limit int `form:"limit"`+}++func (h *instanceHandler) GetLogs(c *gin.Context) {+ instanceId := c.Param("instanceId")++ var query GetLogsQuery+ if err := c.ShouldBindQuery(&query); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Converte as datas+ startDate, err := time.Parse("2006-01-02", query.StartDate)+ if err != nil {+ startDate = time.Now().AddDate(0, 0, -7) // Default: 7 dias atrás+ }++ endDate, err := time.Parse("2006-01-02", query.EndDate)+ if err != nil {+ endDate = time.Now()+ }++ // Ajusta o endDate para o final do dia+ endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)++ if query.Limit == 0 {+ query.Limit = 100 // Default: 100 registros+ }++ logs, err := h.instanceService.GetLogs(instanceId, startDate, endDate, query.Level, query.Limit)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, logs)+}++// GetAdvancedSettings retrieves advanced settings for an instance+// @Summary Get advanced settings+// @Description Get advanced settings for a specific instance+// @Tags Instance+// @Produce json+// @Param instanceId path string true "Instance ID"+// @Success 200 {object} instance_model.AdvancedSettings "Advanced settings retrieved successfully"+// @Failure 400 {object} gin.H "Invalid instance ID"+// @Failure 404 {object} gin.H "Instance not found"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/{instanceId}/advanced-settings [get]+func (h *instanceHandler) GetAdvancedSettings(c *gin.Context) {+ instanceId := c.Param("instanceId")++ if instanceId == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ settings, err := h.instanceService.GetAdvancedSettings(instanceId)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, settings)+}++// UpdateAdvancedSettings updates advanced settings for an instance+// @Summary Update advanced settings+// @Description Update advanced settings for a specific instance+// @Tags Instance+// @Accept json+// @Produce json+// @Param instanceId path string true "Instance ID"+// @Param settings body instance_model.AdvancedSettings true "Advanced settings data"+// @Success 200 {object} gin.H "Advanced settings updated successfully"+// @Failure 400 {object} gin.H "Invalid request data"+// @Failure 404 {object} gin.H "Instance not found"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /instance/{instanceId}/advanced-settings [put]+func (h *instanceHandler) UpdateAdvancedSettings(c *gin.Context) {+ instanceId := c.Param("instanceId")++ if instanceId == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "instanceId is required"})+ return+ }++ var settings instance_model.AdvancedSettings+ if err := c.ShouldBindJSON(&settings); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ err := h.instanceService.UpdateAdvancedSettings(instanceId, &settings)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "message": "Advanced settings updated successfully",+ "settings": settings,+ })+}++func NewInstanceHandler(instanceService instance_service.InstanceService, config *config.Config) InstanceHandler {+ return &instanceHandler{instanceService: instanceService, config: config}+}diff --git a/pkg/instance/model/instance_model.go b/pkg/instance/model/instance_model.gonew file mode 100644index 0000000..3fe8186--- /dev/null+++ b/pkg/instance/model/instance_model.go@@ -0,0 +1,53 @@+package instance_model++import (+ "time"++ "github.com/google/uuid"+ "gorm.io/gorm"+)++type Instance struct {+ Id string `json:"id" gorm:"type:uuid;primaryKey"`+ Name string `json:"name"`+ Token string `json:"token" gorm:"unique"`+ Webhook string `json:"webhook"`+ RabbitmqEnable string `json:"rabbitmqEnable"`+ WebSocketEnable string `json:"websocketEnable"`+ NatsEnable string `json:"natsEnable"`+ Jid string `json:"jid" gorm:"column:jid"`+ Qrcode string `json:"qrcode" gorm:"type:text"`+ Connected bool `json:"connected"`+ Expiration int64 `json:"expiration"`+ DisconnectReason string `json:"disconnect_reason"`+ Events string `json:"events"`+ OsName string `json:"os_name"`+ Proxy string `json:"proxy"`+ ClientName string `json:"client_name"`+ CreatedAt time.Time `json:"createdAt" gorm:"autoCreateTime"`++ // Advanced Settings+ AlwaysOnline bool `json:"alwaysOnline" gorm:"default:false"`+ RejectCall bool `json:"rejectCall" gorm:"default:false"`+ MsgRejectCall string `json:"msgRejectCall" gorm:"default:''"`+ ReadMessages bool `json:"readMessages" gorm:"default:false"`+ IgnoreGroups bool `json:"ignoreGroups" gorm:"default:false"`+ IgnoreStatus bool `json:"ignoreStatus" gorm:"default:false"`+}++// AdvancedSettings representa as configurações avançadas de uma instância+type AdvancedSettings struct {+ AlwaysOnline bool `json:"alwaysOnline"`+ RejectCall bool `json:"rejectCall"`+ MsgRejectCall string `json:"msgRejectCall"`+ ReadMessages bool `json:"readMessages"`+ IgnoreGroups bool `json:"ignoreGroups"`+ IgnoreStatus bool `json:"ignoreStatus"`+}++func (m *Instance) BeforeCreate(tx *gorm.DB) (err error) {+ if m.Id == "" {+ m.Id = uuid.New().String()+ }+ return+}diff --git a/pkg/instance/repository/instance_repository.go b/pkg/instance/repository/instance_repository.gonew file mode 100644index 0000000..cfb60b4--- /dev/null+++ b/pkg/instance/repository/instance_repository.go@@ -0,0 +1,223 @@+package instance_repository++import (+ "fmt"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ "github.com/gomessguii/logger"+ "github.com/google/uuid"+ "gorm.io/gorm"++ label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"+ label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"++ message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"+ message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"+)++type InstanceRepository interface {+ Create(instance instance_model.Instance) (*instance_model.Instance, error)+ GetInstanceByID(instanceId string) (*instance_model.Instance, error)+ GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error)+ GetInstanceByToken(token string) (*instance_model.Instance, error)+ GetInstanceByName(name string) (*instance_model.Instance, error)+ Update(*instance_model.Instance) error+ UpdateConnected(userId string, status bool, disconnectReason string) error+ UpdateQrcode(userId string, qr string) error+ UpdateProxy(userId string, proxy string) error+ UpdateJid(userId string, jid string) error+ GetAllConnectedInstances() ([]*instance_model.Instance, error)+ GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error)+ GetAll(clientName string) ([]*instance_model.Instance, error)+ Delete(instanceId string) error+ GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)+ UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error+}++type instanceRepository struct {+ db *gorm.DB+ labelRepo label_repository.LabelRepository+ messageRepo message_repository.MessageRepository+}++func (i *instanceRepository) Create(instance instance_model.Instance) (*instance_model.Instance, error) {+ if err := i.db.Create(&instance).Error; err != nil {+ return nil, err+ }+ return &instance, nil+}++func (i *instanceRepository) GetInstanceByToken(token string) (*instance_model.Instance, error) {+ var instance instance_model.Instance+ err := i.db.Where("token = ?", token).First(&instance).Error+ if err != nil {+ return nil, err+ }++ return &instance, nil+}++func (i *instanceRepository) GetInstanceByName(name string) (*instance_model.Instance, error) {+ var instance instance_model.Instance+ err := i.db.Where("name = ?", name).First(&instance).Error+ if err != nil {+ return nil, err+ }++ return &instance, nil+}++func (i *instanceRepository) GetInstanceByID(instanceId string) (*instance_model.Instance, error) {+ // Valida o formato do UUID+ if _, err := uuid.Parse(instanceId); err != nil {+ return nil, fmt.Errorf("invalid UUID format: %v", err)+ }++ var instance instance_model.Instance+ err := i.db.Where("id = ?", instanceId).First(&instance).Error+ if err != nil {+ return nil, err+ }++ return &instance, nil+}++func (i *instanceRepository) GetConnectedInstanceByID(instanceId string) (*instance_model.Instance, error) {+ var instance instance_model.Instance+ err := i.db.Where("id = ? AND connected = ?", instanceId, true).First(&instance).Error+ if err != nil {+ return nil, err+ }++ return &instance, nil+}++func (i *instanceRepository) Update(instance *instance_model.Instance) error {+ err := i.db.Save(&instance).Error+ if err != nil {+ logger.LogError("Error updating instance in DB: %v", err)+ }+ return err+}++func (i *instanceRepository) UpdateConnected(userId string, status bool, disconnectReason string) error {+ return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("connected", status).Update("disconnect_reason", disconnectReason).Error+}++func (i *instanceRepository) UpdateQrcode(userId string, qr string) error {+ return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("qrcode", qr).Error+}++func (i *instanceRepository) UpdateProxy(userId string, proxy string) error {+ return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("proxy", proxy).Error+}++func (i *instanceRepository) UpdateJid(userId string, jid string) error {+ return i.db.Model(&instance_model.Instance{}).Where("id = ?", userId).Update("jid", jid).Error+}++func (i *instanceRepository) GetAllConnectedInstances() ([]*instance_model.Instance, error) {+ var instances []*instance_model.Instance+ err := i.db.Where("connected = ?", true).Find(&instances).Error+ if err != nil {+ return nil, err+ }++ return instances, nil+}++func (i *instanceRepository) GetAllConnectedInstancesByClientName(clientName string) ([]*instance_model.Instance, error) {+ var instances []*instance_model.Instance+ err := i.db.Where("connected = ? AND client_name = ?", true, clientName).Find(&instances).Error+ if err != nil {+ return nil, err+ }++ return instances, nil+}++func (i *instanceRepository) GetAll(clientName string) ([]*instance_model.Instance, error) {+ var instances []*instance_model.Instance+ err := i.db.Where("client_name = ?", clientName).Find(&instances).Error+ if err != nil {+ return nil, err+ }++ return instances, nil+}++func (i *instanceRepository) Delete(instanceId string) error {+ return i.db.Transaction(func(tx *gorm.DB) error {+ // Deleta todas as labels associadas à instância+ if err := tx.Where("instance_id = ?", instanceId).Delete(&label_model.Label{}).Error; err != nil {+ return fmt.Errorf("erro ao deletar labels: %v", err)+ }++ // Deleta todas as mensagens associadas à instância+ if err := tx.Where("source = ?", instanceId).Delete(&message_model.Message{}).Error; err != nil {+ return fmt.Errorf("erro ao deletar mensagens: %v", err)+ }++ // Deleta a instância+ if err := tx.Where("id = ?", instanceId).Delete(&instance_model.Instance{}).Error; err != nil {+ return fmt.Errorf("erro ao deletar instância: %v", err)+ }++ return nil+ })+}++func (i *instanceRepository) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {+ // Valida o formato do UUID+ if _, err := uuid.Parse(instanceId); err != nil {+ return nil, fmt.Errorf("invalid UUID format: %v", err)+ }++ var instance instance_model.Instance+ err := i.db.Select("always_online, reject_call, msg_reject_call, read_messages, ignore_groups, ignore_status").+ Where("id = ?", instanceId).First(&instance).Error+ if err != nil {+ return nil, err+ }++ settings := &instance_model.AdvancedSettings{+ AlwaysOnline: instance.AlwaysOnline,+ RejectCall: instance.RejectCall,+ MsgRejectCall: instance.MsgRejectCall,+ ReadMessages: instance.ReadMessages,+ IgnoreGroups: instance.IgnoreGroups,+ IgnoreStatus: instance.IgnoreStatus,+ }++ return settings, nil+}++func (i *instanceRepository) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {+ // Valida o formato do UUID+ if _, err := uuid.Parse(instanceId); err != nil {+ return fmt.Errorf("invalid UUID format: %v", err)+ }++ updates := map[string]interface{}{+ "always_online": settings.AlwaysOnline,+ "reject_call": settings.RejectCall,+ "msg_reject_call": settings.MsgRejectCall,+ "read_messages": settings.ReadMessages,+ "ignore_groups": settings.IgnoreGroups,+ "ignore_status": settings.IgnoreStatus,+ }++ err := i.db.Model(&instance_model.Instance{}).Where("id = ?", instanceId).Updates(updates).Error+ if err != nil {+ logger.LogError("Error updating advanced settings in DB: %v", err)+ return err+ }++ return nil+}++func NewInstanceRepository(db *gorm.DB) InstanceRepository {+ return &instanceRepository{+ db: db,+ }+}diff --git a/pkg/instance/service/instance_service.go b/pkg/instance/service/instance_service.gonew file mode 100644index 0000000..32d831e--- /dev/null+++ b/pkg/instance/service/instance_service.go@@ -0,0 +1,854 @@+package instance_service++import (+ "bufio"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "slices"+ "sort"+ "strings"+ "time"++ "github.com/EvolutionAPI/evolution-go/pkg/config"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"+ event_types "github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+)++type InstanceService interface {+ Create(data *CreateStruct) (*instance_model.Instance, error)+ Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error)+ Reconnect(instance *instance_model.Instance) error+ Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error)+ Logout(instance *instance_model.Instance) (*instance_model.Instance, error)+ Status(instance *instance_model.Instance) (*StatusStruct, error)+ GetQr(instance *instance_model.Instance) (*QrcodeStruct, error)+ Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error)+ GetAll() ([]*instance_model.Instance, error)+ Info(instanceId string) (*instance_model.Instance, error)+ Delete(id string) error+ SetProxy(id string, proxyConfig *ProxyConfig) error+ SetProxyFromStruct(id string, data *SetProxyStruct) error+ RemoveProxy(id string) error+ ForceReconnect(instanceId string, number string) error+ GetInstanceByToken(token string) (*instance_model.Instance, error)+ GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error)+ GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error)+ UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error+}++type instances struct {+ instanceRepository instance_repository.InstanceRepository+ config *config.Config+ killChannel map[string](chan bool)+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type ProxyConfig struct {+ Port string `json:"port"`+ Password string `json:"password"`+ Username string `json:"username"`+ Host string `json:"host"`+}++type CreateStruct struct {+ InstanceId string `json:"instanceId"`+ Name string `json:"name"`+ Token string `json:"token"`+ Proxy *ProxyConfig `json:"proxy"`+ AdvancedSettings *instance_model.AdvancedSettings `json:"advancedSettings"`+}++type ConnectStruct struct {+ WebhookUrl string `json:"webhookUrl"`+ Subscribe []string `json:"subscribe"`+ Immediate bool `json:"immediate"`+ Phone string `json:"phone"`+ RabbitmqEnable string `json:"rabbitmqEnable"`+ WebSocketEnable string `json:"websocketEnable"`+ NatsEnable string `json:"natsEnable"`+}++type StatusStruct struct {+ Connected bool+ LoggedIn bool+ myJid *types.JID+ Name string+}++type QrcodeStruct struct {+ Qrcode string+ Code string+}++type PairStruct struct {+ Subscribe []string `json:"subscribe"`+ Phone string `json:"phone"`+}++type PairReturnStruct struct {+ PairingCode string+}++type SetProxyStruct struct {+ Host string `json:"host" validate:"required"`+ Port string `json:"port" validate:"required"`+ Username string `json:"username"`+ Password string `json:"password"`+}++type ForceReconnectStruct struct {+ Number string `json:"number"`+}++func (i *instances) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ logger := i.loggerWrapper.GetLogger(instanceId)+ client := i.clientPointer[instanceId]+ logger.LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ logger.LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := i.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ logger.LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ logger.LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = i.clientPointer[instanceId]+ logger.LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ logger.LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ logger.LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ logger.LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (i instances) Create(data *CreateStruct) (*instance_model.Instance, error) {+ proxyJson, err := json.Marshal(data.Proxy)+ if err != nil {+ return nil, err+ }++ findInstance, _ := i.instanceRepository.GetInstanceByName(data.Name)++ if findInstance != nil {+ return nil, fmt.Errorf("instance already exists")+ }++ instance := instance_model.Instance{+ Id: data.InstanceId,+ Name: data.Name,+ Token: data.Token,+ OsName: i.config.OsName,+ Proxy: string(proxyJson),+ Connected: false,+ ClientName: i.config.ClientName,+ }++ // Set advanced settings if provided+ if data.AdvancedSettings != nil {+ instance.AlwaysOnline = data.AdvancedSettings.AlwaysOnline+ instance.RejectCall = data.AdvancedSettings.RejectCall+ instance.MsgRejectCall = data.AdvancedSettings.MsgRejectCall+ instance.ReadMessages = data.AdvancedSettings.ReadMessages+ instance.IgnoreGroups = data.AdvancedSettings.IgnoreGroups+ instance.IgnoreStatus = data.AdvancedSettings.IgnoreStatus+ }++ createdInstance, err := i.instanceRepository.Create(instance)+ if err != nil {+ return nil, err+ }++ return createdInstance, nil+}++func (i instances) Connect(data *ConnectStruct, instance *instance_model.Instance) (*instance_model.Instance, string, string, error) {+ var subscribedEvents []string++ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Processing subscribe events: %v", instance.Id, data.Subscribe)++ if len(data.Subscribe) == 0 {+ subscribedEvents = append(subscribedEvents, event_types.MESSAGE)+ } else if len(data.Subscribe) > 0 && data.Subscribe[0] == "ALL" {+ for _, event := range event_types.AllEventTypes {+ subscribedEvents = append(subscribedEvents, event)+ }+ } else {+ for _, arg := range data.Subscribe {+ if !event_types.IsEventType(arg) {+ i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Message type discarded '%s'", instance.Id, arg)+ continue+ }+ subscribedEvents = append(subscribedEvents, arg)+ }+ }++ eventString := strings.Join(subscribedEvents, ",")++ instance.Events = eventString+ instance.Webhook = data.WebhookUrl+ instance.RabbitmqEnable = data.RabbitmqEnable+ instance.NatsEnable = data.NatsEnable+ instance.WebSocketEnable = data.WebSocketEnable++ err := i.instanceRepository.Update(instance)+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error updating instance: %s", instance.Id, err)+ return nil, "", "", err+ }++ // Verifica se a instância já está rodando+ isInstanceRunning := i.clientPointer[instance.Id] != nil++ // Sincroniza as configurações na instância em execução (se já estiver conectada)+ err = i.whatsmeowService.UpdateInstanceSettings(instance.Id)+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance not in runtime yet, will be updated when connected", instance.Id)+ isInstanceRunning = false+ } else {+ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance settings updated successfully in runtime", instance.Id)+ isInstanceRunning = true+ }++ // Se a instância não estiver rodando, inicia uma nova+ if !isInstanceRunning {+ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting new client instance", instance.Id)++ i.killChannel[instance.Id] = make(chan bool)++ clientData := &whatsmeow_service.ClientData{+ Instance: instance,+ Subscriptions: subscribedEvents,+ Phone: data.Phone,+ IsProxy: false,+ }++ if instance.Proxy != "" || i.config.ProxyHost != "" {+ var proxyConfig ProxyConfig+ err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)+ return nil, "", "", err+ }++ if proxyConfig.Host != "" || i.config.ProxyHost != "" {+ clientData.IsProxy = true+ }+ }++ go i.whatsmeowService.StartClient(clientData)+ } else {+ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Instance already running, settings updated without restarting client", instance.Id)+ }++ // logger.LogInfo("Waiting 1 seconds")+ // time.Sleep(1000 * time.Millisecond)++ // if i.clientPointer[instance.Id] != nil {+ // if !i.clientPointer[instance.Id].IsConnected() {+ // return instance, "", "", fmt.Errorf("failed to connect")+ // }+ // } else {+ // return instance, "", "", fmt.Errorf("failed to connect")+ // }++ return instance, instance.Jid, eventString, nil+}++func (i instances) Reconnect(instance *instance_model.Instance) error {+ _, err := i.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ return i.whatsmeowService.ReconnectClient(instance.Id)+}++func (i instances) Disconnect(instance *instance_model.Instance) (*instance_model.Instance, error) {+ client, err := i.ensureClientConnected(instance.Id)+ if err != nil {+ return instance, err+ }++ if client.IsConnected() {+ if client.IsLoggedIn() {+ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)+ i.killChannel[instance.Id] <- true++ instance.Events = ""++ err := i.instanceRepository.Update(instance)+ if err != nil {+ return instance, err+ }++ return instance, nil+ }+ }++ i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring disconnect as it was not connected", instance.Id)+ return instance, nil+}++func (i instances) Logout(instance *instance_model.Instance) (*instance_model.Instance, error) {+ client, err := i.ensureClientConnected(instance.Id)+ if err != nil {+ return instance, err+ }++ if client.IsLoggedIn() && client.IsConnected() {+ err := client.Logout(context.Background())+ if err != nil {+ return instance, err+ }++ instance.Connected = false+ err = i.instanceRepository.Update(instance)+ if err != nil {+ return instance, err+ }++ select {+ case i.killChannel[instance.Id] <- true:+ case <-time.After(5 * time.Second):+ }++ delete(i.clientPointer, instance.Id)+ delete(i.killChannel, instance.Id)++ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Logout successful", instance.Id)+ return instance, nil+ }++ if client.IsConnected() {+ client.Disconnect()++ select {+ case i.killChannel[instance.Id] <- true:+ case <-time.After(5 * time.Second):+ }++ delete(i.clientPointer, instance.Id)+ delete(i.killChannel, instance.Id)++ i.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Disconnection successful", instance.Id)+ return instance, nil+ }++ i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Ignoring logout as it was not connected", instance.Id)+ return instance, fmt.Errorf("ignoring logout as it was not connected")+}++func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {+ client, err := i.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ isConnected := client.IsConnected()+ isLoggedIn := client.IsLoggedIn()++ var myJid *types.JID+ var name string+ if isLoggedIn {+ myJid = client.Store.ID+ name = client.Store.PushName+ }++ status := &StatusStruct{+ Connected: isConnected,+ LoggedIn: isLoggedIn,+ myJid: myJid,+ Name: name,+ }++ return status, nil+}++func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {+ logger := i.loggerWrapper.GetLogger(instance.Id)+ client := i.clientPointer[instance.Id]++ // Se não há cliente ou o cliente está logado, precisamos iniciar um novo cliente+ if client == nil || client.IsLoggedIn() {+ if client != nil && client.IsLoggedIn() {+ logger.LogInfo("[%s] Client is logged in, starting new instance for QR code", instance.Id)+ } else {+ logger.LogInfo("[%s] No client found, starting new instance for QR code", instance.Id)+ }++ // Iniciar nova instância para gerar QR code+ err := i.whatsmeowService.StartInstance(instance.Id)+ if err != nil {+ logger.LogError("[%s] Failed to start instance: %v", instance.Id, err)+ return nil, fmt.Errorf("failed to start instance: %w", err)+ }++ // Aguardar um pouco para o cliente iniciar e gerar QR code+ logger.LogInfo("[%s] Waiting for QR code generation...", instance.Id)+ time.Sleep(3 * time.Second)++ // Verificar novamente se há cliente+ client = i.clientPointer[instance.Id]+ if client != nil && client.IsLoggedIn() {+ return nil, fmt.Errorf("session already logged in")+ }+ } else if !client.IsConnected() {+ // Se o cliente existe mas não está conectado, pode estar aguardando QR code+ logger.LogInfo("[%s] Client exists but not connected, checking for existing QR code", instance.Id)+ }++ // Buscar instância atualizada do banco para pegar o QR code mais recente+ instance, err := i.instanceRepository.GetInstanceByID(instance.Id)+ if err != nil {+ return nil, err+ }++ code := instance.Qrcode+ if code == "" {+ // Se não há QR code ainda, aguardar um pouco mais e tentar novamente+ logger.LogInfo("[%s] No QR code available yet, waiting a bit more...", instance.Id)+ time.Sleep(2 * time.Second)++ instance, err = i.instanceRepository.GetInstanceByID(instance.Id)+ if err != nil {+ return nil, err+ }++ code = instance.Qrcode+ if code == "" {+ return nil, fmt.Errorf("no QR code available. Please wait a moment and try again")+ }+ }++ parts := strings.Split(code, "|")+ if len(parts) < 2 {+ return nil, fmt.Errorf("invalid QR code format")+ }++ qr := &QrcodeStruct{+ Qrcode: parts[0],+ Code: parts[1],+ }++ return qr, nil+}++func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {+ code, err := i.clientPointer[instance.Id].PairPhone(context.Background(), data.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] something went wrong calling pair phone", instance.Id)+ }++ return &PairReturnStruct{PairingCode: code}, nil+}++func (i instances) GetAll() ([]*instance_model.Instance, error) {+ instances, err := i.instanceRepository.GetAll(i.config.ClientName)+ if err != nil {+ return nil, err+ }++ for _, instance := range instances {+ if client := i.clientPointer[instance.Id]; client != nil {+ instance.Connected = client.IsLoggedIn()+ } else {+ instance.Connected = false+ }++ instance.Proxy = ""+ }++ return instances, nil+}++func (i instances) Info(instanceId string) (*instance_model.Instance, error) {+ instance, err := i.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ return nil, err+ }++ // Atualiza o status connected com base no estado real do cliente+ if client := i.clientPointer[instance.Id]; client != nil {+ instance.Connected = client.IsLoggedIn()+ } else {+ instance.Connected = false+ }++ instance.Proxy = ""++ return instance, nil+}++func (i instances) Delete(id string) error {+ instance, err := i.instanceRepository.GetInstanceByID(id)+ if err != nil {+ return err+ }++ if i.clientPointer[instance.Id] != nil && i.clientPointer[instance.Id].IsConnected() {+ if i.clientPointer[instance.Id].IsLoggedIn() {+ i.clientPointer[instance.Id].Logout(context.Background())+ }+ i.clientPointer[instance.Id].Disconnect()+ }++ // Limpar todos os recursos da instância antes de deletar+ delete(i.clientPointer, instance.Id)+ if i.killChannel[instance.Id] != nil {+ close(i.killChannel[instance.Id])+ delete(i.killChannel, instance.Id)+ }++ // Limpar cache via whatsmeow service+ err = i.whatsmeowService.ClearInstanceCache(instance.Id, instance.Token)+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to clear instance cache: %v", instance.Id, err)+ }++ err = i.instanceRepository.Delete(id)+ if err != nil {+ return err+ }++ return nil+}++func (i instances) SetProxy(id string, proxyConfig *ProxyConfig) error {+ instance, err := i.instanceRepository.GetInstanceByID(id)+ if err != nil {+ return err+ }++ // Validate proxy configuration+ if proxyConfig == nil {+ return fmt.Errorf("proxy configuration cannot be nil")+ }++ if proxyConfig.Host == "" {+ return fmt.Errorf("proxy host is required")+ }++ if proxyConfig.Port == "" {+ return fmt.Errorf("proxy port is required")+ }++ // Convert proxy config to JSON+ proxyJSON, err := json.Marshal(proxyConfig)+ if err != nil {+ i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to marshal proxy config: %v", id, err)+ return fmt.Errorf("failed to marshal proxy configuration: %v", err)+ }++ instance.Proxy = string(proxyJSON)++ // Update instance in database+ err = i.instanceRepository.Update(instance)+ if err != nil {+ i.loggerWrapper.GetLogger(id).LogError("[%s] Failed to update instance with proxy: %v", id, err)+ return err+ }++ i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration updated: %s:%s", id, proxyConfig.Host, proxyConfig.Port)++ // Reconnect to apply proxy changes+ go i.Reconnect(instance)++ return nil+}++func (i instances) SetProxyFromStruct(id string, data *SetProxyStruct) error {+ if data == nil {+ return fmt.Errorf("proxy data cannot be nil")+ }++ proxyConfig := &ProxyConfig{+ Host: data.Host,+ Port: data.Port,+ Username: data.Username,+ Password: data.Password,+ }++ return i.SetProxy(id, proxyConfig)+}++func (i instances) RemoveProxy(id string) error {+ instance, err := i.instanceRepository.GetInstanceByID(id)+ if err != nil {+ return err+ }++ instance.Proxy = ""++ err = i.instanceRepository.Update(instance)+ if err != nil {+ return err+ }++ i.loggerWrapper.GetLogger(id).LogInfo("[%s] Proxy configuration removed", id)++ go i.Reconnect(instance)++ return nil+}++func (i instances) ForceReconnect(instanceId string, number string) error {+ if i.clientPointer[instanceId].IsConnected() && i.clientPointer[instanceId].IsLoggedIn() {+ return fmt.Errorf("client already connected")+ }++ err := i.whatsmeowService.ForceUpdateJid(instanceId, number)+ if err != nil {+ return err+ }++ instance, err := i.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ return err+ }++ subscribedEvents := strings.Split(instance.Events, ",")++ i.killChannel[instance.Id] = make(chan bool)++ clientData := &whatsmeow_service.ClientData{+ Instance: instance,+ Subscriptions: subscribedEvents,+ Phone: "",+ IsProxy: false,+ }++ if instance.Proxy != "" || i.config.ProxyHost != "" {+ var proxyConfig ProxyConfig+ err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)+ if err != nil {+ i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error unmarshalling proxy config: %v", instance.Id, err)+ return err+ }++ if proxyConfig.Host != "" || i.config.ProxyHost != "" {+ clientData.IsProxy = true+ }+ }++ if i.clientPointer[instance.Id] != nil {+ client := i.clientPointer[instance.Id]+ client.Disconnect()++ select {+ case i.killChannel[instance.Id] <- true:+ case <-time.After(5 * time.Second):+ }++ delete(i.clientPointer, instance.Id)+ delete(i.killChannel, instance.Id)+ }++ go i.whatsmeowService.StartClient(clientData)++ time.Sleep(2 * time.Second)++ if i.clientPointer[instance.Id] != nil {+ if !i.clientPointer[instance.Id].IsConnected() {+ return fmt.Errorf("failed to connect")+ }++ if !i.clientPointer[instance.Id].IsLoggedIn() {+ return fmt.Errorf("failed to login")+ }+ } else {+ return fmt.Errorf("failed to connect")+ }++ return nil+}++func (i instances) GetInstanceByToken(token string) (*instance_model.Instance, error) {+ return i.instanceRepository.GetInstanceByToken(token)+}++func (i instances) GetLogs(instanceId string, startDate, endDate time.Time, level string, limit int) ([]logger_wrapper.LogEntry, error) {+ // Inicializa o slice vazio para garantir que nunca retorne null+ logs := make([]logger_wrapper.LogEntry, 0)++ // Define valores padrão+ if limit <= 0 {+ limit = 100 // Limite padrão de 100 registros+ }++ // Se não foi fornecida data inicial, usa 7 dias atrás+ if startDate.IsZero() {+ startDate = time.Now().AddDate(0, 0, -7)+ }++ // Se não foi fornecida data final, usa data atual+ if endDate.IsZero() {+ endDate = time.Now()+ }++ // Ajusta as datas para início e fim do dia+ startDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.UTC)+ endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 23, 59, 59, 999999999, time.UTC)++ // Garante que a data inicial não seja posterior à data final+ if startDate.After(endDate) {+ return logs, fmt.Errorf("data inicial não pode ser posterior à data final")+ }++ // Níveis de log válidos+ validLevels := map[string]bool{+ "INFO": true,+ "ERROR": true,+ "WARN": true,+ "DEBUG": true,+ }++ var levelArray []string+ if level == "" {+ // Se nenhum nível foi especificado, usa todos+ levelArray = []string{"INFO", "ERROR", "WARN", "DEBUG"}+ } else {+ // Divide e normaliza os níveis fornecidos+ for _, l := range strings.Split(level, ",") {+ l = strings.TrimSpace(strings.ToUpper(l))+ if !validLevels[l] {+ return logs, fmt.Errorf("nível de log inválido: %s", l)+ }+ levelArray = append(levelArray, l)+ }+ }++ // Lê os logs do arquivo+ logPath := filepath.Join(i.config.LogDirectory, instanceId, "instance.log")+ file, err := os.Open(logPath)+ if err != nil {+ if os.IsNotExist(err) {+ return logs, nil // Retorna array vazio se arquivo não existir+ }+ return logs, fmt.Errorf("erro ao abrir arquivo de log: %v", err)+ }+ defer file.Close()++ scanner := bufio.NewScanner(file)++ // Aumenta o buffer do scanner para lidar com linhas grandes+ const maxCapacity = 1024 * 1024 // 1MB+ buf := make([]byte, maxCapacity)+ scanner.Buffer(buf, maxCapacity)++ for scanner.Scan() {+ var entry logger_wrapper.LogEntry+ if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {+ continue // Ignora linhas inválidas+ }++ // Ajusta o timestamp da entrada para UTC para comparação correta+ entry.Timestamp = entry.Timestamp.UTC()++ // Aplica os filtros+ if entry.Timestamp.Before(startDate) || entry.Timestamp.After(endDate) {+ continue+ }++ if !slices.Contains(levelArray, entry.Level) {+ continue+ }++ logs = append(logs, entry)++ // Verifica o limite+ if len(logs) >= limit {+ break+ }+ }++ if err := scanner.Err(); err != nil {+ return logs, fmt.Errorf("erro ao ler arquivo de log: %v", err)+ }++ // Ordena os logs por timestamp em ordem decrescente+ sort.Slice(logs, func(i, j int) bool {+ return logs[i].Timestamp.After(logs[j].Timestamp)+ })++ return logs, nil+}++func (i instances) GetAdvancedSettings(instanceId string) (*instance_model.AdvancedSettings, error) {+ i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Getting advanced settings", instanceId)++ settings, err := i.instanceRepository.GetAdvancedSettings(instanceId)+ if err != nil {+ i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting advanced settings: %v", instanceId, err)+ return nil, err+ }++ return settings, nil+}++func (i instances) UpdateAdvancedSettings(instanceId string, settings *instance_model.AdvancedSettings) error {+ i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updating advanced settings", instanceId)++ err := i.instanceRepository.UpdateAdvancedSettings(instanceId, settings)+ if err != nil {+ i.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error updating advanced settings: %v", instanceId, err)+ return err+ }++ // Sincroniza as configurações na instância em execução+ err = i.whatsmeowService.UpdateInstanceAdvancedSettings(instanceId)+ if err != nil {+ i.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Error syncing advanced settings to runtime: %v", instanceId, err)+ // Não falha a operação, apenas loga o warning+ }++ i.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Advanced settings updated successfully", instanceId)+ return nil+}++func NewInstanceService(+ instanceRepository instance_repository.InstanceRepository,+ killChannel map[string](chan bool),+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ config *config.Config,+ loggerWrapper *logger_wrapper.LoggerManager,+) InstanceService {+ return &instances{+ instanceRepository: instanceRepository,+ killChannel: killChannel,+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ config: config,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/internal/event_types/event_types.go b/pkg/internal/event_types/event_types.gonew file mode 100644index 0000000..5ff8f87--- /dev/null+++ b/pkg/internal/event_types/event_types.go@@ -0,0 +1,55 @@+package event_types++const (+ ALL = "ALL"+ MESSAGE = "MESSAGE"+ SEND_MESSAGE = "SEND_MESSAGE"+ READ_RECEIPT = "READ_RECEIPT"+ PRESENCE = "PRESENCE"+ HISTORY_SYNC = "HISTORY_SYNC"+ CHAT_PRESENCE = "CHAT_PRESENCE"+ CALL = "CALL"+ CONNECTION = "CONNECTION"+ LABEL = "LABEL"+ CONTACT = "CONTACT"+ GROUP = "GROUP"+ NEWSLETTER = "NEWSLETTER"+ QRCODE = "QRCODE"+)++var AllEventTypes = []string{+ MESSAGE,+ SEND_MESSAGE,+ READ_RECEIPT,+ PRESENCE,+ HISTORY_SYNC,+ CHAT_PRESENCE,+ CALL,+ CONNECTION,+ LABEL,+ CONTACT,+ GROUP,+ NEWSLETTER,+ QRCODE,+}++var validEventTypes = map[string]bool{+ ALL: true,+ MESSAGE: true,+ SEND_MESSAGE: true,+ READ_RECEIPT: true,+ PRESENCE: true,+ HISTORY_SYNC: true,+ CHAT_PRESENCE: true,+ CALL: true,+ CONNECTION: true,+ LABEL: true,+ CONTACT: true,+ GROUP: true,+ NEWSLETTER: true,+ QRCODE: true,+}++func IsEventType(eventType string) bool {+ return validEventTypes[eventType]+}diff --git a/pkg/label/handler/label_handler.go b/pkg/label/handler/label_handler.gonew file mode 100644index 0000000..009d3a3--- /dev/null+++ b/pkg/label/handler/label_handler.go@@ -0,0 +1,297 @@+package label_handler++import (+ "net/http"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"+ "github.com/gin-gonic/gin"+)++type LabelHandler interface {+ ChatLabel(ctx *gin.Context)+ MessageLabel(ctx *gin.Context)+ EditLabel(ctx *gin.Context)+ ChatUnlabel(ctx *gin.Context)+ MessageUnlabel(ctx *gin.Context)+ GetLabels(ctx *gin.Context)+}++type labelHandler struct {+ labelService label_service.LabelService+}++// Add label to chat+// @Summary Add label to chat+// @Description Add label to chat+// @Tags Label+// @Accept json+// @Produce json+// @Param message body label_service.ChatLabelStruct true "Label data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /label/chat [post]+func (l *labelHandler) ChatLabel(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *label_service.ChatLabelStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ if data.LabelID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})+ return+ }++ err = l.labelService.ChatLabel(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Add label to message+// @Summary Add label to message+// @Description Add label to message+// @Tags Label+// @Accept json+// @Produce json+// @Param message body label_service.MessageLabelStruct true "Label data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /label/message [post]+func (l *labelHandler) MessageLabel(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *label_service.MessageLabelStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ if data.LabelID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})+ return+ }++ if data.MessageID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})+ return+ }++ err = l.labelService.MessageLabel(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Edit label+// @Summary Edit label+// @Description Edit label+// @Tags Label+// @Accept json+// @Produce json+// @Param message body label_service.EditLabelStruct true "Label data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /label/edit [post]+func (l *labelHandler) EditLabel(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *label_service.EditLabelStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.LabelID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ err = l.labelService.EditLabel(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Remove label from chat+// @Summary Remove label from chat+// @Description Remove label from chat+// @Tags Label+// @Accept json+// @Produce json+// @Param message body label_service.ChatLabelStruct true "Label data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /unlabel/chat [post]+func (l *labelHandler) ChatUnlabel(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *label_service.ChatLabelStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ if data.LabelID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})+ return+ }++ err = l.labelService.ChatUnlabel(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Remove label from message+// @Summary Remove label from message+// @Description Remove label from message+// @Tags Label+// @Accept json+// @Produce json+// @Param message body label_service.MessageLabelStruct true "Label data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /unlabel/message [post]+func (l *labelHandler) MessageUnlabel(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *label_service.MessageLabelStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ if data.LabelID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "label id is required"})+ return+ }++ if data.MessageID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message id is required"})+ return+ }++ err = l.labelService.MessageUnlabel(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Get all labels+// @Summary Get all labels+// @Description Get all labels+// @Tags Label+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /label [get]+func (l *labelHandler) GetLabels(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ labels, err := l.labelService.GetLabels(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, labels)+}++func NewLabelHandler(+ labelService label_service.LabelService,+) LabelHandler {+ return &labelHandler{+ labelService: labelService,+ }+}diff --git a/pkg/label/model/label_model.go b/pkg/label/model/label_model.gonew file mode 100644index 0000000..e47fb22--- /dev/null+++ b/pkg/label/model/label_model.go@@ -0,0 +1,20 @@+package label_model++import (+ "github.com/google/uuid"+ "gorm.io/gorm"+)++type Label struct {+ Id string `json:"id" gorm:"type:uuid;primaryKey"`+ InstanceID string `json:"instance_id" gorm:"type:uuid"`+ LabelID string `json:"label_id"`+ LabelName string `json:"label_name"`+ LabelColor string `json:"label_color"`+ PredefinedId string `json:"predefined_id"`+}++func (m *Label) BeforeCreate(tx *gorm.DB) (err error) {+ m.Id = uuid.New().String()+ return+}diff --git a/pkg/label/repository/label_repository.go b/pkg/label/repository/label_repository.gonew file mode 100644index 0000000..5853632--- /dev/null+++ b/pkg/label/repository/label_repository.go@@ -0,0 +1,71 @@+package label_repository++import (+ label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++type LabelRepository interface {+ InsertLabel(label label_model.Label) error+ UpdateLabel(label label_model.Label) error+ GetLabelByID(id string) (*label_model.Label, error)+ DeleteLabel(id string) error+ GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error)+ UpsertLabel(label label_model.Label) error+}++type labelRepository struct {+ db *gorm.DB+}++func (l *labelRepository) InsertLabel(label label_model.Label) error {+ return l.db.Create(&label).Error+}++func (l *labelRepository) UpdateLabel(label label_model.Label) error {+ return l.db.Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "id"}},+ DoUpdates: clause.AssignmentColumns([]string{"label_id", "label_name", "label_color"}),+ }).Create(&label).Error+}++func (l *labelRepository) GetLabelByID(id string) (*label_model.Label, error) {+ var label label_model.Label+ err := l.db.Where("id = ?", id).First(&label).Error+ if err != nil {+ if err == gorm.ErrRecordNotFound {+ return nil, nil+ }+ return nil, err+ }+ return &label, nil+}++func (l *labelRepository) DeleteLabel(id string) error {+ return l.db.Where("id = ?", id).Delete(&label_model.Label{}).Error+}++func (l *labelRepository) GetAllLabelsByInstanceID(instanceID string) ([]label_model.Label, error) {+ var labels []label_model.Label+ err := l.db.Where("instance_id = ?", instanceID).Find(&labels).Error+ if err != nil {+ return nil, err+ }+ return labels, nil+}++func (l *labelRepository) UpsertLabel(label label_model.Label) error {+ return l.db.Where("instance_id = ? AND label_id = ?",+ label.InstanceID,+ label.LabelID,+ ).Assign(label_model.Label{+ LabelName: label.LabelName,+ LabelColor: label.LabelColor,+ PredefinedId: label.PredefinedId,+ }).FirstOrCreate(&label).Error+}++func NewLabelRepository(db *gorm.DB) LabelRepository {+ return &labelRepository{db: db}+}diff --git a/pkg/label/service/label_service.go b/pkg/label/service/label_service.gonew file mode 100644index 0000000..570db46--- /dev/null+++ b/pkg/label/service/label_service.go@@ -0,0 +1,240 @@+package label_service++import (+ "context"+ "errors"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"+ label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/appstate"+)++type LabelService interface {+ ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error+ MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error+ EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error+ ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error+ MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error+ GetLabels(instance *instance_model.Instance) ([]label_model.Label, error)+}++type labelService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ labelRepository label_repository.LabelRepository+ loggerWrapper *logger_wrapper.LoggerManager+}++type ChatLabelStruct struct {+ JID string `json:"jid"`+ LabelID string `json:"labelId"`+}++type MessageLabelStruct struct {+ JID string `json:"jid"`+ LabelID string `json:"labelId"`+ MessageID string `json:"messageId"`+}++type EditLabelStruct struct {+ LabelID string `json:"labelId"`+ Name string `json:"name"`+ Color int `json:"color"`+ Deleted bool `json:"deleted"`+}++func (l *labelService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := l.clientPointer[instanceId]+ l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := l.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = l.clientPointer[instanceId]+ l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ l.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ l.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ l.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (l *labelService) ChatLabel(data *ChatLabelStruct, instance *instance_model.Instance) error {+ client, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ jid, ok := utils.ParseJID(data.JID)+ if !ok {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return errors.New("error parse community jid")+ }++ err = client.SendAppState(context.Background(), appstate.BuildLabelChat(+ jid,+ data.LabelID,+ true,+ ))+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)+ return err+ }++ return nil+}++func (l *labelService) MessageLabel(data *MessageLabelStruct, instance *instance_model.Instance) error {+ client, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ jid, ok := utils.ParseJID(data.JID)+ if !ok {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return errors.New("error parse community jid")+ }++ err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(+ jid,+ data.LabelID,+ data.MessageID,+ true,+ ))+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)+ return err+ }++ return nil+}++func (l *labelService) EditLabel(data *EditLabelStruct, instance *instance_model.Instance) error {+ client, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ err = client.SendAppState(context.Background(), appstate.BuildLabelEdit(+ data.LabelID,+ data.Name,+ int32(data.Color),+ data.Deleted,+ ))+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)+ return err+ }++ return nil+}++func (l *labelService) ChatUnlabel(data *ChatLabelStruct, instance *instance_model.Instance) error {+ client, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ jid, ok := utils.ParseJID(data.JID)+ if !ok {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return errors.New("error parse community jid")+ }++ err = client.SendAppState(context.Background(), appstate.BuildLabelChat(+ jid,+ data.LabelID,+ false,+ ))+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label chat: %v", instance.Id, err)+ return err+ }++ return nil+}++func (l *labelService) MessageUnlabel(data *MessageLabelStruct, instance *instance_model.Instance) error {+ client, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ jid, ok := utils.ParseJID(data.JID)+ if !ok {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error parse community jid", instance.Id)+ return errors.New("error parse community jid")+ }++ err = client.SendAppState(context.Background(), appstate.BuildLabelMessage(+ jid,+ data.LabelID,+ data.MessageID,+ false,+ ))+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error label message: %v", instance.Id, err)+ return err+ }++ return nil+}++func (l *labelService) GetLabels(instance *instance_model.Instance) ([]label_model.Label, error) {+ _, err := l.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ labels, err := l.labelRepository.GetAllLabelsByInstanceID(instance.Id)+ if err != nil {+ l.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error fetching labels from database: %v", instance.Id, err)+ return nil, err+ }++ return labels, nil+}++func NewLabelService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ labelRepository label_repository.LabelRepository,+ loggerWrapper *logger_wrapper.LoggerManager,+) LabelService {+ return &labelService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ labelRepository: labelRepository,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/logger/logger.go b/pkg/logger/logger.gonew file mode 100644index 0000000..1543568--- /dev/null+++ b/pkg/logger/logger.go@@ -0,0 +1,146 @@+package logger++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "sync"+ "time"++ "github.com/EvolutionAPI/evolution-go/pkg/config"+ "github.com/gomessguii/logger"+ "gopkg.in/natefinch/lumberjack.v2"+)++type LoggerManager struct {+ config *config.Config+ loggers map[string]*Logger+ mu sync.RWMutex+}++type Logger struct {+ config *config.Config+ instanceId string+ mu sync.Mutex+ writer *lumberjack.Logger+}++type LogEntry struct {+ Timestamp time.Time `json:"timestamp"`+ Level string `json:"level"`+ InstanceId string `json:"instance_id"`+ Message string `json:"message"`+ Metadata json.RawMessage `json:"metadata,omitempty"`+}++func NewLoggerManager(config *config.Config) *LoggerManager {+ // Garante que o diretório base de logs existe+ if err := os.MkdirAll(config.LogDirectory, 0755); err != nil {+ logger.LogError("Falha ao criar diretório base de logs: %v", err)+ }++ return &LoggerManager{+ config: config,+ loggers: make(map[string]*Logger),+ }+}++func (lm *LoggerManager) GetLogger(instanceId string) *Logger {+ lm.mu.RLock()+ logger, exists := lm.loggers[instanceId]+ lm.mu.RUnlock()++ if exists {+ return logger+ }++ lm.mu.Lock()+ defer lm.mu.Unlock()++ // Verificar novamente após obter o lock de escrita+ if logger, exists = lm.loggers[instanceId]; exists {+ return logger+ }++ // Criar novo logger para a instância+ logger = newLogger(instanceId, lm.config)+ lm.loggers[instanceId] = logger+ return logger+}++func newLogger(instanceId string, config *config.Config) *Logger {+ // Garante que o diretório existe+ logPath := filepath.Join(config.LogDirectory, instanceId)+ os.MkdirAll(logPath, 0755)++ logFile := filepath.Join(logPath, "instance.log")++ writer := &lumberjack.Logger{+ Filename: logFile,+ MaxSize: config.LogMaxSize,+ MaxBackups: config.LogMaxBackups,+ MaxAge: config.LogMaxAge,+ Compress: config.LogCompress,+ }++ return &Logger{+ config: config,+ instanceId: instanceId,+ writer: writer,+ }+}++func (l *Logger) LogInfo(format string, args ...interface{}) {+ l.log("INFO", format, args...)+ logger.LogInfo(format, args...)+}++func (l *Logger) LogError(format string, args ...interface{}) {+ l.log("ERROR", format, args...)+ logger.LogError(format, args...)+}++func (l *Logger) LogWarn(format string, args ...interface{}) {+ l.log("WARN", format, args...)+ logger.LogWarn(format, args...)+}++func (l *Logger) LogDebug(format string, args ...interface{}) {+ l.log("DEBUG", format, args...)+ logger.LogDebug(format, args...)+}++func (l *Logger) log(level string, format string, args ...interface{}) {+ l.mu.Lock()+ defer l.mu.Unlock()++ entry := LogEntry{+ Timestamp: time.Now(),+ Level: level,+ InstanceId: l.instanceId,+ Message: fmt.Sprintf(format, args...),+ }++ jsonEntry, err := json.Marshal(entry)+ if err != nil {+ logger.LogError("Failed to marshal log entry: %v", err)+ return+ }++ if _, err := l.writer.Write(append(jsonEntry, '\n')); err != nil {+ logger.LogError("Failed to write log: %v", err)+ }+}++func (l *Logger) Close() error {+ l.mu.Lock()+ defer l.mu.Unlock()+ return l.writer.Close()+}++// GetLogs retorna os logs da instância com filtros opcionais+func (l *Logger) GetLogs(startDate, endDate time.Time, level string, limit int) ([]LogEntry, error) {+ // Implementação movida para o service+ return nil, fmt.Errorf("método movido para instance_service")+}diff --git a/pkg/message/handler/message_handler.go b/pkg/message/handler/message_handler.gonew file mode 100644index 0000000..38fcdff--- /dev/null+++ b/pkg/message/handler/message_handler.go@@ -0,0 +1,371 @@+package message_handler++import (+ "net/http"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"+ "github.com/gin-gonic/gin"+)++type MessageHandler interface {+ React(ctx *gin.Context)+ ChatPresence(ctx *gin.Context)+ MarkRead(ctx *gin.Context)+ DownloadMedia(ctx *gin.Context)+ GetMessageStatus(ctx *gin.Context)+ DeleteMessageEveryone(ctx *gin.Context)+ EditMessage(ctx *gin.Context)+}++type messageHandler struct {+ messageService message_service.MessageService+}++// React a message+// @Summary React a message+// @Description React to a message with support for fromMe field and participant field for group messages+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.ReactStruct true "React to a message with fromMe and participant fields"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/react [post]+func (m *messageHandler) React(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.ReactStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Reaction == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message reaction is required"})+ return+ }++ message, err := m.messageService.React(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// ChatPresence set chat presence+// @Summary Set chat presence+// @Description Set chat presence+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.ChatPresenceStruct true "Set chat presence"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/presence [post]+func (m *messageHandler) ChatPresence(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.ChatPresenceStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.State == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "state is required"})+ return+ }++ ts, err := m.messageService.ChatPresence(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// MarkRead mark a message as read+// @Summary Mark a message as read+// @Description Mark a message as read+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.MarkReadStruct true "Mark a message as read"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/markread [post]+func (m *messageHandler) MarkRead(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.MarkReadStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if len(data.Id) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})+ return+ }++ ts, err := m.messageService.MarkRead(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// DownloadImage download an image+// @Summary Download an image+// @Description Download an image+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.DownloadImageStruct true "Download an image"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/downloadimage [post]+func (m *messageHandler) DownloadMedia(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.DownloadMediaStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ dataUrl, ts, err := m.messageService.DownloadMedia(data, instance, ctx.Request)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "base64": dataUrl.String(),+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// GetMessageStatus get message status+// @Summary Get message status+// @Description Get message status+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.MessageStatusStruct true "Get message status"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/status [post]+func (m *messageHandler) GetMessageStatus(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.MessageStatusStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Id == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})+ return+ }++ message, ts, err := m.messageService.GetMessageStatus(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "result": message,+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// DeleteMessageEveryone delete a message for everyone+// @Summary Delete a message for everyone+// @Description Delete a message for everyone+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.MessageStruct true "Delete a message for everyone"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/delete [post]+func (m *messageHandler) DeleteMessageEveryone(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.MessageStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ if data.MessageID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})+ return+ }++ msgId, ts, err := m.messageService.DeleteMessageEveryone(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "messageId": msgId,+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// EditMessage edit a message+// @Summary Edit a message+// @Description Edit a message+// @Tags Message+// @Accept json+// @Produce json+// @Param message body message_service.EditMessageStruct true "Edit a message"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /message/edit [post]+func (m *messageHandler) EditMessage(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *message_service.EditMessageStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Chat == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "chat is required"})+ return+ }++ if data.Message == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message is required"})+ return+ }++ if data.MessageID == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "messageId is required"})+ return+ }++ msgId, ts, err := m.messageService.EditMessage(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ responseData := gin.H{+ "messageId": msgId,+ "timestamp": ts,+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++func NewMessageHandler(+ messageService message_service.MessageService,+) MessageHandler {+ return &messageHandler{+ messageService: messageService,+ }+}diff --git a/pkg/message/model/message_model.go b/pkg/message/model/message_model.gonew file mode 100644index 0000000..3644ca5--- /dev/null+++ b/pkg/message/model/message_model.go@@ -0,0 +1,19 @@+package message_model++import (+ "github.com/google/uuid"+ "gorm.io/gorm"+)++type Message struct {+ Id string `json:"id" gorm:"type:uuid;primaryKey"`+ MessageID string `json:"message_id" gorm:"unique"`+ Timestamp string `json:"timestamp"`+ Status string `json:"status"`+ Source string `json:"source"`+}++func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {+ m.Id = uuid.New().String()+ return+}diff --git a/pkg/message/repository/message_repository.go b/pkg/message/repository/message_repository.gonew file mode 100644index 0000000..5a61ddb--- /dev/null+++ b/pkg/message/repository/message_repository.go@@ -0,0 +1,60 @@+package message_repository++import (+ message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++type MessageRepository interface {+ InsertMessage(message message_model.Message) error+ GetMessageByID(messageID string) (*message_model.Message, error)+ DeleteAllMessages() (int64, error)+ GetLatestMessageID(source string) (string, string, error)+}++type messageRepository struct {+ db *gorm.DB+}++func (m *messageRepository) InsertMessage(message message_model.Message) error {+ return m.db.Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "message_id"}},+ DoUpdates: clause.AssignmentColumns([]string{"timestamp", "status", "source"}),+ }).Create(&message).Error+}++func (m *messageRepository) GetMessageByID(messageID string) (*message_model.Message, error) {+ var message message_model.Message+ err := m.db.Where("message_id = ?", messageID).First(&message).Error+ if err != nil {+ if err == gorm.ErrRecordNotFound {+ return nil, nil+ }+ return nil, err+ }++ return &message, nil+}++func (m *messageRepository) DeleteAllMessages() (int64, error) {+ result := m.db.Exec("DELETE FROM messages")+ return result.RowsAffected, result.Error+}++func (m *messageRepository) GetLatestMessageID(source string) (string, string, error) {+ var message message_model.Message+ err := m.db.Where("source = ?", source).Order("timestamp DESC").First(&message).Error+ if err != nil {+ if err == gorm.ErrRecordNotFound {+ return "", "", nil+ }+ return "", "", err+ }++ return message.MessageID, message.Timestamp, nil+}++func NewMessageRepository(db *gorm.DB) MessageRepository {+ return &messageRepository{db: db}+}diff --git a/pkg/message/service/message_service.go b/pkg/message/service/message_service.gonew file mode 100644index 0000000..36ffb68--- /dev/null+++ b/pkg/message/service/message_service.go@@ -0,0 +1,440 @@+package message_service++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "os"+ "strings"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"+ message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "github.com/vincent-petithory/dataurl"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waCommon"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"+ "google.golang.org/protobuf/proto"+)++type MessageService interface {+ React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error)+ MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error)+ DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error)+ GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error)+ DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error)+ EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error)+}++type messageService struct {+ clientPointer map[string]*whatsmeow.Client+ messageRepository message_repository.MessageRepository+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type ReactStruct struct {+ Number string `json:"number"`+ Reaction string `json:"reaction"`+ Id string `json:"id"`+ FromMe bool `json:"fromMe"`+ Participant string `json:"participant,omitempty"`+}++type ChatPresenceStruct struct {+ Number string `json:"number"`+ State string `json:"state"`+ IsAudio bool `json:"isAudio"`+}++type MarkReadStruct struct {+ Id []string `json:"id"`+ Number string `json:"number"`+}++type DownloadMediaStruct struct {+ Message *waE2E.Message `json:"message"`+}++type MessageStatusStruct struct {+ Id string `json:"id"`+}++type MessageStruct struct {+ Chat string `json:"chat"`+ MessageID string `json:"messageId"`+}++type EditMessageStruct struct {+ Chat string `json:"chat"`+ Message string `json:"message"`+ MessageID string `json:"messageId"`+}++type MessageSendStruct struct {+ Info types.MessageInfo+ Message *waE2E.Message+ MessageContextInfo *waE2E.ContextInfo+}++func (m *messageService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := m.clientPointer[instanceId]+ m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := m.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = m.clientPointer[instanceId]+ m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ m.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ m.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ m.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (m *messageService) React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ msgId := ""++ recipient, ok := utils.ParseJID(data.Number)+ if !ok {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return nil, errors.New("invalid phone number")+ }++ if data.Id == "" {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Missing Id in Payload", instance.Id)+ return nil, errors.New("missing id in payload")+ } else {+ msgId = data.Id+ }++ fromMe := data.FromMe+ reaction := data.Reaction+ if reaction == "remove" {+ reaction = ""+ }++ // Create MessageKey+ messageKey := &waCommon.MessageKey{+ RemoteJID: proto.String(recipient.String()),+ FromMe: proto.Bool(fromMe),+ ID: proto.String(msgId),+ }++ // Add participant if provided (for group messages)+ if data.Participant != "" {+ participantJID, ok := utils.ParseJID(data.Participant)+ if ok {+ messageKey.Participant = proto.String(participantJID.String())+ }+ }++ msg := &waE2E.Message{+ ReactionMessage: &waE2E.ReactionMessage{+ Key: messageKey,+ Text: proto.String(reaction),+ // GroupingKey: proto.String(reaction),+ SenderTimestampMS: proto.Int64(time.Now().UnixMilli()),+ },+ }++ response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{+ ID: msgId,+ })+ if err != nil {+ return nil, err+ }++ isGroup := strings.Contains(data.Number, "@g.us")+ messageType := "ReactionMessage"++ messageInfo := types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: recipient,+ Sender: *client.Store.ID,+ IsFromMe: true,+ IsGroup: isGroup,+ },+ ID: msgId,+ Timestamp: time.Now(),+ ServerID: response.ServerID,+ Type: messageType,+ }++ messageSent := &MessageSendStruct{+ Info: messageInfo,+ Message: msg,+ }++ return messageSent, nil+}++func (m *messageService) ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Number)+ if !ok {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ media := ""++ if data.IsAudio {+ media = "audio"+ }++ err = client.SendChatPresence(context.Background(), recipient, types.ChatPresence(data.State), types.ChatPresenceMedia(media))+ if err != nil {+ return "", err+ }++ m.loggerWrapper.GetLogger(instance.Id).LogInfo("Message sent to %s", data.Number)++ return ts.String(), nil+}++func (m *messageService) MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return "", err+ }++ var ts time.Time++ jid, ok := utils.ParseJID(data.Number)+ if !ok {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", errors.New("invalid phone number")+ }++ err = client.MarkRead(context.Background(), data.Id, time.Now(), jid, jid)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error marking message as read: %v", instance.Id, err)+ return "", errors.New("error marking message as read")+ }++ return ts.String(), nil+}++func (m *messageService) DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, "", err+ }++ var ts time.Time++ msg := data.Message++ mimetype := ""+ var mediaData []byte++ img := msg.GetImageMessage()+ audio := msg.GetAudioMessage()+ document := msg.GetDocumentMessage()+ video := msg.GetVideoMessage()+ sticker := msg.GetStickerMessage()++ if img == nil && audio == nil && document == nil && video == nil && sticker == nil {+ return nil, "", errors.New("invalid media type")+ }++ userDirectory := fmt.Sprintf(`files/user_%s`, instance.Id)+ _, err = os.Stat(userDirectory)+ if os.IsNotExist(err) {+ errDir := os.MkdirAll(userDirectory, 0751)+ if errDir != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Could not create user directory (%s)", instance.Id, userDirectory)+ return nil, "", errDir+ }+ }++ if img != nil {+ mediaData, err = client.Download(context.Background(), img)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download image", instance.Id)+ msg := fmt.Sprintf("Failed to download image %v", err)+ return nil, "", errors.New(msg)+ }+ mimetype = img.GetMimetype()+ }++ if audio != nil {+ mediaData, err = client.Download(context.Background(), audio)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download audio", instance.Id)+ msg := fmt.Sprintf("Failed to download audio %v", err)+ return nil, "", errors.New(msg)+ }+ mimetype = audio.GetMimetype()+ }++ if document != nil {+ mediaData, err = client.Download(context.Background(), document)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download document", instance.Id)+ msg := fmt.Sprintf("Failed to download document %v", err)+ return nil, "", errors.New(msg)+ }+ mimetype = document.GetMimetype()+ }++ if video != nil {+ mediaData, err = client.Download(context.Background(), video)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download video", instance.Id)+ msg := fmt.Sprintf("Failed to download video %v", err)+ return nil, "", errors.New(msg)+ }+ mimetype = video.GetMimetype()+ }++ if sticker != nil {+ mediaData, err = client.Download(context.Background(), sticker)+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to download sticker", instance.Id)+ msg := fmt.Sprintf("Failed to download sticker %v", err)+ return nil, "", errors.New(msg)+ }+ mimetype = sticker.GetMimetype()+ }++ dataURL := dataurl.New(mediaData, mimetype)++ return dataURL, ts.String(), nil+}++func (m *messageService) GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error) {+ _, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, "", err+ }++ var ts time.Time++ result, err := m.messageRepository.GetMessageByID(data.Id)+ if err != nil {+ return nil, "", err+ }++ return result, ts.String(), nil+}++func (m *messageService) DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return "", "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", "", errors.New("invalid phone number")+ }++ m.loggerWrapper.GetLogger(instance.Id).LogInfo("Revoking message %s from %s", data.MessageID, recipient)++ resp, err := client.SendMessage(+ context.Background(),+ recipient,+ client.BuildRevoke(recipient, types.EmptyJID, data.MessageID))+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)+ return "", "", err+ }++ response := resp.ID++ return response, ts.String(), nil+}++func (m *messageService) EditMessage(data *EditMessageStruct, instance *instance_model.Instance) (string, string, error) {+ client, err := m.ensureClientConnected(instance.Id)+ if err != nil {+ return "", "", err+ }++ var ts time.Time++ recipient, ok := utils.ParseJID(data.Chat)+ if !ok {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return "", "", errors.New("invalid phone number")+ }++ resp, err := client.SendMessage(+ context.Background(),+ recipient,+ client.BuildEdit(+ recipient,+ data.MessageID,+ &waE2E.Message{+ Conversation: proto.String(data.Message),+ }))+ if err != nil {+ m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error revoking message: %v", instance.Id, err)+ return "", "", err+ }++ response := resp.ID++ return response, ts.String(), nil+}++func NewMessageService(+ clientPointer map[string]*whatsmeow.Client,+ messageRepository message_repository.MessageRepository,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) MessageService {+ return &messageService{+ clientPointer: clientPointer,+ messageRepository: messageRepository,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/middleware/auth_middleware.go b/pkg/middleware/auth_middleware.gonew file mode 100644index 0000000..429fee6--- /dev/null+++ b/pkg/middleware/auth_middleware.go@@ -0,0 +1,56 @@+package auth_middleware++import (+ "net/http"++ "github.com/EvolutionAPI/evolution-go/pkg/config"+ instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"+ "github.com/gin-gonic/gin"+)++type Middleware interface {+ Auth(ctx *gin.Context)+ AuthAdmin(ctx *gin.Context)+}++type middleware struct {+ config *config.Config+ instanceService instance_service.InstanceService+}++func (m middleware) Auth(ctx *gin.Context) {+ token := ctx.GetHeader("apikey")+ if token == "" {+ ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})+ return+ }++ instance, err := m.instanceService.GetInstanceByToken(token)+ if err != nil {+ ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})+ return+ }++ ctx.Set("instance", instance)++ ctx.Next()+}++func (m middleware) AuthAdmin(ctx *gin.Context) {+ token := ctx.GetHeader("apikey")+ if token == "" {+ ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})+ return+ }++ if token != m.config.GlobalApiKey {+ ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "not authorized"})+ return+ }++ ctx.Next()+}++func NewMiddleware(config *config.Config, instanceService instance_service.InstanceService) *middleware {+ return &middleware{config: config, instanceService: instanceService}+}diff --git a/pkg/middleware/jid_validation_middleware.go b/pkg/middleware/jid_validation_middleware.gonew file mode 100644index 0000000..cb175f4--- /dev/null+++ b/pkg/middleware/jid_validation_middleware.go@@ -0,0 +1,533 @@+package auth_middleware++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"++ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ "github.com/gin-gonic/gin"+ "github.com/gomessguii/logger"+)++// JIDValidationMiddleware validates JID parameters in request bodies+type JIDValidationMiddleware struct{}++// NewJIDValidationMiddleware creates a new JID validation middleware+func NewJIDValidationMiddleware() *JIDValidationMiddleware {+ return &JIDValidationMiddleware{}+}++// ValidateJIDFields validates and normalizes JID fields in request body+func (m *JIDValidationMiddleware) ValidateJIDFields(fieldNames ...string) gin.HandlerFunc {+ return func(c *gin.Context) {+ // Only process JSON requests+ contentType := c.ContentType()+ if !strings.Contains(contentType, "application/json") {+ // For multipart/form-data, validate form fields+ if strings.Contains(contentType, "multipart/form-data") {+ m.validateFormFields(c, fieldNames...)+ return+ }+ c.Next()+ return+ }++ // Read the request body+ body, err := io.ReadAll(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})+ c.Abort()+ return+ }++ // Restore the request body for downstream handlers+ c.Request.Body = io.NopCloser(bytes.NewBuffer(body))++ // Parse JSON+ var requestData map[string]interface{}+ if err := json.Unmarshal(body, &requestData); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})+ c.Abort()+ return+ }++ // Validate and normalize JID fields+ modified := false+ for _, fieldName := range fieldNames {+ if value, exists := requestData[fieldName]; exists {+ if strValue, ok := value.(string); ok && strValue != "" {+ // Validate and normalize the JID+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),+ })+ c.Abort()+ return+ }++ // Update the value if it was normalized+ if normalizedJID != strValue {+ requestData[fieldName] = normalizedJID+ modified = true+ logger.LogDebug("Normalized %s from %s to %s", fieldName, strValue, normalizedJID)+ }+ } else if strValue == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("%s is required and cannot be empty", fieldName),+ })+ c.Abort()+ return+ }+ }+ }++ // If we modified the request, update the body+ if modified {+ newBody, err := json.Marshal(requestData)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})+ c.Abort()+ return+ }+ c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))+ }++ c.Next()+ }+}++// validateFormFields validates JID fields in multipart form data+func (m *JIDValidationMiddleware) validateFormFields(c *gin.Context, fieldNames ...string) {+ for _, fieldName := range fieldNames {+ value := c.PostForm(fieldName)+ if value != "" {+ // Validate the JID format+ _, err := utils.CreateJID(value)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid %s format: %s", fieldName, err.Error()),+ })+ c.Abort()+ return+ }+ } else if fieldName == "number" { // number is typically required+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("%s is required and cannot be empty", fieldName),+ })+ c.Abort()+ return+ }+ }+ c.Next()+}++// ValidateNumberField is a convenience method for the common "number" field+// It handles both single strings and arrays of strings+func (m *JIDValidationMiddleware) ValidateNumberField() gin.HandlerFunc {+ return func(c *gin.Context) {+ // Only process JSON requests+ contentType := c.ContentType()+ if !strings.Contains(contentType, "application/json") {+ // For multipart/form-data, validate form fields+ if strings.Contains(contentType, "multipart/form-data") {+ m.validateFormFields(c, "number")+ return+ }+ c.Next()+ return+ }++ // Read the request body+ body, err := io.ReadAll(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})+ c.Abort()+ return+ }++ // Restore the request body for downstream handlers+ c.Request.Body = io.NopCloser(bytes.NewBuffer(body))++ // Parse JSON+ var requestData map[string]interface{}+ if err := json.Unmarshal(body, &requestData); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})+ c.Abort()+ return+ }++ // Validate and normalize number field (can be string or array)+ modified := false+ if value, exists := requestData["number"]; exists {+ // Handle array of strings+ if arrayValue, ok := value.([]interface{}); ok {+ if len(arrayValue) == 0 {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number array cannot be empty",+ })+ c.Abort()+ return+ }++ for i, item := range arrayValue {+ if strValue, ok := item.(string); ok && strValue != "" {+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ arrayValue[i] = normalizedJID+ modified = true+ logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)+ }+ } else if strValue == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("number[%d] cannot be empty", i),+ })+ c.Abort()+ return+ }+ }+ } else if strValue, ok := value.(string); ok {+ // Handle single string+ if strValue == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number is required and cannot be empty",+ })+ c.Abort()+ return+ }++ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid number format: %s", err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ requestData["number"] = normalizedJID+ modified = true+ logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)+ }+ } else {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number must be a string or array of strings",+ })+ c.Abort()+ return+ }+ }++ // If we modified the request, update the body+ if modified {+ newBody, err := json.Marshal(requestData)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})+ c.Abort()+ return+ }+ c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))+ }++ c.Next()+ }+}++// ValidateMultipleNumbers validates multiple number fields (for arrays or multiple contacts)+func (m *JIDValidationMiddleware) ValidateMultipleNumbers(fieldName string) gin.HandlerFunc {+ return func(c *gin.Context) {+ // Only process JSON requests+ contentType := c.ContentType()+ if !strings.Contains(contentType, "application/json") {+ c.Next()+ return+ }++ // Read the request body+ body, err := io.ReadAll(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})+ c.Abort()+ return+ }++ // Restore the request body for downstream handlers+ c.Request.Body = io.NopCloser(bytes.NewBuffer(body))++ // Parse JSON+ var requestData map[string]interface{}+ if err := json.Unmarshal(body, &requestData); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})+ c.Abort()+ return+ }++ // Validate array of numbers+ if value, exists := requestData[fieldName]; exists {+ modified := false++ // Handle array of strings+ if arrayValue, ok := value.([]interface{}); ok {+ for i, item := range arrayValue {+ if strValue, ok := item.(string); ok && strValue != "" {+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid %s[%d] format: %s", fieldName, i, err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ arrayValue[i] = normalizedJID+ modified = true+ }+ }+ }+ }++ // If we modified the request, update the body+ if modified {+ newBody, err := json.Marshal(requestData)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})+ c.Abort()+ return+ }+ c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))+ }+ }++ c.Next()+ }+}++// ValidateNumberFieldWithFormatJid validates number field but respects FormatJid parameter+// When FormatJid is true (default), numbers are normalized to full JID format+// When FormatJid is false, numbers are kept as received (raw format)+func (m *JIDValidationMiddleware) ValidateNumberFieldWithFormatJid() gin.HandlerFunc {+ return func(c *gin.Context) {+ // Only process JSON requests+ contentType := c.ContentType()+ if !strings.Contains(contentType, "application/json") {+ c.Next()+ return+ }++ // Read the request body+ body, err := io.ReadAll(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})+ c.Abort()+ return+ }++ // Restore the request body for downstream handlers+ c.Request.Body = io.NopCloser(bytes.NewBuffer(body))++ // Parse JSON+ var requestData map[string]interface{}+ if err := json.Unmarshal(body, &requestData); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})+ c.Abort()+ return+ }++ // Check FormatJid parameter (default is true)+ formatJid := true+ if formatJidValue, exists := requestData["formatJid"]; exists {+ if formatJidBool, ok := formatJidValue.(bool); ok {+ formatJid = formatJidBool+ }+ }++ // Validate and optionally normalize number field based on FormatJid+ modified := false+ if value, exists := requestData["number"]; exists {+ // Handle array of strings+ if arrayValue, ok := value.([]interface{}); ok {+ if len(arrayValue) == 0 {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number array cannot be empty",+ })+ c.Abort()+ return+ }++ for i, item := range arrayValue {+ if strValue, ok := item.(string); ok && strValue != "" {+ // Only validate and normalize if FormatJid is true+ if formatJid {+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid number[%d] format: %s", i, err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ arrayValue[i] = normalizedJID+ modified = true+ logger.LogDebug("Normalized number[%d] from %s to %s", i, strValue, normalizedJID)+ }+ }+ // When formatJid is false, we accept numbers as received without validation+ } else if strValue == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("number[%d] cannot be empty", i),+ })+ c.Abort()+ return+ }+ }+ } else if strValue, ok := value.(string); ok {+ // Handle single string+ if strValue == "" {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number is required and cannot be empty",+ })+ c.Abort()+ return+ }++ // Only validate and normalize if FormatJid is true+ if formatJid {+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid number format: %s", err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ requestData["number"] = normalizedJID+ modified = true+ logger.LogDebug("Normalized number from %s to %s", strValue, normalizedJID)+ }+ }+ // When formatJid is false, we accept numbers as received without validation+ } else {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "number must be a string or array of strings",+ })+ c.Abort()+ return+ }+ }++ // If we modified the request, update the body+ if modified {+ newBody, err := json.Marshal(requestData)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})+ c.Abort()+ return+ }+ c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))+ }++ c.Next()+ }+}++// ValidateContactFields validates contact-specific fields that may contain phone numbers+func (m *JIDValidationMiddleware) ValidateContactFields() gin.HandlerFunc {+ return func(c *gin.Context) {+ // Only process JSON requests+ contentType := c.ContentType()+ if !strings.Contains(contentType, "application/json") {+ c.Next()+ return+ }++ // Read the request body+ body, err := io.ReadAll(c.Request.Body)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})+ c.Abort()+ return+ }++ // Restore the request body for downstream handlers+ c.Request.Body = io.NopCloser(bytes.NewBuffer(body))++ // Parse JSON+ var requestData map[string]interface{}+ if err := json.Unmarshal(body, &requestData); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})+ c.Abort()+ return+ }++ modified := false++ // Validate main number field+ if value, exists := requestData["number"]; exists {+ if strValue, ok := value.(string); ok && strValue != "" {+ normalizedJID, err := utils.CreateJID(strValue)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid number format: %s", err.Error()),+ })+ c.Abort()+ return+ }++ if normalizedJID != strValue {+ requestData["number"] = normalizedJID+ modified = true+ }+ }+ }++ // Validate vcard phone field if present+ if vcardValue, exists := requestData["vcard"]; exists {+ if vcardMap, ok := vcardValue.(map[string]interface{}); ok {+ if phoneValue, phoneExists := vcardMap["phone"]; phoneExists {+ if phoneStr, ok := phoneValue.(string); ok && phoneStr != "" {+ // For vcard phone, we just validate format but don't necessarily convert to JID+ _, err := utils.CreateJID(phoneStr)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "error": fmt.Sprintf("Invalid vcard phone format: %s", err.Error()),+ })+ c.Abort()+ return+ }+ }+ }+ }+ }++ // If we modified the request, update the body+ if modified {+ newBody, err := json.Marshal(requestData)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to process request"})+ c.Abort()+ return+ }+ c.Request.Body = io.NopCloser(bytes.NewBuffer(newBody))+ }++ c.Next()+ }+}diff --git a/pkg/newsletter/handler/newsletter_handler.go b/pkg/newsletter/handler/newsletter_handler.gonew file mode 100644index 0000000..39b241a--- /dev/null+++ b/pkg/newsletter/handler/newsletter_handler.go@@ -0,0 +1,262 @@+package newsletter_handler++import (+ "net/http"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"+ "github.com/gin-gonic/gin"+)++type NewsletterHandler interface {+ CreateNewsletter(ctx *gin.Context)+ ListNewsletter(ctx *gin.Context)+ GetNewsletter(ctx *gin.Context)+ GetNewsletterInvite(ctx *gin.Context)+ SubscribeNewsletter(ctx *gin.Context)+ GetNewsletterMessages(ctx *gin.Context)+}++type newsletterHandler struct {+ newsletterService newsletter_service.NewsletterService+}++// Create newsletter+// @Summary Create newsletter+// @Description Create newsletter+// @Tags Newsletter+// @Accept json+// @Produce json+// @Param message body newsletter_service.CreateNewsletterStruct true "Newsletter data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/create [post]+func (n *newsletterHandler) CreateNewsletter(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *newsletter_service.CreateNewsletterStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ newsletter, err := n.newsletterService.CreateNewsletter(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})+}++// List newsletters+// @Summary List newsletters+// @Description List newsletters+// @Tags Newsletter+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/list [get]+func (n *newsletterHandler) ListNewsletter(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ newsletters, err := n.newsletterService.ListNewsletter(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletters})+}++// Get newsletter+// @Summary Get newsletter+// @Description Get newsletter+// @Tags Newsletter+// @Accept json+// @Produce json+// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/info [post]+func (n *newsletterHandler) GetNewsletter(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *newsletter_service.GetNewsletterStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID.String() == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ newsletter, err := n.newsletterService.GetNewsletter(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})+}++// Get newsletter invite+// @Summary Get newsletter invite+// @Description Get newsletter invite+// @Tags Newsletter+// @Accept json+// @Produce json+// @Param message body newsletter_service.GetNewsletterInviteStruct true "Newsletter data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/link [post]+func (n *newsletterHandler) GetNewsletterInvite(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *newsletter_service.GetNewsletterInviteStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Key == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "key is required"})+ return+ }++ newsletter, err := n.newsletterService.GetNewsletterInvite(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": newsletter})+}++// Subscribe newsletter+// @Summary Subscribe newsletter+// @Description Subscribe newsletter+// @Tags Newsletter+// @Accept json+// @Produce json+// @Param message body newsletter_service.GetNewsletterStruct true "Newsletter data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/subscribe [post]+func (n *newsletterHandler) SubscribeNewsletter(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *newsletter_service.GetNewsletterStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID.String() == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ err = n.newsletterService.SubscribeNewsletter(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success"})+}++// Get newsletter messages+// @Summary Get newsletter messages+// @Description Get newsletter messages+// @Tags Newsletter+// @Accept json+// @Produce json+// @Param message body newsletter_service.GetNewsletterMessagesStruct true "Newsletter data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /newsletter/messages [post]+func (n *newsletterHandler) GetNewsletterMessages(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *newsletter_service.GetNewsletterMessagesStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.JID.String() == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "jid is required"})+ return+ }++ messages, err := n.newsletterService.GetNewsletterMessages(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": messages})+}++func NewNewsletterHandler(+ newsletterService newsletter_service.NewsletterService,+) NewsletterHandler {+ return &newsletterHandler{+ newsletterService: newsletterService,+ }+}diff --git a/pkg/newsletter/service/newsletter_service.go b/pkg/newsletter/service/newsletter_service.gonew file mode 100644index 0000000..c56d9d0--- /dev/null+++ b/pkg/newsletter/service/newsletter_service.go@@ -0,0 +1,207 @@+package newsletter_service++import (+ "context"+ "errors"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+)++type NewsletterService interface {+ CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)+ ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error)+ GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)+ GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error)+ SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error+ GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error)+}++type newsletterService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type CreateNewsletterStruct struct {+ Name string `json:"name"`+ Description string `json:"description"`+}++type GetNewsletterStruct struct {+ JID types.JID `json:"jid"`+}++type GetNewsletterInviteStruct struct {+ Key string `json:"key"`+}++type GetNewsletterMessagesStruct struct {+ JID types.JID `json:"jid"`+ Count int `json:"count"`+ BeforeID int `json:"before_id"`+}++func (n *newsletterService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := n.clientPointer[instanceId]+ n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := n.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = n.clientPointer[instanceId]+ n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ n.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ n.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ n.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (n *newsletterService) CreateNewsletter(data *CreateNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ newsletter, err := client.CreateNewsletter(context.Background(), whatsmeow.CreateNewsletterParams{+ Name: data.Name,+ Description: data.Description,+ })+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error create newsletter: %v", instance.Id, err)+ return nil, err+ }++ return newsletter, nil+}++func (n *newsletterService) ListNewsletter(instance *instance_model.Instance) ([]*types.NewsletterMetadata, error) {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ newsletters, err := client.GetSubscribedNewsletters(context.Background())+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletters: %v", instance.Id, err)+ return nil, err+ }++ // For each newsletter, fetch full info to get subscribers_count+ fullNewsletters := make([]*types.NewsletterMetadata, 0, len(newsletters))+ for _, newsletter := range newsletters {+ fullInfo, err := client.GetNewsletterInfo(context.Background(), newsletter.ID)+ if err != nil {+ // If we can't get full info, use the basic one+ n.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] error getting full info for newsletter %s: %v", instance.Id, newsletter.ID.String(), err)+ fullNewsletters = append(fullNewsletters, newsletter)+ continue+ }+ fullNewsletters = append(fullNewsletters, fullInfo)+ }++ return fullNewsletters, nil+}++func (n *newsletterService) GetNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ newsletter, err := client.GetNewsletterInfo(context.Background(), data.JID)+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)+ return nil, err+ }++ return newsletter, nil+}++func (n *newsletterService) GetNewsletterInvite(data *GetNewsletterInviteStruct, instance *instance_model.Instance) (*types.NewsletterMetadata, error) {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ newsletter, err := client.GetNewsletterInfoWithInvite(context.Background(), data.Key)+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)+ return nil, err+ }++ return newsletter, nil+}++func (n *newsletterService) SubscribeNewsletter(data *GetNewsletterStruct, instance *instance_model.Instance) error {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return err+ }++ _, err = client.NewsletterSubscribeLiveUpdates(context.TODO(), data.JID)+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)+ return err+ }++ return nil+}++func (n *newsletterService) GetNewsletterMessages(data *GetNewsletterMessagesStruct, instance *instance_model.Instance) ([]*types.NewsletterMessage, error) {+ client, err := n.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ messages, err := client.GetNewsletterMessages(context.Background(), data.JID,+ &whatsmeow.GetNewsletterMessagesParams{+ Count: data.Count, Before: data.BeforeID,+ })+ if err != nil {+ n.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error list newsletter: %v", instance.Id, err)+ return nil, err+ }++ return messages, nil+}++func NewNewsletterService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) NewsletterService {+ return &newsletterService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/poll/handler/poll_handler.go b/pkg/poll/handler/poll_handler.gonew file mode 100644index 0000000..d33e6b0--- /dev/null+++ b/pkg/poll/handler/poll_handler.go@@ -0,0 +1,98 @@+package poll_handler++import (+ "encoding/json"+ "net/http"++ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"+ "github.com/gin-gonic/gin"+)++type PollHandler struct {+ pollService poll_service.PollService+ loggerWrapper *logger_wrapper.LoggerManager+}++// NewPollHandler cria handler usando PollService existente (evita dupla inicialização)+func NewPollHandler(pollService poll_service.PollService, loggerWrapper *logger_wrapper.LoggerManager) *PollHandler {+ return &PollHandler{+ pollService: pollService,+ loggerWrapper: loggerWrapper,+ }+}++// GetPollResults retorna os resultados de uma enquete+// @Summary Get poll results+// @Description Retorna todos os votos de uma enquete específica+// @Tags Polls+// @Accept json+// @Produce json+// @Param pollMessageId path string true "ID da mensagem da enquete"+// @Success 200 {object} model.PollResults+// @Failure 400 {object} gin.H+// @Failure 404 {object} gin.H+// @Failure 500 {object} gin.H+// @Router /polls/{pollMessageId}/results [get]+func (h *PollHandler) GetPollResults(c *gin.Context) {+ pollMessageID := c.Param("pollMessageId")++ // Pegar instance do contexto de autenticação+ instanceInterface, exists := c.Get("instance")+ if !exists {+ h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Instance not found in context")+ c.JSON(http.StatusUnauthorized, gin.H{+ "error": "Authentication required",+ })+ return+ }++ // Converter para struct Instance+ type Instance struct {+ Id string `json:"id"`+ }+ instanceBytes, _ := json.Marshal(instanceInterface)+ var instance Instance+ if err := json.Unmarshal(instanceBytes, &instance); err != nil {+ h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Failed to parse instance: %v", err)+ c.JSON(http.StatusInternalServerError, gin.H{+ "error": "Failed to get instance information",+ })+ return+ }++ instanceID := instance.Id++ // Validações de segurança+ if pollMessageID == "" {+ h.loggerWrapper.GetLogger("poll-handler").LogWarn("[POLL] Missing pollMessageId")+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "pollMessageId is required",+ })+ return+ }++ h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Fetching results for poll %s (instance: %s)", pollMessageID, instanceID)++ // Buscar resultados do banco+ results, err := h.pollService.GetPollResults(c.Request.Context(), pollMessageID, instanceID)+ if err != nil {+ h.loggerWrapper.GetLogger("poll-handler").LogError("[POLL] Error fetching results: %v", err)+ c.JSON(http.StatusInternalServerError, gin.H{+ "error": "Failed to fetch poll results",+ })+ return+ }++ if results.TotalVotes == 0 {+ h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] No votes found for poll %s", pollMessageID)+ c.JSON(http.StatusNotFound, gin.H{+ "error": "No votes found for this poll",+ "message": "This poll has no votes yet, or the pollMessageId is incorrect",+ })+ return+ }++ h.loggerWrapper.GetLogger("poll-handler").LogInfo("[POLL] Returning %d votes for poll %s", results.TotalVotes, pollMessageID)+ c.JSON(http.StatusOK, results)+}diff --git a/pkg/poll/model/poll_vote.go b/pkg/poll/model/poll_vote.gonew file mode 100644index 0000000..bb28c82--- /dev/null+++ b/pkg/poll/model/poll_vote.go@@ -0,0 +1,38 @@+package model++import "time"++// PollVote representa um voto em uma enquete do WhatsApp+type PollVote struct {+ ID string `json:"id"`+ CompanyID string `json:"companyId"`+ InstanceID string `json:"instanceId"`+ PollMessageID string `json:"pollMessageId"`+ PollChatJid string `json:"pollChatJid"`+ VoteMessageID string `json:"voteMessageId"`+ VoterJid string `json:"voterJid"`+ VoterPhone string `json:"voterPhone,omitempty"`+ VoterName string `json:"voterName,omitempty"`+ SelectedOptions []string `json:"selectedOptions"` // SHA-256 hashes+ VotedAt time.Time `json:"votedAt"`+ ReceivedAt time.Time `json:"receivedAt"`+}++// PollResults representa os resultados agregados de uma enquete+type PollResults struct {+ PollMessageID string `json:"pollMessageId"`+ PollChatJid string `json:"pollChatJid"`+ TotalVotes int `json:"totalVotes"`+ Votes []PollVote `json:"votes"`+ OptionCounts map[string]int `json:"optionCounts"` // hash -> count+ Voters []VoterInfo `json:"voters"`+}++// VoterInfo representa informações de um votante+type VoterInfo struct {+ Jid string `json:"jid"`+ Phone string `json:"phone,omitempty"`+ Name string `json:"name,omitempty"`+ SelectedOptions []string `json:"selectedOptions"`+ VotedAt time.Time `json:"votedAt"`+}diff --git a/pkg/poll/service/poll_service.go b/pkg/poll/service/poll_service.gonew file mode 100644index 0000000..a9396ad--- /dev/null+++ b/pkg/poll/service/poll_service.go@@ -0,0 +1,304 @@+package poll_service++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "time"++ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/poll/model"+ "github.com/google/uuid"+ waProto "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"+)++// PollService define a interface para gerenciamento de votos de enquetes+type PollService interface {+ // SavePollVote salva um voto de enquete no banco de dados+ SavePollVote(ctx context.Context, vote *model.PollVote) error++ // GetPollResults retorna os resultados de uma enquete+ GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error)+}++type pollService struct {+ db *sql.DB+ loggerWrapper *logger_wrapper.LoggerManager+}++// NewPollService cria uma nova instância do serviço de polls+func NewPollService(db *sql.DB, loggerWrapper *logger_wrapper.LoggerManager) PollService {+ service := &pollService{+ db: db,+ loggerWrapper: loggerWrapper,+ }++ // Auto-migration: criar tabela se não existir+ if err := service.autoMigrate(); err != nil {+ loggerWrapper.GetLogger("poll-service").LogError("[POLL] Auto-migration failed: %v", err)+ }++ return service+}++// autoMigrate cria a tabela poll_votes se não existir+func (s *pollService) autoMigrate() error {+ createTableSQL := `+ CREATE TABLE IF NOT EXISTS poll_votes (+ id VARCHAR(255) PRIMARY KEY,+ company_id VARCHAR(255) NOT NULL,+ instance_id VARCHAR(255) NOT NULL,+ poll_message_id VARCHAR(255) NOT NULL,+ poll_chat_jid VARCHAR(255) NOT NULL,+ vote_message_id VARCHAR(255) NOT NULL,+ voter_jid VARCHAR(255) NOT NULL,+ voter_phone VARCHAR(255),+ voter_name VARCHAR(255),+ selected_options TEXT[] NOT NULL DEFAULT '{}',+ voted_at TIMESTAMP NOT NULL DEFAULT NOW(),+ received_at TIMESTAMP NOT NULL DEFAULT NOW(),+ CONSTRAINT unique_vote_per_poll UNIQUE (poll_message_id, voter_jid)+ );++ CREATE INDEX IF NOT EXISTS idx_poll_votes_company ON poll_votes(company_id);+ CREATE INDEX IF NOT EXISTS idx_poll_votes_instance ON poll_votes(instance_id);+ CREATE INDEX IF NOT EXISTS idx_poll_votes_poll_message ON poll_votes(poll_message_id);+ CREATE INDEX IF NOT EXISTS idx_poll_votes_chat ON poll_votes(poll_chat_jid);+ CREATE INDEX IF NOT EXISTS idx_poll_votes_voter ON poll_votes(voter_jid);+ `++ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Running auto-migration...")++ _, err := s.db.Exec(createTableSQL)+ if err != nil {+ return fmt.Errorf("failed to create poll_votes table: %w", err)+ }++ return nil+}++// SavePollVote salva um voto de enquete no banco de dados (NÃO-INVASIVO)+func (s *pollService) SavePollVote(ctx context.Context, vote *model.PollVote) error {+ // Log seguro - não expõe dados sensíveis+ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Saving vote for poll %s from %s", vote.PollMessageID, vote.VoterJid)++ // Extrair telefone do JID de forma segura+ if vote.VoterPhone == "" && strings.Contains(vote.VoterJid, "@") {+ phone := strings.Split(vote.VoterJid, "@")[0]+ vote.VoterPhone = phone+ }++ // Garantir ID único+ if vote.ID == "" {+ vote.ID = uuid.New().String()+ }++ // Query INSERT com ON CONFLICT para evitar duplicatas (SEGURO)+ query := `+ INSERT INTO poll_votes (+ id, company_id, instance_id, poll_message_id, poll_chat_jid,+ vote_message_id, voter_jid, voter_phone, voter_name,+ selected_options, voted_at, received_at+ ) VALUES (+ $1, $2, $3, $4, $5,+ $6, $7, $8, $9,+ $10, $11, $12+ )+ ON CONFLICT (poll_message_id, voter_jid)+ DO UPDATE SET+ selected_options = EXCLUDED.selected_options,+ voted_at = EXCLUDED.voted_at,+ received_at = EXCLUDED.received_at+ `++ _, err := s.db.ExecContext(ctx, query,+ vote.ID,+ vote.CompanyID,+ vote.InstanceID,+ vote.PollMessageID,+ vote.PollChatJid,+ vote.VoteMessageID,+ vote.VoterJid,+ vote.VoterPhone,+ vote.VoterName,+ stringArrayToPostgresArray(vote.SelectedOptions),+ vote.VotedAt,+ vote.ReceivedAt,+ )++ if err != nil {+ s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to save vote: %v", err)+ return fmt.Errorf("failed to save poll vote: %w", err)+ }++ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Vote saved successfully for poll %s", vote.PollMessageID)+ return nil+}++// GetPollResults retorna os resultados agregados de uma enquete+func (s *pollService) GetPollResults(ctx context.Context, pollMessageID string, instanceID string) (*model.PollResults, error) {+ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Fetching results for poll %s", pollMessageID)++ query := `+ SELECT+ id, company_id, instance_id, poll_message_id, poll_chat_jid,+ vote_message_id, voter_jid, voter_phone, voter_name,+ selected_options, voted_at, received_at+ FROM poll_votes+ WHERE poll_message_id = $1 AND instance_id = $2+ ORDER BY voted_at ASC+ `++ rows, err := s.db.QueryContext(ctx, query, pollMessageID, instanceID)+ if err != nil {+ s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to query votes: %v", err)+ return nil, fmt.Errorf("failed to query poll votes: %w", err)+ }+ defer rows.Close()++ var votes []model.PollVote+ optionCounts := make(map[string]int)++ for rows.Next() {+ var vote model.PollVote+ var selectedOptionsStr string++ err := rows.Scan(+ &vote.ID,+ &vote.CompanyID,+ &vote.InstanceID,+ &vote.PollMessageID,+ &vote.PollChatJid,+ &vote.VoteMessageID,+ &vote.VoterJid,+ &vote.VoterPhone,+ &vote.VoterName,+ &selectedOptionsStr,+ &vote.VotedAt,+ &vote.ReceivedAt,+ )+ if err != nil {+ s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Failed to scan vote: %v", err)+ continue+ }++ // Converter array do PostgreSQL para []string+ vote.SelectedOptions = postgresArrayToStringSlice(selectedOptionsStr)++ // Contar opções+ for _, option := range vote.SelectedOptions {+ optionCounts[option]+++ }++ votes = append(votes, vote)+ }++ if err = rows.Err(); err != nil {+ s.loggerWrapper.GetLogger("poll-service").LogError("[POLL] Rows iteration error: %v", err)+ return nil, fmt.Errorf("error iterating votes: %w", err)+ }++ // Verificar se há votos antes de construir resultado+ if len(votes) == 0 {+ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] No votes found for poll %s", pollMessageID)+ return &model.PollResults{+ PollMessageID: pollMessageID,+ PollChatJid: "",+ TotalVotes: 0,+ Votes: []model.PollVote{},+ OptionCounts: make(map[string]int),+ Voters: []model.VoterInfo{},+ }, nil+ }++ // Construir informações dos votantes+ voters := make([]model.VoterInfo, len(votes))+ for i, vote := range votes {+ voters[i] = model.VoterInfo{+ Jid: vote.VoterJid,+ Phone: vote.VoterPhone,+ Name: vote.VoterName,+ SelectedOptions: vote.SelectedOptions,+ VotedAt: vote.VotedAt,+ }+ }++ results := &model.PollResults{+ PollMessageID: pollMessageID,+ PollChatJid: votes[0].PollChatJid,+ TotalVotes: len(votes),+ Votes: votes,+ OptionCounts: optionCounts,+ Voters: voters,+ }++ s.loggerWrapper.GetLogger("poll-service").LogInfo("[POLL] Found %d votes for poll %s", len(votes), pollMessageID)+ return results, nil+}++// Helper para converter []string em formato PostgreSQL array+func stringArrayToPostgresArray(arr []string) string {+ if len(arr) == 0 {+ return "{}"+ }+ return fmt.Sprintf("{%s}", strings.Join(arr, ","))+}++// Helper para converter array PostgreSQL de volta para []string+func postgresArrayToStringSlice(s string) []string {+ // Remove { e }+ s = strings.TrimPrefix(s, "{")+ s = strings.TrimSuffix(s, "}")++ if s == "" {+ return []string{}+ }++ return strings.Split(s, ",")+}++// BuildPollVoteFromEvent constrói um model.PollVote a partir de eventos do WhatsApp (HELPER SEGURO)+// NOTA: Espera que voteInfo já tenha passado pelo JID swap (Sender = número real)+func BuildPollVoteFromEvent(+ pollInfo *types.MessageInfo,+ voteInfo *types.MessageInfo,+ decryptedVote *waProto.PollVoteMessage,+ companyID string,+ instanceID string,+) *model.PollVote {+ // Extrair opções selecionadas (hashes SHA-256)+ selectedOptions := make([]string, len(decryptedVote.SelectedOptions))+ for i, option := range decryptedVote.SelectedOptions {+ selectedOptions[i] = fmt.Sprintf("%x", option) // Converte bytes para hex+ }++ // Extrair telefone do votante+ // NOTA: O JID swap já foi feito antes de chegar aqui!+ // Se havia LID+WhatsApp, o Sender JÁ É o número real (@s.whatsapp.net) e SenderAlt é o LID+ voterPhone := voteInfo.Sender.User+ voterJid := voteInfo.Sender.String()++ fmt.Printf("[POLL DEBUG] ==========================================\n")+ fmt.Printf("[POLL DEBUG] Voter JID: %s\n", voterJid)+ fmt.Printf("[POLL DEBUG] Sender.Server: %s\n", voteInfo.Sender.Server)+ fmt.Printf("[POLL DEBUG] Sender.User: %s\n", voteInfo.Sender.User)+ fmt.Printf("[POLL DEBUG] FINAL voterPhone: %s\n", voterPhone)+ fmt.Printf("[POLL DEBUG] ==========================================\n")++ return &model.PollVote{+ ID: uuid.New().String(),+ CompanyID: companyID,+ InstanceID: instanceID,+ PollMessageID: pollInfo.ID,+ PollChatJid: pollInfo.Chat.String(),+ VoteMessageID: voteInfo.ID,+ VoterJid: voteInfo.Sender.String(),+ VoterPhone: voterPhone,+ VoterName: voteInfo.PushName,+ SelectedOptions: selectedOptions,+ VotedAt: voteInfo.Timestamp,+ ReceivedAt: time.Now(),+ }+}diff --git a/pkg/routes/routes.go b/pkg/routes/routes.gonew file mode 100644index 0000000..0064014--- /dev/null+++ b/pkg/routes/routes.go@@ -0,0 +1,277 @@+package routes++import (+ "net/http"++ "github.com/gin-gonic/gin"+ swaggerFiles "github.com/swaggo/files"+ ginSwagger "github.com/swaggo/gin-swagger"++ _ "github.com/EvolutionAPI/evolution-go/docs"+ call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"+ chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"+ community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"+ group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"+ instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"+ label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"+ message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"+ auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"+ newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"+ poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"+ send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"+ server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"+ user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"+)++type Routes struct {+ authMiddleware auth_middleware.Middleware+ jidValidationMiddleware *auth_middleware.JIDValidationMiddleware+ instanceHandler instance_handler.InstanceHandler+ userHandler user_handler.UserHandler+ sendHandler send_handler.SendHandler+ messageHandler message_handler.MessageHandler+ chatHandler chat_handler.ChatHandler+ groupHandler group_handler.GroupHandler+ callHandler call_handler.CallHandler+ communityHandler community_handler.CommunityHandler+ labelHandler label_handler.LabelHandler+ newsletterHandler newsletter_handler.NewsletterHandler+ pollHandler *poll_handler.PollHandler+ serverHandler server_handler.ServerHandler+}++func (r *Routes) AssignRoutes(eng *gin.Engine) {+ // Configuração do CORS+ eng.Use(func(c *gin.Context) {+ c.Writer.Header().Set("Access-Control-Allow-Origin", "*")+ c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")+ c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")+ c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Cache-Control, X-Requested-With, apikey, ApiKey")+ c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")++ if c.Request.Method == "OPTIONS" {+ c.AbortWithStatus(200)+ return+ }++ c.Next()+ })++ eng.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))++ eng.GET("/favicon.ico", func(c *gin.Context) {+ c.Status(http.StatusNoContent)+ })++ // Rotas para o gerenciador React (sem autenticação)+ eng.Static("/assets", "./manager/dist/assets")++ // Ajuste nas rotas do manager para suportar client-side routing do React+ eng.GET("/manager/*any", func(c *gin.Context) {+ c.File("manager/dist/index.html")+ })++ eng.GET("/manager", func(c *gin.Context) {+ c.File("manager/dist/index.html")+ })++ eng.GET("/server/ok", r.serverHandler.ServerOk)++ routes := eng.Group("/instance")+ {+ routes.Use(r.authMiddleware.AuthAdmin)+ {+ routes.POST("/create", r.instanceHandler.Create)+ routes.GET("/all", r.instanceHandler.All)+ routes.GET("/info/:instanceId", r.instanceHandler.Info)+ routes.DELETE("/delete/:instanceId", r.instanceHandler.Delete)+ routes.POST("/proxy/:instanceId", r.instanceHandler.SetProxy)+ routes.DELETE("/proxy/:instanceId", r.instanceHandler.DeleteProxy)+ routes.POST("/forcereconnect/:instanceId", r.instanceHandler.ForceReconnect)+ routes.GET("/logs/:instanceId", r.instanceHandler.GetLogs)+ }+ }++ routes = eng.Group("/instance")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/connect", r.instanceHandler.Connect)+ routes.GET("/status", r.instanceHandler.Status)+ routes.GET("/qr", r.instanceHandler.Qr)+ routes.POST("/pair", r.jidValidationMiddleware.ValidateNumberField(), r.instanceHandler.Pair)+ routes.POST("/disconnect", r.instanceHandler.Disconnect)+ routes.POST("/reconnect", r.instanceHandler.Reconnect)+ routes.DELETE("/logout", r.instanceHandler.Logout)+ routes.GET("/:instanceId/advanced-settings", r.instanceHandler.GetAdvancedSettings)+ routes.PUT("/:instanceId/advanced-settings", r.instanceHandler.UpdateAdvancedSettings)+ }+ }++ routes = eng.Group("/send")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/text", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendText)+ routes.POST("/link", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLink)+ routes.POST("/media", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendMedia)+ routes.POST("/poll", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendPoll)+ routes.POST("/sticker", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendSticker)+ routes.POST("/location", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendLocation)+ routes.POST("/contact", r.jidValidationMiddleware.ValidateContactFields(), r.sendHandler.SendContact) // TODO: send multiple contacts+ routes.POST("/button", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendButton)+ routes.POST("/list", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.sendHandler.SendList)+ // TODO: send status+ }+ }+ routes = eng.Group("/user")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetUser)+ routes.POST("/check", r.jidValidationMiddleware.ValidateNumberFieldWithFormatJid(), r.userHandler.CheckUser)+ routes.POST("/avatar", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.GetAvatar)+ routes.GET("/contacts", r.userHandler.GetContacts)+ routes.GET("/privacy", r.userHandler.GetPrivacy)+ routes.POST("/privacy", r.userHandler.SetPrivacy)+ routes.POST("/block", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.BlockContact)+ routes.POST("/unblock", r.jidValidationMiddleware.ValidateNumberField(), r.userHandler.UnblockContact)+ routes.GET("/blocklist", r.userHandler.GetBlockList)+ routes.POST("/profilePicture", r.userHandler.SetProfilePicture)+ routes.POST("/profileName", r.userHandler.SetProfileName)+ routes.POST("/profileStatus", r.userHandler.SetProfileStatus)+ }+ }+ routes = eng.Group("/message")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/react", r.jidValidationMiddleware.ValidateJIDFields("number"), r.messageHandler.React)+ routes.POST("/presence", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.ChatPresence)+ routes.POST("/markread", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.MarkRead)+ routes.POST("/downloadmedia", r.messageHandler.DownloadMedia)+ routes.POST("/status", r.messageHandler.GetMessageStatus)+ routes.POST("/delete", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.DeleteMessageEveryone)+ routes.POST("/edit", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.EditMessage) // TODO: edit MediaMessage too+ }+ }+ routes = eng.Group("/chat")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/pin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatPin) // TODO: not working+ routes.POST("/unpin", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnpin) // TODO: not working+ routes.POST("/archive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatArchive) // TODO: not working+ routes.POST("/unarchive", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnarchive) // TODO: not working+ routes.POST("/mute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatMute) // TODO: not working+ routes.POST("/unmute", r.jidValidationMiddleware.ValidateNumberField(), r.chatHandler.ChatUnmute) // TODO: not working+ routes.POST("/history-sync", r.chatHandler.HistorySyncRequest)+ }+ }+ routes = eng.Group("/group")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.GET("/list", r.groupHandler.ListGroups)+ routes.POST("/info", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInfo)+ routes.POST("/invitelink", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.GetGroupInviteLink)+ routes.POST("/photo", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupPhoto)+ routes.POST("/name", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupName)+ routes.POST("/description", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.SetGroupDescription)+ routes.POST("/create", r.jidValidationMiddleware.ValidateMultipleNumbers("participants"), r.groupHandler.CreateGroup)+ routes.POST("/participant", r.jidValidationMiddleware.ValidateJIDFields("number", "participants"), r.groupHandler.UpdateParticipant)+ routes.GET("/myall", r.groupHandler.GetMyGroups) // TODO: not working+ routes.POST("/join", r.groupHandler.JoinGroupLink)+ routes.POST("/leave", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.LeaveGroup)+ }+ }+ routes = eng.Group("/call")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/reject", r.jidValidationMiddleware.ValidateNumberField(), r.callHandler.RejectCall)+ }+ }+ routes = eng.Group("/community")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/create", r.communityHandler.CreateCommunity)+ routes.POST("/add", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityAdd)+ routes.POST("/remove", r.jidValidationMiddleware.ValidateJIDFields("number", "communityId"), r.communityHandler.CommunityRemove)+ }+ }+ routes = eng.Group("/label")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatLabel)+ routes.POST("/message", r.labelHandler.MessageLabel)+ routes.POST("/edit", r.labelHandler.EditLabel)+ routes.GET("/list", r.labelHandler.GetLabels)+ }+ }+ routes = eng.Group("/unlabel")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/chat", r.jidValidationMiddleware.ValidateNumberField(), r.labelHandler.ChatUnlabel)+ routes.POST("/message", r.labelHandler.MessageUnlabel)+ }+ }+ routes = eng.Group("/newsletter")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.POST("/create", r.newsletterHandler.CreateNewsletter)+ routes.GET("/list", r.newsletterHandler.ListNewsletter)+ routes.POST("/info", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletter)+ routes.POST("/link", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterInvite)+ routes.POST("/subscribe", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.SubscribeNewsletter)+ routes.POST("/messages", r.jidValidationMiddleware.ValidateJIDFields("newsletterId"), r.newsletterHandler.GetNewsletterMessages)+ }+ }++ // NOVO: Rotas de Enquetes (Polls)+ routes = eng.Group("/polls")+ {+ routes.Use(r.authMiddleware.Auth)+ {+ routes.GET("/:pollMessageId/results", r.pollHandler.GetPollResults)+ }+ }++}++func NewRouter(+ authMiddleware auth_middleware.Middleware,+ instanceHandler instance_handler.InstanceHandler,+ userHandler user_handler.UserHandler,+ sendHandler send_handler.SendHandler,+ messageHandler message_handler.MessageHandler,+ chatHandler chat_handler.ChatHandler,+ groupHandler group_handler.GroupHandler,+ callHandler call_handler.CallHandler,+ communityHandler community_handler.CommunityHandler,+ labelHandler label_handler.LabelHandler,+ newsletterHandler newsletter_handler.NewsletterHandler,+ pollHandler *poll_handler.PollHandler,+ serverHandler server_handler.ServerHandler,+) *Routes {+ return &Routes{+ authMiddleware: authMiddleware,+ jidValidationMiddleware: auth_middleware.NewJIDValidationMiddleware(),+ instanceHandler: instanceHandler,+ userHandler: userHandler,+ sendHandler: sendHandler,+ messageHandler: messageHandler,+ chatHandler: chatHandler,+ groupHandler: groupHandler,+ callHandler: callHandler,+ communityHandler: communityHandler,+ labelHandler: labelHandler,+ newsletterHandler: newsletterHandler,+ pollHandler: pollHandler,+ serverHandler: serverHandler,+ }+}diff --git a/pkg/sendMessage/handler/send_handler.go b/pkg/sendMessage/handler/send_handler.gonew file mode 100644index 0000000..7e4e43f--- /dev/null+++ b/pkg/sendMessage/handler/send_handler.go@@ -0,0 +1,579 @@+package send_handler++import (+ "io"+ "net/http"+ "strconv"+ "strings"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"+ "github.com/gin-gonic/gin"+)++type SendHandler interface {+ SendText(ctx *gin.Context)+ SendLink(ctx *gin.Context)+ SendMedia(ctx *gin.Context)+ SendPoll(ctx *gin.Context)+ SendSticker(ctx *gin.Context)+ SendLocation(ctx *gin.Context)+ SendContact(ctx *gin.Context)+ SendButton(ctx *gin.Context)+ SendList(ctx *gin.Context)+}++type sendHandler struct {+ sendMessageService send_service.SendService+}++// Send a text message+// @Summary Send a text message+// @Description Send a text message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.TextStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/text [post]+func (s *sendHandler) SendText(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.TextStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Text == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})+ return+ }++ message, err := s.sendMessageService.SendText(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a link message+// @Summary Send a link message+// @Description Send a link message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.LinkStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/link [post]+func (s *sendHandler) SendLink(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.LinkStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Text == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "message body is required"})+ return+ }++ message, err := s.sendMessageService.SendLink(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a media message+// @Summary Send a media message+// @Description Send a media message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.MediaStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/media [post]+func (s *sendHandler) SendMedia(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ contentType := ctx.ContentType()++ var data *send_service.MediaStruct++ if strings.HasPrefix(contentType, "multipart/form-data") {+ // Handle form-data+ number := ctx.PostForm("number")+ if number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ mediaType := ctx.PostForm("type")+ if mediaType == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})+ return+ }++ caption := ctx.PostForm("caption")+ filename := ctx.PostForm("filename")+ id := ctx.PostForm("id")+ delayStr := ctx.PostForm("delay")+ delay := int32(0)+ if delayStr != "" {+ delay64, err := strconv.ParseInt(delayStr, 10, 32)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid delay"})+ return+ }+ delay = int32(delay64)+ }++ // Get file+ file, err := ctx.FormFile("file")+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})+ return+ }++ // Open file+ fileData, err := file.Open()+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})+ return+ }+ defer fileData.Close()+ fileBytes, err := io.ReadAll(fileData)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read file"})+ return+ }++ // Create MediaStruct+ data = &send_service.MediaStruct{+ Number: number,+ Type: mediaType,+ Caption: caption,+ Filename: filename,+ Id: id,+ Delay: delay,+ // Other fields as necessary+ }++ // Pass fileBytes to the send service+ message, err := s.sendMessageService.SendMediaFile(data, fileBytes, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})++ } else {++ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Url == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "URL is required"})+ return+ }++ if data.Type == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "media type is required"})+ return+ }++ message, err := s.sendMessageService.SendMediaUrl(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+ }+}++// Send a poll message+// @Summary Send a poll message+// @Description Send a poll message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.PollStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/poll [post]+func (s *sendHandler) SendPoll(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.PollStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Question == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "question is required"})+ return+ }++ if len(data.Options) < 2 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "minimum 2 options are required"})+ return+ }++ message, err := s.sendMessageService.SendPoll(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a sticker message+// @Summary Send a sticker message+// @Description Send a sticker message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.StickerStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/sticker [post]+func (s *sendHandler) SendSticker(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.StickerStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Sticker == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "sticker is required"})+ return+ }++ message, err := s.sendMessageService.SendSticker(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a location message+// @Summary Send a location message+// @Description Send a location message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.LocationStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/location [post]+func (s *sendHandler) SendLocation(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.LocationStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Latitude == 0 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "latitude is required"})+ return+ }++ if data.Longitude == 0 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "longitude is required"})+ return+ }++ if data.Address == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "address is required"})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ message, err := s.sendMessageService.SendLocation(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a contact message+// @Summary Send a contact message+// @Description Send a contact message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.ContactStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/contact [post]+func (s *sendHandler) SendContact(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.ContactStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Vcard.Phone == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact phone number is required"})+ return+ }++ if data.Vcard.FullName == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "contact full name is required"})+ return+ }++ message, err := s.sendMessageService.SendContact(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a button message+// @Summary Send a button message+// @Description Send a button message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.ContactStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/button [post]+func (s *sendHandler) SendButton(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.ButtonStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Title == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})+ return+ }++ if data.Description == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})+ return+ }++ if data.Footer == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})+ return+ }++ message, err := s.sendMessageService.SendButton(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++// Send a list message+// @Summary Send a list message+// @Description Send a list message+// @Tags Send Message+// @Accept json+// @Produce json+// @Param message body send_service.ContactStruct true "Message data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /send/list [post]+func (s *sendHandler) SendList(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *send_service.ListStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Title == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "title is required"})+ return+ }++ if data.Description == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "description is required"})+ return+ }++ if data.FooterText == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "footer is required"})+ return+ }++ if data.ButtonText == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "button text is required"})+ return+ }++ message, err := s.sendMessageService.SendList(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": message})+}++func NewSendHandler(+ sendMessageService send_service.SendService,+) SendHandler {+ return &sendHandler{+ sendMessageService: sendMessageService,+ }+}diff --git a/pkg/sendMessage/service/send_service.go b/pkg/sendMessage/service/send_service.gonew file mode 100644index 0000000..4bf3412--- /dev/null+++ b/pkg/sendMessage/service/send_service.go@@ -0,0 +1,2554 @@+package send_service++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "image"+ "image/png"+ "io"+ "mime/multipart"+ "net/http"+ "os/exec"+ "regexp"+ "strconv"+ "strings"+ "time"++ config "github.com/EvolutionAPI/evolution-go/pkg/config"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "github.com/chai2010/webp"+ "github.com/gabriel-vasile/mimetype"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/types"+ "golang.org/x/net/html"+ "google.golang.org/protobuf/proto"+)++type SendService interface {+ SendText(data *TextStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendLink(data *LinkStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendMediaUrl(data *MediaStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendMediaFile(data *MediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendPoll(data *PollStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendSticker(data *StickerStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendLocation(data *LocationStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendContact(data *ContactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendButton(data *ButtonStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+ SendList(data *ListStruct, instance *instance_model.Instance) (*MessageSendStruct, error)+}++type sendService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ config *config.Config+ loggerWrapper *logger_wrapper.LoggerManager+}++type SendDataStruct struct {+ Id string+ Number string+ Delay int32+ MentionAll bool+ MentionedJID []string+ FormatJid *bool+ Quoted QuotedStruct+ MediaHandle string+}++type QuotedStruct struct {+ MessageID string `json:"messageId"`+ Participant string `json:"participant"`+}++type TextStruct struct {+ Number string `json:"number"`+ Text string `json:"text"`+ Id string `json:"id"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type LinkStruct struct {+ Number string `json:"number"`+ Text string `json:"text"`+ Title string `json:"title"`+ Url string `json:"url"`+ Description string `json:"description"`+ ImgUrl string `json:"imgUrl"`+ Id string `json:"id"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type MediaStruct struct {+ Number string `json:"number"`+ Url string `json:"url"`+ Type string `json:"type"`+ Caption string `json:"caption"`+ Filename string `json:"filename"`+ Id string `json:"id"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type PollStruct struct {+ Id string `json:"id"`+ Number string `json:"number"`+ Question string `json:"question"`+ MaxAnswer int `json:"maxAnswer"`+ Options []string `json:"options"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type StickerStruct struct {+ Number string `json:"number"`+ Sticker string `json:"sticker"`+ Id string `json:"id"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type LocationStruct struct {+ Number string `json:"number"`+ Id string `json:"id"`+ Name string `json:"name"`+ Latitude float64 `json:"latitude"`+ Longitude float64 `json:"longitude"`+ Address string `json:"address"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type ContactStruct struct {+ Number string `json:"number"`+ Id string `json:"id"`+ Vcard utils.VCardStruct `json:"vcard"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type Button struct {+ Type string `json:"type"`+ DisplayText string `json:"displayText"`+ Id string `json:"id"`+ CopyCode string `json:"copyCode"`+ URL string `json:"url"`+ PhoneNumber string `json:"phoneNumber"`+ Currency string `json:"currency"`+ Name string `json:"name"`+ KeyType string `json:"keyType"`+ Key string `json:"key"`+}++type ButtonStruct struct {+ Number string `json:"number"`+ Title string `json:"title"`+ Description string `json:"description"`+ Footer string `json:"footer"`+ Buttons []Button `json:"buttons"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type Row struct {+ Title string `json:"title"`+ Description string `json:"description"`+ RowId string `json:"rowId"`+}++type Section struct {+ Title string `json:"title"`+ Rows []Row `json:"rows"`+}++type ListStruct struct {+ Number string `json:"number"`+ Title string `json:"title"`+ Description string `json:"description"`+ ButtonText string `json:"buttonText"`+ FooterText string `json:"footerText"`+ Sections []Section `json:"sections"`+ Delay int32 `json:"delay"`+ MentionedJID []string `json:"mentionedJid"`+ MentionAll bool `json:"mentionAll"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+}++type CarouselButtonStruct struct {+ Type string `json:"type"`+ DisplayText string `json:"displayText"`+ Id string `json:"id"`+ CopyCode string `json:"copyCode,omitempty"`+}++type CarouselCardHeaderStruct struct {+ Title string `json:"title"`+ Subtitle string `json:"subtitle"`+ ImageUrl string `json:"imageUrl,omitempty"`+ VideoUrl string `json:"videoUrl,omitempty"`+}++type CarouselCardBodyStruct struct {+ Text string `json:"text"`+}++type CarouselCardStruct struct {+ Header CarouselCardHeaderStruct `json:"header"`+ Body CarouselCardBodyStruct `json:"body"`+ Footer string `json:"footer,omitempty"`+ Buttons []CarouselButtonStruct `json:"buttons,omitempty"`+}++type CarouselStruct struct {+ Number string `json:"number"`+ Body string `json:"body,omitempty"`+ Footer string `json:"footer,omitempty"`+ Delay int32 `json:"delay"`+ FormatJid *bool `json:"formatJid,omitempty"`+ Quoted QuotedStruct `json:"quoted"`+ Cards []CarouselCardStruct `json:"cards"`+}++type MessageSendStruct struct {+ Info types.MessageInfo+ Message *waE2E.Message+ MessageContextInfo *waE2E.ContextInfo+}++func (s *sendService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := s.clientPointer[instanceId]+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := s.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = s.clientPointer[instanceId]+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ s.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++// ensureClientConnectedWithRetry attempts to ensure client connection with automatic reconnection and retry+func (s *sendService) ensureClientConnectedWithRetry(instanceId string, maxRetries int) (*whatsmeow.Client, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Connection attempt %d/%d", instanceId, attempt, maxRetries)++ client, err := s.ensureClientConnected(instanceId)+ if err == nil {+ return client, nil+ }++ // Check if it's a disconnection error that we can retry+ if err.Error() == "client disconnected" || err.Error() == "no active session found" {+ s.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Client disconnected on attempt %d/%d, attempting reconnection...", instanceId, attempt, maxRetries)++ // Attempt to reconnect the client+ reconnectErr := s.whatsmeowService.ReconnectClient(instanceId)+ if reconnectErr != nil {+ s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to reconnect client on attempt %d: %v", instanceId, attempt, reconnectErr)+ } else {+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Reconnection initiated on attempt %d, waiting 3 seconds...", instanceId, attempt)+ time.Sleep(3 * time.Second)+ }++ // If this is not the last attempt, continue to retry+ if attempt < maxRetries {+ waitTime := time.Duration(attempt*2) * time.Second // Progressive backoff+ s.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Waiting %v before retry attempt %d", instanceId, waitTime, attempt+1)+ time.Sleep(waitTime)+ continue+ }+ }++ // If it's the last attempt or a non-retryable error, return the error+ s.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to ensure client connection after %d attempts: %v", instanceId, attempt, err)+ return nil, err+ }++ return nil, fmt.Errorf("failed to connect client after %d attempts", maxRetries)+}++func validateMessageFields(phone string, formatJid *bool, messageID *string, participant *string) (types.JID, error) {+ // Apply formatting if formatJid is true (default)+ shouldFormat := true // Default value+ if formatJid != nil {+ shouldFormat = *formatJid+ }++ var finalPhone string+ if shouldFormat {+ // Extract raw number if it's already a JID, then apply CreateJID formatting+ rawNumber := phone+ if strings.Contains(phone, "@s.whatsapp.net") {+ rawNumber = strings.Split(phone, "@")[0]+ }++ normalizedJID, err := utils.CreateJID(rawNumber)+ if err != nil {+ // If CreateJID fails, try with ParseJID as fallback+ recipient, ok := utils.ParseJID(phone)+ if !ok {+ return types.NewJID("", types.DefaultUserServer), fmt.Errorf("could not parse phone: %s", phone)+ }+ finalPhone = recipient.String()+ } else {+ finalPhone = normalizedJID+ }+ } else {+ // Use phone as received without formatting+ finalPhone = phone+ }++ recipient, ok := utils.ParseJID(finalPhone)+ if !ok {+ return types.NewJID("", types.DefaultUserServer), errors.New("could not parse formatted phone")+ }++ if messageID != nil {+ if participant == nil {+ return types.NewJID("", types.DefaultUserServer), errors.New("missing Participant in ContextInfo")+ }+ }++ if participant != nil {+ if messageID == nil {+ return types.NewJID("", types.DefaultUserServer), errors.New("missing StanzaId in ContextInfo")+ }+ }++ return recipient, nil+}++// validateAndCheckUserExists validates message fields and checks if the user exists on WhatsApp+// Now uses the new approach: CheckUser with formatJid=false by default, and uses remoteJID for messaging+func (s *sendService) validateAndCheckUserExists(phone string, formatJid *bool, messageID *string, participant *string, instance *instance_model.Instance) (types.JID, error) {+ // Skip WhatsApp check if disabled in config+ if !s.config.CheckUserExists {+ s.loggerWrapper.GetLogger(instance.Id).LogDebug("[%s] User existence check disabled by configuration", instance.Id)+ // Use original validation logic when check is disabled+ return validateMessageFields(phone, formatJid, messageID, participant)+ }++ // Skip WhatsApp check for group messages, broadcast, newsletter, and LID+ if strings.Contains(phone, "@g.us") || strings.Contains(phone, "@broadcast") || strings.Contains(phone, "@newsletter") || strings.Contains(phone, "@lid") {+ return validateMessageFields(phone, formatJid, messageID, participant)+ }++ // Get the client to check if user exists on WhatsApp+ client, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return types.NewJID("", types.DefaultUserServer), fmt.Errorf("failed to connect client: %v", err)+ }++ // Use CheckUser approach: formatJid=false by default+ formatJidForCheck := false++ // First attempt with formatJid=false+ remoteJID, found, err := s.checkSingleUserExists(client, phone, formatJidForCheck, instance.Id)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Failed to check user existence: %v", instance.Id, err)+ // Continue with sending even if check fails (network issues, etc.)+ return validateMessageFields(phone, formatJid, messageID, participant)+ }++ // If not found with formatJid=false, try with formatJid=true as fallback+ if !found {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] User not found with formatJid=false, trying with formatJid=true", instance.Id)+ remoteJIDRetry, foundRetry, errRetry := s.checkSingleUserExists(client, phone, true, instance.Id)+ if errRetry == nil && foundRetry {+ remoteJID = remoteJIDRetry+ found = foundRetry+ }+ }++ if !found {+ return types.NewJID("", types.DefaultUserServer), fmt.Errorf("number %s is not registered on WhatsApp", phone)+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Number %s verified as valid WhatsApp user, using remoteJID: %s", instance.Id, phone, remoteJID)++ // Validate the remoteJID with formatJid=false for message sending+ formatJidFalse := false+ return validateMessageFields(remoteJID, &formatJidFalse, messageID, participant)+}++// checkSingleUserExists checks if a single user exists on WhatsApp with the specified formatJid setting+// Returns: remoteJID, found, error+func (s *sendService) checkSingleUserExists(client *whatsmeow.Client, phone string, formatJid bool, instanceId string) (string, bool, error) {+ phoneNumbers, err := utils.PrepareNumbersForWhatsAppCheck([]string{phone}, &formatJid)+ if err != nil {+ return "", false, fmt.Errorf("failed to prepare number for WhatsApp check: %v", err)+ }++ // Check if the number exists on WhatsApp+ resp, err := client.IsOnWhatsApp(context.Background(), phoneNumbers)+ if err != nil {+ return "", false, fmt.Errorf("failed to check if number %s exists on WhatsApp: %v", phoneNumbers[0], err)+ }++ // Verify if the number was found+ if len(resp) == 0 {+ return "", false, fmt.Errorf("number %s not found in WhatsApp response", phoneNumbers[0])+ }++ // Check if the first result indicates the number is on WhatsApp+ if !resp[0].IsIn {+ return "", false, nil // Not an error, just not found+ }++ // Return the remoteJID from WhatsApp's response+ remoteJID := fmt.Sprintf("%v", resp[0].JID)+ return remoteJID, true, nil+}++func findURL(text string) string {+ urlRegex := `http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+`+ re := regexp.MustCompile(urlRegex)+ urls := re.FindAllString(text, -1)+ if len(urls) > 0 {+ return urls[0]+ }+ return ""+}++func (s *sendService) SendText(data *TextStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ return s.sendTextWithRetry(data, instance, 3) // 3 tentativas máximas+}++func (s *sendService) sendTextWithRetry(data *TextStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendText attempt %d/%d", instance.Id, attempt, maxRetries)++ _, err := s.ensureClientConnectedWithRetry(instance.Id, 2)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ msg := &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: &data.Text,+ },+ }++ message, err := s.SendMessage(instance, msg, "ExtendedTextMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })++ if err != nil {+ // Check if it's a client disconnection error+ if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendText failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)+ if attempt < maxRetries {+ waitTime := time.Duration(attempt) * time.Second+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)+ time.Sleep(waitTime)+ continue+ }+ }+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendText successful on attempt %d", instance.Id, attempt)+ return message, nil+ }++ return nil, fmt.Errorf("failed to send text after %d attempts", maxRetries)+}++func fetchLinkMetadata(url string) (string, string, string, error) {+ resp, err := http.Get(url)+ if err != nil {+ return "", "", "", err+ }+ defer resp.Body.Close()++ doc, err := html.Parse(resp.Body)+ if err != nil {+ return "", "", "", err+ }++ var title, description, imgURL string++ var f func(*html.Node)+ f = func(n *html.Node) {+ if n.Type == html.ElementNode {+ if n.Data == "title" && n.FirstChild != nil {+ title = n.FirstChild.Data+ }+ if n.Data == "meta" {+ var property, content string+ for _, attr := range n.Attr {+ if attr.Key == "property" || attr.Key == "name" {+ property = attr.Val+ }+ if attr.Key == "content" {+ content = attr.Val+ }+ }++ if (property == "description" || property == "og:description") && content != "" {+ description = content+ }++ if property == "og:image" && content != "" {+ imgURL = content+ }+ }+ }++ for c := n.FirstChild; c != nil; c = c.NextSibling {+ f(c)+ }+ }++ f(doc)++ return title, description, imgURL, nil+}++func (s *sendService) SendLink(data *LinkStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ return s.sendLinkWithRetry(data, instance, 3)+}++func (s *sendService) sendLinkWithRetry(data *LinkStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendLink attempt %d/%d", instance.Id, attempt, maxRetries)++ _, err := s.ensureClientConnectedWithRetry(instance.Id, 2)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ matchedText := findURL(data.Text)++ if matchedText != "" {+ title, description, imgUrl, err := fetchLinkMetadata(matchedText)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ data.Title = title+ data.Description = description+ data.ImgUrl = imgUrl+ }++ var fileData []byte+ if data.ImgUrl != "" {+ resp, err := http.Get(data.ImgUrl)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }+ defer resp.Body.Close()+ fileData, _ = io.ReadAll(resp.Body)+ }++ msg := &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: &data.Text,+ Title: &data.Title,+ MatchedText: &matchedText,+ JPEGThumbnail: fileData,+ Description: &data.Description,+ },+ }++ message, err := s.SendMessage(instance, msg, "ExtendedTextMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })++ if err != nil {+ // Check if it's a client disconnection error+ if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendLink failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)+ if attempt < maxRetries {+ waitTime := time.Duration(attempt) * time.Second+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)+ time.Sleep(waitTime)+ continue+ }+ }+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendLink successful on attempt %d", instance.Id, attempt)+ return message, nil+ }++ return nil, fmt.Errorf("failed to send link after %d attempts", maxRetries)+}++type ConvertAudio struct {+ Url string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+}++type ApiResponse struct {+ Duration int `json:"duration"`+ Audio string `json:"audio"`+}++func convertAudioWithApi(apiUrl string, apiKey string, convertData ConvertAudio) ([]byte, int, error) {+ var requestBody bytes.Buffer+ writer := multipart.NewWriter(&requestBody)++ // Adiciona o campo "url" ao form-data se a URL for fornecida+ if convertData.Url != "" {+ err := writer.WriteField("url", convertData.Url)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao adicionar a URL no form-data: %v", err)+ }+ }++ // Adiciona o campo "base64" ao form-data se a string base64 for fornecida+ if convertData.Base64 != "" {+ err := writer.WriteField("base64", convertData.Base64)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao adicionar o base64 no form-data: %v", err)+ }+ }++ // Fecha o writer multipart+ err := writer.Close()+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao finalizar o form-data: %v", err)+ }++ req, err := http.NewRequest("POST", apiUrl, &requestBody)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao criar a requisição: %v", err)+ }++ req.Header.Set("Content-Type", writer.FormDataContentType())+ req.Header.Set("apikey", apiKey)++ client := &http.Client{}+ resp, err := client.Do(req)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao enviar a requisição: %v", err)+ }+ defer resp.Body.Close()++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao ler a resposta: %v", err)+ }++ if resp.StatusCode != http.StatusOK {+ return nil, 0, fmt.Errorf("requisição falhou com status: %d, resposta: %s", resp.StatusCode, string(body))+ }++ var apiResponse ApiResponse+ err = json.Unmarshal(body, &apiResponse)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao deserializar a resposta: %v", err)+ }++ base64ToBytes, err := base64.StdEncoding.DecodeString(apiResponse.Audio)+ if err != nil {+ return nil, 0, fmt.Errorf("erro ao decodificar o áudio: %v", err)+ }++ return base64ToBytes, apiResponse.Duration, nil+}++func convertAudioToOpusWithDuration(inputData []byte) ([]byte, int, error) {+ cmd := exec.Command("ffmpeg", "-i", "pipe:0",+ "-f",+ "ogg",+ "-vn",+ "-c:a",+ "libopus",+ "-avoid_negative_ts",+ "make_zero",+ "-b:a",+ "128k",+ "-ar",+ "48000",+ "-ac",+ "1",+ "-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:1",+ )++ var outBuffer bytes.Buffer+ var errBuffer bytes.Buffer++ cmd.Stdin = bytes.NewReader(inputData)+ cmd.Stdout = &outBuffer+ cmd.Stderr = &errBuffer++ err := cmd.Run()+ if err != nil {+ return nil, 0, fmt.Errorf("error during conversion: %v, details: %s", err, errBuffer.String())+ }++ convertedData := outBuffer.Bytes()++ outputText := errBuffer.String()++ splitTime := strings.Split(outputText, "time=")++ if len(splitTime) < 2 {+ return nil, 0, errors.New("duração não encontrada")+ }++ // Use the last occurrence of time= in case there are multiple+ timeString := splitTime[len(splitTime)-1]++ re := regexp.MustCompile(`(\d+):(\d+):(\d+\.\d+)`)+ matches := re.FindStringSubmatch(timeString)+ if len(matches) != 4 {+ return nil, 0, errors.New("formato de duração não encontrado")+ }++ hours, _ := strconv.ParseFloat(matches[1], 64)+ minutes, _ := strconv.ParseFloat(matches[2], 64)+ seconds, _ := strconv.ParseFloat(matches[3], 64)+ duration := int(hours*3600 + minutes*60 + seconds)++ return convertedData, duration, nil+}++func (s *sendService) SendMediaFile(data *MediaStruct, fileData []byte, instance *instance_model.Instance) (*MessageSendStruct, error) {+ return s.sendMediaFileWithRetry(data, fileData, instance, 3)+}++func (s *sendService) sendMediaFileWithRetry(data *MediaStruct, fileData []byte, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaFile attempt %d/%d", instance.Id, attempt, maxRetries)++ client, err := s.ensureClientConnectedWithRetry(instance.Id, 2)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ mime, _ := mimetype.DetectReader(bytes.NewReader(fileData))+ mimeType := mime.String()++ var uploadType whatsmeow.MediaType+ var duration int++ switch data.Type {+ case "image":+ if mimeType != "image/jpeg" && mimeType != "image/png" && mimeType != "image/webp" {+ errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted", mimeType)+ return nil, errors.New(errMsg)+ }+ if mimeType == "image/webp" {+ mimeType = "image/jpeg"+ }+ uploadType = whatsmeow.MediaImage+ case "video":+ if mimeType != "video/mp4" {+ errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'video/mp4' is accepted", mimeType)+ return nil, errors.New(errMsg)+ }+ uploadType = whatsmeow.MediaVideo+ case "audio":+ converterApiUrl := s.config.ApiAudioConverter+ converterApiKey := s.config.ApiAudioConverterKey+ var convertedData []byte+ var err error+ if converterApiUrl == "" {++ convertedData, duration, err = convertAudioToOpusWithDuration(fileData)+ if err != nil {+ return nil, err+ }+ } else {+ convertedData, duration, err = convertAudioWithApi(converterApiUrl, converterApiKey, ConvertAudio{Base64: base64.StdEncoding.EncodeToString(fileData)})+ if err != nil {+ return nil, err+ }+ }++ fileData = convertedData+ mimeType = "audio/ogg; codecs=opus"+ uploadType = whatsmeow.MediaAudio+ case "document":+ uploadType = whatsmeow.MediaDocument+ default:+ return nil, errors.New("invalid media type")+ }++ // Detectar se é newsletter para usar upload sem criptografia+ isNewsletter := strings.Contains(data.Number, "@newsletter")++ // Validar se é documento em newsletter (não suportado)+ if isNewsletter && data.Type == "document" {+ return nil, errors.New("documentos não são suportados em canais do WhatsApp. Use imagem, vídeo, áudio ou enquete")+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaFile - Upload iniciado (Newsletter: %v)...", instance.Id, isNewsletter)++ var uploaded whatsmeow.UploadResponse+ if isNewsletter {+ // Newsletter: upload SEM criptografia+ uploaded, err = client.UploadNewsletter(context.Background(), fileData, uploadType)+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Newsletter upload - Handle: %s", instance.Id, uploaded.Handle)+ } else {+ // Normal: upload COM criptografia+ uploaded, err = client.Upload(context.Background(), fileData, uploadType)+ }++ if err != nil {+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Media uploaded with size %d", instance.Id, uploaded.FileLength)++ var media *waE2E.Message+ var mediaType string++ switch data.Type {+ case "image":+ if isNewsletter {+ // Newsletter: SEM MediaKey e FileEncSHA256+ media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ Caption: proto.String(data.Caption),+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ // Normal: COM MediaKey e FileEncSHA256+ media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ Caption: proto.String(data.Caption),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "ImageMessage"+ case "video":+ if isNewsletter {+ media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{+ Caption: proto.String(data.Caption),+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{+ Caption: proto.String(data.Caption),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "VideoMessage"+ case "ptv":+ if isNewsletter {+ media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "PtvMessage"+ case "audio":+ if isNewsletter {+ media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ URL: &uploaded.URL,+ PTT: proto.Bool(true),+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ Seconds: proto.Uint32(uint32(duration)),+ }}+ } else {+ media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ URL: proto.String(uploaded.URL),+ PTT: proto.Bool(true),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uploaded.FileLength),+ Seconds: proto.Uint32(uint32(duration)),+ }}+ }+ mediaType = "AudioMessage"+ case "document":+ if isNewsletter {+ media = &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ FileName: &data.Filename,+ Caption: proto.String(data.Caption),+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ FileName: &data.Filename,+ Caption: proto.String(data.Caption),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }++ if media.GetDocumentMessage().GetCaption() != "" {+ media.DocumentWithCaptionMessage = &waE2E.FutureProofMessage{+ Message: &waE2E.Message{+ DocumentMessage: media.DocumentMessage,+ },+ }+ media.DocumentMessage = nil+ }++ mediaType = "DocumentMessage"+ default:+ return nil, errors.New("invalid media type")+ }++ message, err := s.SendMessage(instance, media, mediaType, &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ MediaHandle: uploaded.Handle,+ })++ if err != nil {+ // Check if it's a client disconnection error+ if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendMediaFile failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)+ if attempt < maxRetries {+ waitTime := time.Duration(attempt) * time.Second+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)+ time.Sleep(waitTime)+ continue+ }+ }+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaFile successful on attempt %d", instance.Id, attempt)+ return message, nil+ }++ return nil, fmt.Errorf("failed to send media file after %d attempts", maxRetries)+}++func (s *sendService) SendMediaUrl(data *MediaStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ return s.sendMediaUrlWithRetry(data, instance, 3)+}++func (s *sendService) sendMediaUrlWithRetry(data *MediaStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaUrl attempt %d/%d for URL: %s", instance.Id, attempt, maxRetries, data.Url)+ startTime := time.Now()++ client, err := s.ensureClientConnectedWithRetry(instance.Id, 2)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Iniciando download da URL: %s", instance.Id, data.Url)++ resp, err := http.Get(data.Url)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Download concluído em %v. Lendo dados...", instance.Id, time.Since(startTime))++ downloadStart := time.Now()+ fileData, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, err+ }+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Leitura dos dados concluída em %v. Tamanho: %d bytes", instance.Id, time.Since(downloadStart), len(fileData))++ mime, _ := mimetype.DetectReader(bytes.NewReader(fileData))+ mimeType := mime.String()+ if strings.HasSuffix(strings.ToLower(data.Url), ".mp4") {+ mimeType = "video/mp4"+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Tipo MIME detectado: %s", instance.Id, mimeType)++ var uploadType whatsmeow.MediaType+ var duration int++ processingStart := time.Now()+ switch data.Type {+ case "image":+ if mimeType != "image/jpeg" && mimeType != "image/png" && mimeType != "image/webp" {+ errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'image/jpeg', 'image/png' and 'image/webp' are accepted", mimeType)+ return nil, errors.New(errMsg)+ }+ if mimeType == "image/webp" {+ mimeType = "image/jpeg"+ }+ uploadType = whatsmeow.MediaImage++ case "video", "ptv":+ if mimeType != "video/mp4" {+ errMsg := fmt.Sprintf("Invalid file format: '%s'. Only 'video/mp4' are accepted", mimeType)+ return nil, errors.New(errMsg)+ }+ uploadType = whatsmeow.MediaVideo+ case "audio":+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Iniciando conversão de áudio...", instance.Id)+ converterApiUrl := s.config.ApiAudioConverter+ converterApiKey := s.config.ApiAudioConverterKey+ var convertedData []byte+ var err error+ if converterApiUrl == "" {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Usando conversão local...", instance.Id)+ convertedData, duration, err = convertAudioToOpusWithDuration(fileData)+ } else {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Usando API de conversão...", instance.Id)+ convertedData, duration, err = convertAudioWithApi(converterApiUrl, converterApiKey, ConvertAudio{Base64: base64.StdEncoding.EncodeToString(fileData)})+ }+ if err != nil {+ return nil, err+ }+ fileData = convertedData+ mimeType = "audio/ogg; codecs=opus"+ uploadType = whatsmeow.MediaAudio+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Conversão de áudio concluída em %v", instance.Id, time.Since(processingStart))+ case "document":+ uploadType = whatsmeow.MediaDocument+ default:+ return nil, errors.New("invalid media type")+ }++ // Detectar se é newsletter para usar upload sem criptografia+ isNewsletter := strings.Contains(data.Number, "@newsletter")++ // Validar se é documento em newsletter (não suportado)+ if isNewsletter && data.Type == "document" {+ return nil, errors.New("documentos não são suportados em canais do WhatsApp. Use imagem, vídeo, áudio ou enquete")+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Iniciando upload para WhatsApp (Newsletter: %v)...", instance.Id, isNewsletter)+ uploadStart := time.Now()++ var uploaded whatsmeow.UploadResponse+ if isNewsletter {+ // Newsletter: upload sem criptografia+ uploaded, err = client.UploadNewsletter(context.Background(), fileData, uploadType)+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Newsletter upload - Handle: %s", instance.Id, uploaded.Handle)+ } else {+ // Upload normal com criptografia+ uploaded, err = client.Upload(context.Background(), fileData, uploadType)+ }++ if err != nil {+ return nil, err+ }+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Upload concluído em %v. Tamanho: %d", instance.Id, time.Since(uploadStart), uploaded.FileLength)++ var media *waE2E.Message+ var mediaType string++ switch data.Type {+ case "image":+ if isNewsletter {+ // Newsletter: sem criptografia (sem MediaKey e FileEncSHA256)+ media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ Caption: proto.String(data.Caption),+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ // Normal: com criptografia+ media = &waE2E.Message{ImageMessage: &waE2E.ImageMessage{+ Caption: proto.String(data.Caption),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "ImageMessage"+ case "video":+ if isNewsletter {+ media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{+ Caption: proto.String(data.Caption),+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{VideoMessage: &waE2E.VideoMessage{+ Caption: proto.String(data.Caption),+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "VideoMessage"+ case "ptv":+ if isNewsletter {+ media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{+ URL: &uploaded.URL,+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{PtvMessage: &waE2E.VideoMessage{+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }+ mediaType = "PtvMessage"+ case "audio":+ if isNewsletter {+ media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ URL: &uploaded.URL,+ PTT: proto.Bool(true),+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ StreamingSidecar: []byte(*proto.String("QpmXDsU7YLagdg==")),+ Waveform: []byte(*proto.String("OjAnExISDgsKCAkJBwgkHAQEBBEFAwMNAxAcKCgkFzM0QUE4Jh4eKAoKChcLCwkeFgkJCQo3JiQmIiIRPz8/Ow==")),+ Seconds: proto.Uint32(uint32(duration)),+ }}+ } else {+ media = &waE2E.Message{AudioMessage: &waE2E.AudioMessage{+ URL: proto.String(uploaded.URL),+ PTT: proto.Bool(true),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uploaded.FileLength),+ StreamingSidecar: []byte(*proto.String("QpmXDsU7YLagdg==")),+ Waveform: []byte(*proto.String("OjAnExISDgsKCAkJBwgkHAQEBBEFAwMNAxAcKCgkFzM0QUE4Jh4eKAoKChcLCwkeFgkJCQo3JiQmIiIRPz8/Ow==")),+ Seconds: proto.Uint32(uint32(duration)),+ }}+ }+ mediaType = "AudioMessage"+ case "document":+ if isNewsletter {+ media = &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ URL: &uploaded.URL,+ FileName: &data.Filename,+ Caption: proto.String(data.Caption),+ DirectPath: &uploaded.DirectPath,+ Mimetype: proto.String(mimeType),+ FileSHA256: uploaded.FileSHA256,+ FileLength: &uploaded.FileLength,+ }}+ } else {+ media = &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{+ URL: proto.String(uploaded.URL),+ FileName: &data.Filename,+ Caption: proto.String(data.Caption),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(mimeType),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ }}+ }++ if media.GetDocumentMessage().GetCaption() != "" {+ media.DocumentWithCaptionMessage = &waE2E.FutureProofMessage{+ Message: &waE2E.Message{+ DocumentMessage: media.DocumentMessage,+ },+ }+ media.DocumentMessage = nil+ }++ mediaType = "DocumentMessage"+ default:+ return nil, errors.New("invalid media type")+ }++ messageStart := time.Now()+ message, err := s.SendMessage(instance, media, mediaType, &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ MediaHandle: uploaded.Handle,+ })++ if err != nil {+ // Check if it's a client disconnection error+ if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendMediaUrl failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)+ if attempt < maxRetries {+ waitTime := time.Duration(attempt) * time.Second+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)+ time.Sleep(waitTime)+ continue+ }+ }+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Mensagem enviada em %v", instance.Id, time.Since(messageStart))++ totalTime := time.Since(startTime)+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMediaUrl successful on attempt %d, processo completo em %v", instance.Id, attempt, totalTime)++ return message, nil+ }++ return nil, fmt.Errorf("failed to send media url after %d attempts", maxRetries)+}++func (s *sendService) SendPoll(data *PollStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ return s.sendPollWithRetry(data, instance, 3)+}++func (s *sendService) sendPollWithRetry(data *PollStruct, instance *instance_model.Instance, maxRetries int) (*MessageSendStruct, error) {+ for attempt := 1; attempt <= maxRetries; attempt++ {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendPoll attempt %d/%d", instance.Id, attempt, maxRetries)++ client, err := s.ensureClientConnectedWithRetry(instance.Id, 2)+ if err != nil {+ if attempt == maxRetries {+ return nil, err+ }+ continue+ }++ msg := client.BuildPollCreation(data.Question, data.Options, data.MaxAnswer)++ message, err := s.SendMessage(instance, msg, "PollCreationMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })++ if err != nil {+ // Check if it's a client disconnection error+ if strings.Contains(err.Error(), "client disconnected") || strings.Contains(err.Error(), "no active session") {+ s.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendPoll failed due to disconnection on attempt %d/%d: %v", instance.Id, attempt, maxRetries, err)+ if attempt < maxRetries {+ waitTime := time.Duration(attempt) * time.Second+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Waiting %v before retry", instance.Id, waitTime)+ time.Sleep(waitTime)+ continue+ }+ }+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendPoll successful on attempt %d", instance.Id, attempt)+ return message, nil+ }++ return nil, fmt.Errorf("failed to send poll after %d attempts", maxRetries)+}++func convertToWebP(imageData string) ([]byte, error) {+ var img image.Image+ var err error++ resp, err := http.Get(imageData)+ if err != nil {+ return nil, fmt.Errorf("failed to fetch image from URL: %v", err)+ }+ defer resp.Body.Close()++ img, _, err = image.Decode(resp.Body)+ if err != nil {+ return nil, fmt.Errorf("failed to decode image: %v", err)+ }++ var webpBuffer bytes.Buffer+ err = webp.Encode(&webpBuffer, img, &webp.Options{Lossless: false, Quality: 80})+ if err != nil {+ return nil, fmt.Errorf("failed to encode image to WebP: %v", err)+ }++ return webpBuffer.Bytes(), nil+}++func (s *sendService) SendSticker(data *StickerStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ client, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ var uploaded whatsmeow.UploadResponse+ var filedata []byte++ if strings.HasPrefix(data.Sticker, "http") {+ webpData, err := convertToWebP(data.Sticker)+ if err != nil {+ return nil, fmt.Errorf("failed to convert image to WebP: %v", err)+ }++ filedata = webpData++ uploaded, err = client.Upload(context.Background(), filedata, whatsmeow.MediaImage)+ if err != nil {+ return nil, fmt.Errorf("failed to upload sticker: %v", err)+ }+ } else {+ return nil, fmt.Errorf("invalid sticker URL")+ }++ msg := &waE2E.Message{StickerMessage: &waE2E.StickerMessage{+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String(http.DetectContentType(filedata)),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(filedata))),+ }}++ message, err := s.SendMessage(instance, msg, "StickerMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })+ if err != nil {+ return nil, err+ }++ return message, nil+}++func (s *sendService) SendLocation(data *LocationStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ _, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ msg := &waE2E.Message{LocationMessage: &waE2E.LocationMessage{+ DegreesLatitude: &data.Latitude,+ DegreesLongitude: &data.Longitude,+ Name: &data.Name,+ Address: &data.Address,+ }}++ message, err := s.SendMessage(instance, msg, "LocationMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })+ if err != nil {+ return nil, err+ }++ return message, nil+}++func (s *sendService) SendContact(data *ContactStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ _, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ VCstring := utils.GenerateVC(utils.VCardStruct{+ FullName: data.Vcard.FullName,+ Phone: data.Vcard.Phone,+ Organization: data.Vcard.Organization,+ })++ fmt.Println(VCstring)++ msg := &waE2E.Message{ContactMessage: &waE2E.ContactMessage{+ DisplayName: &data.Vcard.FullName,+ Vcard: &VCstring,+ }}++ messaged, err := s.SendMessage(instance, msg, "ContactMessage", &SendDataStruct{+ Id: data.Id,+ Number: data.Number,+ Quoted: data.Quoted,+ Delay: data.Delay,+ MentionAll: data.MentionAll,+ MentionedJID: data.MentionedJID,+ FormatJid: data.FormatJid,+ })+ if err != nil {+ return nil, err+ }++ return messaged, nil+}++func mapKeyType(keyType string) string {+ switch keyType {+ case "phone":+ return "PHONE"+ case "email":+ return "EMAIL"+ case "cpf":+ return "CPF"+ case "cnpj":+ return "CNPJ"+ case "random":+ return "EVP"+ default:+ return keyType+ }+}++func (s *sendService) SendButton(data *ButtonStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ client, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ hasReply := false+ hasPix := false+ hasOtherTypes := false+ replyCount := 0++ for _, v := range data.Buttons {+ switch v.Type {+ case "reply":+ hasReply = true+ replyCount+++ case "pix":+ hasPix = true+ default:+ hasOtherTypes = true+ }+ }++ if hasReply {+ if replyCount > 3 {+ return nil, errors.New("máximo de 3 botões do tipo 'reply' permitidos")+ }+ if hasOtherTypes {+ return nil, errors.New("botões do tipo 'reply' não podem ser misturados com outros tipos")+ }+ }++ if hasPix {+ if len(data.Buttons) > 1 {+ return nil, errors.New("botão do tipo 'pix' não pode ser combinado com outros botões")+ }+ }++ buttons := []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{}++ for _, v := range data.Buttons {+ var paramsJSON *string++ var name *string++ switch v.Type {+ case "reply":+ name = proto.String("quick_reply")+ paramsJSON = proto.String(`{"display_text":"` + v.DisplayText + `","id":"` + v.Id + `"}`)+ case "copy":+ name = proto.String("cta_copy")+ paramsJSON = proto.String(`{"display_text":"` + v.DisplayText + `","copy_code":"` + v.CopyCode + `"}`)+ case "url":+ name = proto.String("cta_url")+ paramsJSON = proto.String(`{"display_text":"` + v.DisplayText + `","url":"` + v.URL + `","merchant_url":"` + v.URL + `"}`)+ case "call":+ name = proto.String("cta_call")+ paramsJSON = proto.String(`{"display_text":"` + v.DisplayText + `","phone_number":"` + v.PhoneNumber + `"}`)+ case "pix":+ randomId := utils.GenerateRandomString(11)+ name = proto.String("payment_info")+ paramsJSON = proto.String(`{"currency":"` + v.Currency + `","total_amount":{"value":0,"offset":100},"reference_id":"` + randomId + `","type":"physical-goods","order":{"status":"pending","subtotal":{"value":0,"offset":100},"order_type":"ORDER","items":[{"name":"","amount":{"value":0,"offset":100},"quantity":0,"sale_amount":{"value":0,"offset":100}}]},"payment_settings":[{"type":"pix_static_code","pix_static_code":{"merchant_name":"` + v.Name + `","key":"` + v.Key + `","key_type":"` + mapKeyType(v.KeyType) + `"}}],"share_payment_status":false}`)+ }++ buttons = append(buttons, &waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{+ Name: name,+ ButtonParamsJSON: paramsJSON,+ })+ }++ messageId := client.GenerateMessageID()+ templateId := strconv.FormatInt(time.Now().UnixNano()/1000000, 10)+ messageParamsJSON := `{"from":"api","templateId":` + templateId + `}`++ var msg *waE2E.Message++ if hasPix {+ msg = &waE2E.Message{+ InteractiveMessage: &waE2E.InteractiveMessage{+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{+ NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{+ Buttons: buttons,+ MessageParamsJSON: &messageParamsJSON,+ },+ },+ },+ }+ } else {+ body := func() string {+ t := "*" + data.Title + "*"+ if data.Description != "" {+ t += "\n\n" + data.Description + "\n"+ }+ return t+ }()++ msg = &waE2E.Message{ViewOnceMessage: &waE2E.FutureProofMessage{+ Message: &waE2E.Message{+ InteractiveMessage: &waE2E.InteractiveMessage{+ Body: &waE2E.InteractiveMessage_Body{+ Text: &body,+ },+ Footer: &waE2E.InteractiveMessage_Footer{+ Text: &data.Footer,+ },+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{+ NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{+ Buttons: buttons,+ MessageParamsJSON: &messageParamsJSON,+ },+ },+ },+ },+ }}+ }++ recipient, err := s.validateAndCheckUserExists(data.Number, data.FormatJid, &data.Quoted.MessageID, &data.Quoted.MessageID, instance)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields or user check: %v", instance.Id, err)+ return nil, err+ }++ if data.Delay > 0 {+ err := client.SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(""))+ if err != nil {+ return nil, err+ }++ time.Sleep(time.Duration(data.Delay) * time.Millisecond)++ err = client.SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(""))+ if err != nil {+ return nil, err+ }+ }++ response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{ID: messageId})+ if err != nil {+ return nil, err+ }++ messageInfo := types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: recipient,+ Sender: *client.Store.ID,+ IsFromMe: true,+ IsGroup: false,+ },+ ID: messageId,+ Timestamp: time.Now(),+ ServerID: response.ServerID,+ Type: "ButtonMessage",+ }++ messageSent := &MessageSendStruct{+ Info: messageInfo,+ Message: msg,+ MessageContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ },+ }++ return messageSent, nil+}++func stringPointer(s string) *string {+ return &s+}++func sectionsToString(data *ListStruct) (string, error) {+ type row struct {+ Header *string `json:"header,omitempty"`+ Title string `json:"title"`+ Description *string `json:"description,omitempty"`+ ID string `json:"id"`+ }++ type listSection struct {+ Title string `json:"title"`+ Rows []row `json:"rows"`+ }++ type list struct {+ Title string `json:"title"`+ Sections []listSection `json:"sections"`+ }++ sections := []listSection{}++ for _, s := range data.Sections {+ rows := []row{}++ for _, r := range s.Rows {+ rows = append(rows, row{+ Title: r.Title,+ Description: stringPointer(r.Description),+ ID: r.RowId,+ })+ }++ section := listSection{+ Title: s.Title,+ Rows: rows,+ }++ sections = append(sections, section)+ }++ listData := list{+ Title: data.ButtonText,+ Sections: sections,+ }++ jsonData, err := json.Marshal(listData)+ if err != nil {+ return "", err+ }++ return string(jsonData), nil+}++func (s *sendService) SendList(data *ListStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ client, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ messageId := client.GenerateMessageID()++ templateId := strconv.FormatInt(time.Now().UnixNano()/1000000, 10)++ messageParamsJSON := `{"from":"api","templateId":` + templateId + `}`++ buttons := []*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{}++ sectionString, err := sectionsToString(data)+ if err != nil {+ return nil, err+ }++ buttons = append(buttons, &waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{+ Name: proto.String("single_select"),+ ButtonParamsJSON: proto.String(sectionString),+ })++ body := func() string {+ t := "*" + data.Title + "*"+ if data.Description != "" {+ t += "\n\n" + data.Description + "\n"+ }+ return t+ }()++ msg := &waE2E.Message{ViewOnceMessage: &waE2E.FutureProofMessage{+ Message: &waE2E.Message{+ InteractiveMessage: &waE2E.InteractiveMessage{+ Body: &waE2E.InteractiveMessage_Body{+ Text: &body,+ },+ Footer: &waE2E.InteractiveMessage_Footer{+ Text: &data.FooterText,+ },+ InteractiveMessage: &waE2E.InteractiveMessage_NativeFlowMessage_{+ NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{+ Buttons: buttons,+ MessageParamsJSON: &messageParamsJSON,+ },+ },+ },+ },+ }}++ recipient, err := s.validateAndCheckUserExists(data.Number, data.FormatJid, &data.Quoted.MessageID, &data.Quoted.MessageID, instance)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields or user check: %v", instance.Id, err)+ return nil, err+ }++ if data.Delay > 0 {+ err := client.SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(""))+ if err != nil {+ return nil, err+ }++ time.Sleep(time.Duration(data.Delay) * time.Millisecond)++ err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(""))+ if err != nil {+ return nil, err+ }+ }++ response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{ID: messageId})+ if err != nil {+ return nil, err+ }++ messageInfo := types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: recipient,+ Sender: *s.clientPointer[instance.Id].Store.ID,+ IsFromMe: true,+ IsGroup: false,+ },+ ID: messageId,+ Timestamp: time.Now(),+ ServerID: response.ServerID,+ Type: "ListMessage",+ }++ messageSent := &MessageSendStruct{+ Info: messageInfo,+ Message: msg,+ MessageContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ },+ }++ return messageSent, nil+}++func (s *sendService) SendMessage(instance *instance_model.Instance, msg *waE2E.Message, messageType string, data *SendDataStruct) (*MessageSendStruct, error) {+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] SendMessage called for number: %s, type: %s", instance.Id, data.Number, messageType)++ recipient, err := s.validateAndCheckUserExists(data.Number, data.FormatJid, &data.Quoted.MessageID, &data.Quoted.MessageID, instance)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields or user check: %v", instance.Id, err)+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Recipient validated: %s (Server: %s)", instance.Id, recipient.String(), recipient.Server)++ var message string+ if data.Id == "" {+ message = s.clientPointer[instance.Id].GenerateMessageID()+ } else {+ message = data.Id+ }++ if data.Delay > 0 {+ media := ""+ if messageType == "AudioMessage" {+ media = "audio"+ }++ err := s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("composing"), types.ChatPresenceMedia(media))+ if err != nil {+ return nil, err+ }++ time.Sleep(time.Duration(data.Delay) * time.Millisecond)++ err = s.clientPointer[instance.Id].SendChatPresence(context.Background(), recipient, types.ChatPresence("paused"), types.ChatPresenceMedia(media))+ if err != nil {+ return nil, err+ }+ }++ isMedia := false++ if data.Quoted.MessageID != "" {+ switch messageType {+ case "ExtendedTextMessage":+ msg.ExtendedTextMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ case "ImageMessage":+ msg.ImageMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ isMedia = true+ case "VideoMessage":+ msg.VideoMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ isMedia = true+ case "PtvMessage":+ msg.PtvMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ isMedia = true+ case "AudioMessage":+ msg.AudioMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ isMedia = true+ case "DocumentMessage":+ if msg.DocumentMessage != nil {+ msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ } else if msg.DocumentWithCaptionMessage != nil {+ msg.DocumentWithCaptionMessage.Message.DocumentMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ }+ isMedia = true+ case "PollCreationMessage":+ msg.PollCreationMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ case "StickerMessage":+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ isMedia = true+ case "LocationMessage":+ msg.LocationMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ case "ContactMessage":+ msg.ContactMessage.ContextInfo = &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ }+ default:+ return nil, fmt.Errorf("invalid messageType: %s", messageType)+ }+ } else {+ switch messageType {+ case "ExtendedTextMessage":+ msg.ExtendedTextMessage.ContextInfo = &waE2E.ContextInfo{}+ case "ImageMessage":+ msg.ImageMessage.ContextInfo = &waE2E.ContextInfo{}+ isMedia = true+ case "VideoMessage":+ msg.VideoMessage.ContextInfo = &waE2E.ContextInfo{}+ isMedia = true+ case "PtvMessage":+ msg.PtvMessage.ContextInfo = &waE2E.ContextInfo{}+ isMedia = true+ case "AudioMessage":+ msg.AudioMessage.ContextInfo = &waE2E.ContextInfo{}+ isMedia = true+ case "DocumentMessage":+ if msg.DocumentMessage != nil {+ msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}+ } else if msg.DocumentWithCaptionMessage != nil {+ msg.DocumentWithCaptionMessage.Message.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ isMedia = true+ case "PollCreationMessage":+ msg.PollCreationMessage.ContextInfo = &waE2E.ContextInfo{}+ case "StickerMessage":+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{}+ case "LocationMessage":+ msg.LocationMessage.ContextInfo = &waE2E.ContextInfo{}+ case "ContactMessage":+ msg.ContactMessage.ContextInfo = &waE2E.ContextInfo{}+ default:+ return nil, fmt.Errorf("invalid messageType: %s", messageType)+ }+ }++ isGroup := strings.Contains(data.Number, "@g.us")+ isNewsletter := strings.Contains(data.Number, "@newsletter")++ // Only try to get participants for actual groups, not newsletters+ if isGroup && !isNewsletter {+ if data.MentionAll {+ groupInfo, err := s.clientPointer[instance.Id].GetGroupInfo(context.Background(), recipient)+ if err != nil {+ return nil, err+ }++ var mentionedJIDs []string+ for _, participant := range groupInfo.Participants {+ mentionedJIDs = append(mentionedJIDs, participant.JID.String())+ }++ switch messageType {+ case "ExtendedTextMessage":+ if msg.ExtendedTextMessage.ContextInfo == nil {+ msg.ExtendedTextMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ExtendedTextMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "ImageMessage":+ if msg.ImageMessage.ContextInfo == nil {+ msg.ImageMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ImageMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "VideoMessage":+ if msg.VideoMessage.ContextInfo == nil {+ msg.VideoMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.VideoMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "PtvMessage":+ if msg.PtvMessage.ContextInfo == nil {+ msg.PtvMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.PtvMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "AudioMessage":+ if msg.AudioMessage.ContextInfo == nil {+ msg.AudioMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.AudioMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "DocumentMessage":+ if msg.DocumentMessage.ContextInfo == nil {+ msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.DocumentMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "PollCreationMessage":+ if msg.PollCreationMessage.ContextInfo == nil {+ msg.PollCreationMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.PollCreationMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "StickerMessage":+ if msg.StickerMessage.ContextInfo == nil {+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.StickerMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "LocationMessage":+ if msg.LocationMessage.ContextInfo == nil {+ msg.LocationMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.LocationMessage.ContextInfo.MentionedJID = mentionedJIDs+ case "ContactMessage":+ if msg.ContactMessage.ContextInfo == nil {+ msg.ContactMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ContactMessage.ContextInfo.MentionedJID = mentionedJIDs+ }++ }++ if len(data.MentionedJID) > 0 {+ switch messageType {+ case "ExtendedTextMessage":+ if msg.ExtendedTextMessage.ContextInfo == nil {+ msg.ExtendedTextMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ExtendedTextMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "ImageMessage":+ if msg.ImageMessage.ContextInfo == nil {+ msg.ImageMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ImageMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "VideoMessage":+ if msg.VideoMessage.ContextInfo == nil {+ msg.VideoMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.VideoMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "PtvMessage":+ if msg.PtvMessage.ContextInfo == nil {+ msg.PtvMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.PtvMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "AudioMessage":+ if msg.AudioMessage.ContextInfo == nil {+ msg.AudioMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.AudioMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "DocumentMessage":+ if msg.DocumentMessage.ContextInfo == nil {+ msg.DocumentMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.DocumentMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "PollCreationMessage":+ if msg.PollCreationMessage.ContextInfo == nil {+ msg.PollCreationMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.PollCreationMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "StickerMessage":+ if msg.StickerMessage.ContextInfo == nil {+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.StickerMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "LocationMessage":+ if msg.LocationMessage.ContextInfo == nil {+ msg.LocationMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.LocationMessage.ContextInfo.MentionedJID = data.MentionedJID+ case "ContactMessage":+ if msg.ContactMessage.ContextInfo == nil {+ msg.ContactMessage.ContextInfo = &waE2E.ContextInfo{}+ }+ msg.ContactMessage.ContextInfo.MentionedJID = data.MentionedJID+ }+ }+ }++ recipient.User = strings.ReplaceAll(recipient.User, "+", "")++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Sending message to %s with ID %s", instance.Id, recipient.String(), message)++ // Preparar extra parameters para o envio+ sendExtra := whatsmeow.SendRequestExtra{ID: message}++ // Para newsletters/canais, adicionar o MediaHandle se houver mídia+ if recipient.Server == "newsletter" && data.MediaHandle != "" {+ sendExtra.MediaHandle = data.MediaHandle+ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Newsletter detected, using MediaHandle: %s", instance.Id, data.MediaHandle)+ }++ response, err := s.clientPointer[instance.Id].SendMessage(context.Background(), recipient, msg, sendExtra)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending message: %v", instance.Id, err)+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent successfully! ServerID: %d", instance.Id, response.ServerID)++ messageInfo := types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: recipient,+ Sender: *s.clientPointer[instance.Id].Store.ID,+ IsFromMe: true,+ IsGroup: isGroup,+ },+ ID: message,+ Timestamp: time.Now(),+ ServerID: response.ServerID,+ Type: messageType,+ }++ messageSent := &MessageSendStruct{+ Info: messageInfo,+ Message: msg,+ MessageContextInfo: &waE2E.ContextInfo{+ StanzaID: proto.String(data.Quoted.MessageID),+ Participant: proto.String(data.Quoted.Participant),+ QuotedMessage: &waE2E.Message{Conversation: proto.String("")},+ },+ }++ postMap := make(map[string]interface{})+ postMap["event"] = "SendMessage"++ // Convertendo o MessageSendStruct para map antes de atribuir+ messageData := make(map[string]interface{})+ messageData["Info"] = messageSent.Info++ // Convertendo a mensagem para map usando json marshal/unmarshal+ msgBytes, err := json.Marshal(messageSent.Message)+ if err != nil {+ return nil, fmt.Errorf("failed to marshal message: %v", err)+ }++ var msgMap map[string]interface{}+ if err := json.Unmarshal(msgBytes, &msgMap); err != nil {+ return nil, fmt.Errorf("failed to unmarshal message: %v", err)+ }++ messageData["Message"] = msgMap+ messageData["MessageContextInfo"] = messageSent.MessageContextInfo++ postMap["data"] = messageData++ if isMedia && s.config.WebhookFiles {+ var data []byte+ var err error++ img := msg.GetImageMessage()+ audio := msg.GetAudioMessage()+ document := msg.GetDocumentMessage()+ video := msg.GetVideoMessage()+ sticker := msg.GetStickerMessage()++ if img != nil {+ data, err = s.clientPointer[instance.Id].Download(context.Background(), img)+ } else if audio != nil {+ data, err = s.clientPointer[instance.Id].Download(context.Background(), audio)+ } else if document != nil {+ data, err = s.clientPointer[instance.Id].Download(context.Background(), document)+ } else if video != nil {+ data, err = s.clientPointer[instance.Id].Download(context.Background(), video)+ } else if sticker != nil {+ data, err = s.clientPointer[instance.Id].Download(context.Background(), sticker)++ webpReader := bytes.NewReader(data)+ img, err := webp.Decode(webpReader)+ if err == nil {+ var pngBuffer bytes.Buffer+ err = png.Encode(&pngBuffer, img)+ if err == nil {+ data = pngBuffer.Bytes()+ }+ }+ }++ if err == nil {+ // Acessando o Message do map já convertido+ messageMap := msgMap+ if messageMap == nil {+ messageMap = make(map[string]interface{})+ }++ encodeData := base64.StdEncoding.EncodeToString(data)+ messageMap["base64"] = encodeData++ messageData["Message"] = messageMap+ }+ }++ postMap["instanceToken"] = instance.Token+ postMap["instanceId"] = instance.Id+ postMap["instanceName"] = instance.Name++ var queueName string++ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", instance.Id, postMap["event"]))+ }++ values, err := json.Marshal(postMap)+ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to marshal JSON for queue", instance.Id)+ return nil, err+ }++ go s.whatsmeowService.CallWebhook(instance, queueName, values)++ if s.config.AmqpGlobalEnabled || s.config.NatsGlobalEnabled {+ go s.whatsmeowService.SendToGlobalQueues(postMap["event"].(string), values, instance.Id)+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent to %s", instance.Id, data.Number)+ return messageSent, nil+}++func (s *sendService) SendCarousel(data *CarouselStruct, instance *instance_model.Instance) (*MessageSendStruct, error) {+ client, err := s.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ formatJid := true+ if data.FormatJid != nil {+ formatJid = *data.FormatJid+ }++ var recipient types.JID+ var ok bool+ recipient, ok = utils.ParseJID(data.Number)+ if !ok && formatJid {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)+ return nil, errors.New("invalid phone number")+ } else if !ok && !formatJid {+ recipient = types.JID{+ User: data.Number,+ Server: types.DefaultUserServer,+ }+ }++ // Build carousel cards+ cards := make([]*waE2E.InteractiveMessage, len(data.Cards))+ messageVersion := int32(1)++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Building carousel for %s with %d cards", instance.Id, recipient.String(), len(data.Cards))++ for i, card := range data.Cards {+ // Each card MUST have both header and body for carousel to work+ interactiveCard := &waE2E.InteractiveMessage{+ Body: &waE2E.InteractiveMessage_Body{+ Text: proto.String(card.Body.Text),+ },+ Header: &waE2E.InteractiveMessage_Header{+ Title: proto.String(card.Header.Title),+ Subtitle: proto.String(card.Header.Subtitle),+ HasMediaAttachment: proto.Bool(false),+ },+ }++ // Add media to header if URL provided+ if card.Header.ImageUrl != "" || card.Header.VideoUrl != "" {+ header := interactiveCard.Header++ // Add media to header if URL provided+ if card.Header.ImageUrl != "" {+ // Download and upload image+ resp, err := http.Get(card.Header.ImageUrl)+ if err == nil {+ defer resp.Body.Close()+ fileData, err := io.ReadAll(resp.Body)+ if err == nil {+ uploaded, err := client.Upload(context.Background(), fileData, whatsmeow.MediaImage)+ if err == nil {+ header.HasMediaAttachment = proto.Bool(true)+ header.Media = &waE2E.InteractiveMessage_Header_ImageMessage{+ ImageMessage: &waE2E.ImageMessage{+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String("image/jpeg"),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ },+ }+ }+ }+ }+ } else if card.Header.VideoUrl != "" {+ // Download and upload video+ resp, err := http.Get(card.Header.VideoUrl)+ if err == nil {+ defer resp.Body.Close()+ fileData, err := io.ReadAll(resp.Body)+ if err == nil {+ uploaded, err := client.Upload(context.Background(), fileData, whatsmeow.MediaVideo)+ if err == nil {+ header.HasMediaAttachment = proto.Bool(true)+ header.Media = &waE2E.InteractiveMessage_Header_VideoMessage{+ VideoMessage: &waE2E.VideoMessage{+ URL: proto.String(uploaded.URL),+ DirectPath: proto.String(uploaded.DirectPath),+ MediaKey: uploaded.MediaKey,+ Mimetype: proto.String("video/mp4"),+ FileEncSHA256: uploaded.FileEncSHA256,+ FileSHA256: uploaded.FileSHA256,+ FileLength: proto.Uint64(uint64(len(fileData))),+ },+ }+ }+ }+ }+ }+ }++ // Add footer if exists+ if card.Footer != "" {+ interactiveCard.Footer = &waE2E.InteractiveMessage_Footer{+ Text: proto.String(card.Footer),+ }+ }++ // Add buttons if exist+ if len(card.Buttons) > 0 {+ buttons := make([]*waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton, len(card.Buttons))+ for j, btn := range card.Buttons {+ buttonType := strings.ToUpper(btn.Type)+ if buttonType == "" {+ buttonType = "REPLY" // Default type+ }++ var buttonName string+ var buttonParams string++ switch buttonType {+ case "URL":+ // URL button - opens a link+ buttonName = "cta_url"+ buttonParams = fmt.Sprintf(`{"display_text":"%s","url":"%s"}`, btn.DisplayText, btn.Id)+ case "CALL":+ // Call button - initiates a phone call+ buttonName = "cta_call"+ buttonParams = fmt.Sprintf(`{"display_text":"%s","phone_number":"%s"}`, btn.DisplayText, btn.Id)+ case "COPY":+ // Copy button - copies text to clipboard+ buttonName = "cta_copy"+ buttonParams = fmt.Sprintf(`{"display_text":"%s","copy_code":"%s"}`, btn.DisplayText, btn.CopyCode)+ case "REPLY":+ fallthrough+ default:+ // Quick reply button (default)+ buttonName = "quick_reply"+ buttonParams = fmt.Sprintf(`{"display_text":"%s","id":"%s"}`, btn.DisplayText, btn.Id)+ }++ buttons[j] = &waE2E.InteractiveMessage_NativeFlowMessage_NativeFlowButton{+ Name: proto.String(buttonName),+ ButtonParamsJSON: proto.String(buttonParams),+ }+ }++ // messageParamsJSON is REQUIRED for NativeFlowMessage with buttons+ messageParamsJSON := fmt.Sprintf(`{"from":"api","templateId":"%d"}`, time.Now().UnixNano()/1000000)++ interactiveCard.InteractiveMessage = &waE2E.InteractiveMessage_NativeFlowMessage_{+ NativeFlowMessage: &waE2E.InteractiveMessage_NativeFlowMessage{+ Buttons: buttons,+ MessageParamsJSON: proto.String(messageParamsJSON),+ MessageVersion: proto.Int32(1),+ },+ }+ }++ cards[i] = interactiveCard+ }++ // Build carousel message+ carouselCardType := waE2E.InteractiveMessage_CarouselMessage_HSCROLL_CARDS+ interactiveMsg := &waE2E.InteractiveMessage{+ InteractiveMessage: &waE2E.InteractiveMessage_CarouselMessage_{+ CarouselMessage: &waE2E.InteractiveMessage_CarouselMessage{+ Cards: cards,+ MessageVersion: &messageVersion,+ CarouselCardType: &carouselCardType,+ },+ },+ }++ // Add body if provided (main message above carousel)+ if data.Body != "" {+ interactiveMsg.Body = &waE2E.InteractiveMessage_Body{+ Text: proto.String(data.Body),+ }+ }++ // Add footer if provided (text below carousel)+ if data.Footer != "" {+ interactiveMsg.Footer = &waE2E.InteractiveMessage_Footer{+ Text: proto.String(data.Footer),+ }+ }++ // ContextInfo is REQUIRED for iOS compatibility+ // Even if empty, iOS requires this field to display carousel+ contextInfo := &waE2E.ContextInfo{}++ // Add quoted message if exists+ if data.Quoted.MessageID != "" {+ contextInfo.StanzaID = proto.String(data.Quoted.MessageID)+ if data.Quoted.Participant != "" {+ participantJID, ok := utils.ParseJID(data.Quoted.Participant)+ if ok {+ contextInfo.Participant = proto.String(participantJID.String())+ }+ }+ }++ // Always set ContextInfo (required for iOS)+ interactiveMsg.ContextInfo = contextInfo++ // Build final message with MessageContextInfo for proper notification delivery+ msg := &waE2E.Message{+ InteractiveMessage: interactiveMsg,+ MessageContextInfo: &waE2E.MessageContextInfo{+ DeviceListMetadata: &waE2E.DeviceListMetadata{},+ },+ }++ message, err := s.SendMessage(instance, msg, "InteractiveMessage", &SendDataStruct{+ Number: data.Number,+ Delay: data.Delay,+ })++ if err != nil {+ s.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error sending carousel: %v", instance.Id, err)+ return nil, err+ }++ s.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Carousel sent to %s with %d cards", instance.Id, data.Number, len(data.Cards))+ return message, nil+}++func NewSendService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ config *config.Config,+ loggerWrapper *logger_wrapper.LoggerManager,+) SendService {+ return &sendService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ config: config,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/server/handler/server_handler.go b/pkg/server/handler/server_handler.gonew file mode 100644index 0000000..d20bd73--- /dev/null+++ b/pkg/server/handler/server_handler.go@@ -0,0 +1,21 @@+package server_handler++import "github.com/gin-gonic/gin"++type ServerHandler interface {+ ServerOk(ctx *gin.Context)+}++type serverHandler struct {+}++// ServerOk implements ServerHandler.+func (s *serverHandler) ServerOk(ctx *gin.Context) {+ ctx.JSON(200, gin.H{+ "status": "ok",+ })+}++func NewServerHandler() ServerHandler {+ return &serverHandler{}+}diff --git a/pkg/storage/interfaces/media_storage.go b/pkg/storage/interfaces/media_storage.gonew file mode 100644index 0000000..07b6a66--- /dev/null+++ b/pkg/storage/interfaces/media_storage.go@@ -0,0 +1,15 @@+package storage_interfaces++import "context"++// MediaStorage defines the contract for storing and retrieving media files+type MediaStorage interface {+ // Store saves the media data and returns a public URL to access it+ Store(ctx context.Context, data []byte, fileName string, contentType string) (string, error)++ // Delete removes the stored media+ Delete(ctx context.Context, fileName string) error++ // GetURL returns the public URL for accessing the media+ GetURL(ctx context.Context, fileName string) (string, error)+}diff --git a/pkg/storage/minio/media_storage.go b/pkg/storage/minio/media_storage.gonew file mode 100644index 0000000..042a19c--- /dev/null+++ b/pkg/storage/minio/media_storage.go@@ -0,0 +1,155 @@+package minio_storage++import (+ "bytes"+ "context"+ "fmt"+ "net/url"+ "strings"+ "time"++ storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"+ "github.com/minio/minio-go/v7"+ "github.com/minio/minio-go/v7/pkg/credentials"+)++type MinioMediaStorage struct {+ client *minio.Client+ bucketName string+ baseURL string+}++func setBucketPolicy(client *minio.Client, bucketName string) error {+ policy := `{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": "*",+ "Action": ["s3:GetObject"],+ "Resource": ["arn:aws:s3:::` + bucketName + `/*"]+ }+ ]+ }`++ return client.SetBucketPolicy(context.Background(), bucketName, policy)+}++// generateFilePath creates a simple media folder structure+// Format: evolution-go-medias/{filename}+func generateFilePath(fileName string) string {+ return fmt.Sprintf("evolution-go-medias/%s", fileName)+}++// resolveFilePath determines if the input is a full path or just a filename+// If it's just a filename, it assumes it's in the evolution-go-medias folder+// If it's a full path, it returns it as-is+func (m *MinioMediaStorage) resolveFilePath(ctx context.Context, fileNameOrPath string) (string, error) {+ // If the input already contains path separators, assume it's a full path+ if strings.Contains(fileNameOrPath, "/") {+ return fileNameOrPath, nil+ }++ // If it's just a filename, assume it's in the evolution-go-medias folder+ return fmt.Sprintf("evolution-go-medias/%s", fileNameOrPath), nil+}++func NewMinioMediaStorage(+ endpoint,+ accessKeyID,+ secretAccessKey,+ bucketName,+ region string,+ useSSL bool,+) (storage_interfaces.MediaStorage, error) {+ client, err := minio.New(endpoint, &minio.Options{+ Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),+ Secure: useSSL,+ Region: region,+ })+ if err != nil {+ return nil, fmt.Errorf("failed to create MinIO client: %w", err)+ }++ // Try to set bucket policy to allow public access (optional for some providers)+ err = setBucketPolicy(client, bucketName)+ if err != nil {+ // Some providers (like Backblaze B2) don't support SetBucketPolicy+ // Log warning but continue - files can still be accessed via presigned URLs+ fmt.Printf("Warning: Failed to set bucket policy (provider may not support it): %v\n", err)+ }++ baseURL := fmt.Sprintf("https://%s/%s", endpoint, bucketName)+ if !useSSL {+ baseURL = fmt.Sprintf("http://%s/%s", endpoint, bucketName)+ }++ return &MinioMediaStorage{+ client: client,+ bucketName: bucketName,+ baseURL: baseURL,+ }, nil+}++func (m *MinioMediaStorage) Store(ctx context.Context, data []byte, fileName string, contentType string) (string, error) {+ // Generate organized file path+ filePath := generateFilePath(fileName)+ reader := bytes.NewReader(data)++ _, err := m.client.PutObject(ctx, m.bucketName, filePath, reader, int64(len(data)), minio.PutObjectOptions{+ ContentType: contentType,+ })+ if err != nil {+ return "", fmt.Errorf("failed to store object: %w", err)+ }++ // Gerando URL assinada com validade de 7 dias+ reqParams := make(url.Values)+ presignedURL, err := m.client.PresignedGetObject(ctx, m.bucketName, filePath, time.Hour*24*7, reqParams)+ if err != nil {+ return "", fmt.Errorf("failed to generate presigned URL: %w", err)+ }++ fmt.Println(presignedURL.String())++ return presignedURL.String(), nil+}++func (m *MinioMediaStorage) Delete(ctx context.Context, fileName string) error {+ // Resolve the full path for the file+ filePath, err := m.resolveFilePath(ctx, fileName)+ if err != nil {+ return fmt.Errorf("failed to resolve file path: %w", err)+ }++ err = m.client.RemoveObject(ctx, m.bucketName, filePath, minio.RemoveObjectOptions{})+ if err != nil {+ return fmt.Errorf("failed to delete object: %w", err)+ }+ return nil+}++func (m *MinioMediaStorage) GetURL(ctx context.Context, fileName string) (string, error) {+ // Resolve the full path for the file+ filePath, err := m.resolveFilePath(ctx, fileName)+ if err != nil {+ return "", fmt.Errorf("failed to resolve file path: %w", err)+ }++ // Check if object exists+ _, err = m.client.StatObject(ctx, m.bucketName, filePath, minio.StatObjectOptions{})+ if err != nil {+ return "", fmt.Errorf("failed to get object stats: %w", err)+ }++ // Gerando URL assinada com validade de 7 dias+ reqParams := make(url.Values)+ presignedURL, err := m.client.PresignedGetObject(ctx, m.bucketName, filePath, time.Hour*24*7, reqParams)+ if err != nil {+ return "", fmt.Errorf("failed to generate presigned URL: %w", err)+ }++ fmt.Println(presignedURL.String())++ return presignedURL.String(), nil+}diff --git a/pkg/telemetry/telemetry.go b/pkg/telemetry/telemetry.gonew file mode 100644index 0000000..067a543--- /dev/null+++ b/pkg/telemetry/telemetry.go@@ -0,0 +1,62 @@+package telemetry++import (+ "bytes"+ "encoding/json"+ "log"+ "net/http"+ "time"++ "github.com/gin-gonic/gin"+)++type TelemetryData struct {+ Route string `json:"route"`+ APIVersion string `json:"apiVersion"`+ Timestamp time.Time `json:"timestamp"`+}++type telemetryService struct{}++func (t *telemetryService) TelemetryMiddleware() gin.HandlerFunc {+ return func(c *gin.Context) {+ route := c.FullPath()+ go SendTelemetry(route)+ c.Next()+ }+}++type TelemetryService interface {+ TelemetryMiddleware() gin.HandlerFunc+}++func SendTelemetry(route string) {+ if route == "/" {+ return+ }++ telemetry := TelemetryData{+ Route: route,+ APIVersion: "evo-go",+ Timestamp: time.Now(),+ }++ url := "https://log.evolution-api.com/telemetry"++ data, err := json.Marshal(telemetry)+ if err != nil {+ log.Println("Erro ao serializar telemetria:", err)+ return+ }++ resp, err := http.Post(url, "application/json", bytes.NewBuffer(data))+ if err != nil {+ log.Println("Erro ao enviar telemetria:", err)+ return+ }+ defer resp.Body.Close()+}++func NewTelemetryService() TelemetryService {+ return &telemetryService{}+}diff --git a/pkg/user/handler/user_handler.go b/pkg/user/handler/user_handler.gonew file mode 100644index 0000000..1350c7e--- /dev/null+++ b/pkg/user/handler/user_handler.go@@ -0,0 +1,551 @@+package user_handler++import (+ "net/http"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"+ "github.com/gin-gonic/gin"+)++type UserHandler interface {+ GetUser(ctx *gin.Context)+ CheckUser(ctx *gin.Context)+ GetAvatar(ctx *gin.Context)+ GetContacts(ctx *gin.Context)+ GetPrivacy(ctx *gin.Context)+ SetPrivacy(ctx *gin.Context)+ BlockContact(ctx *gin.Context)+ UnblockContact(ctx *gin.Context)+ GetBlockList(ctx *gin.Context)+ SetProfilePicture(ctx *gin.Context)+ SetProfileName(ctx *gin.Context)+ SetProfileStatus(ctx *gin.Context)+}++type userHandler struct {+ userService user_service.UserService+}++// Get a user+// @Summary Get a user+// @Description Get a user+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.CheckUserStruct true "User data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/info [post]+func (u *userHandler) GetUser(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.CheckUserStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if len(data.Number) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ uc, err := u.userService.GetUser(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": uc})+}++// Check a user+// @Summary Check a user+// @Description Check a user+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.CheckUserStruct true "User data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/check [post]+func (u *userHandler) CheckUser(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.CheckUserStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if len(data.Number) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ uc, err := u.userService.CheckUser(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": uc})+}++// Get a user's avatar+// @Summary Get a user's avatar+// @Description Get a user's avatar+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.GetAvatarStruct true "Avatar data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/avatar [post]+func (u *userHandler) GetAvatar(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.GetAvatarStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if len(data.Number) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ pic, err := u.userService.GetAvatar(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": pic})+}++// Get a user's contacts+// @Summary Get a user's contacts+// @Description Get a user's contacts+// @Tags User+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/contacts [get]+func (u *userHandler) GetContacts(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ contacts, err := u.userService.GetContacts(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": contacts})+}++// Get a user's privacy settings+// @Summary Get a user's privacy settings+// @Description Get a user's privacy settings+// @Tags User+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/privacy [get]+func (u *userHandler) GetPrivacy(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ privacy, err := u.userService.GetPrivacy(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": privacy})+}++// Set a user's privacy settings+// @Summary Set a user's privacy settings+// @Description Set a user's privacy settings+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.PrivacyStruct true "Privacy data"+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/privacy [post]+func (u *userHandler) SetPrivacy(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.PrivacyStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.CallAdd == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "call add is required"})+ return+ }++ if data.GroupAdd == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "group add is required"})+ return+ }++ if data.LastSeen == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "last seen is required"})+ return+ }++ if data.Online == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "online is required"})+ return+ }++ if data.Profile == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "profile is required"})+ return+ }++ if data.ReadReceipts == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "read receipts is required"})+ return+ }++ if data.Status == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "status is required"})+ return+ }++ privacy, err := u.userService.SetPrivacy(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": privacy})+}++// Block a contact+// @Summary Block a contact+// @Description Block a contact+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.BlockStruct true "Block data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/block [post]+func (u *userHandler) BlockContact(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.BlockStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if len(data.Number) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ resp, err := u.userService.BlockContact(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Unblock a contact+// @Summary Unblock a contact+// @Description Unblock a contact+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.BlockStruct true "Block data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/unblock [post]+func (u *userHandler) UnblockContact(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.BlockStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if len(data.Number) < 1 {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ if data.Number == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})+ return+ }++ resp, err := u.userService.UnlockContact(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Get a user's block list+// @Summary Get a user's block list+// @Description Get a user's block list+// @Tags User+// @Accept json+// @Produce json+// @Success 200 {object} gin.H "success"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/blocklist [get]+func (u *userHandler) GetBlockList(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ resp, err := u.userService.GetBlockList(instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": resp})+}++// Set a user's profile picture+// @Summary Set a user's profile picture+// @Description Set a user's profile picture+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.SetProfilePictureStruct true "Profile picture data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/profilePicture [post]+func (u *userHandler) SetProfilePicture(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.SetProfilePictureStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Image == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})+ return+ }++ resp, err := u.userService.SetProfilePicture(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ if !resp {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})+ return+ }++ responseData := gin.H{"image": data.Image}++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Set a user's profile name+// @Summary Set a user's profile name+// @Description Set a user's profile name+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.SetProfilePictureStruct true "Profile name data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/profileName [post]+func (u *userHandler) SetProfileName(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.SetProfileNameStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Name == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ resp, err := u.userService.SetProfileName(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ if !resp {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})+ return+ }++ responseData := gin.H{"name": data.Name}++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++// Set a user's profile status+// @Summary Set a user's profile status+// @Description Set a user's profile status+// @Tags User+// @Accept json+// @Produce json+// @Param message body user_service.SetProfilePictureStruct true "Profile status data"+// @Success 200 {object} gin.H "success"+// @Failure 400 {object} gin.H "Error on validation"+// @Failure 500 {object} gin.H "Internal server error"+// @Router /user/profileStatus [post]+func (u *userHandler) SetProfileStatus(ctx *gin.Context) {+ getInstance := ctx.MustGet("instance")++ instance, ok := getInstance.(*instance_model.Instance)+ if !ok {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})+ return+ }++ var data *user_service.SetProfileStatusStruct+ err := ctx.ShouldBindBodyWithJSON(&data)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if data.Status == "" {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})+ return+ }++ resp, err := u.userService.SetProfileStatus(data, instance)+ if err != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }++ if !resp {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to set profile picture"})+ return+ }++ responseData := gin.H{"status": data.Status}++ ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})+}++func NewUserHandler(+ userService user_service.UserService,+) UserHandler {+ return &userHandler{+ userService: userService,+ }+}diff --git a/pkg/user/service/user_service.go b/pkg/user/service/user_service.gonew file mode 100644index 0000000..1ac63b1--- /dev/null+++ b/pkg/user/service/user_service.go@@ -0,0 +1,553 @@+package user_service++import (+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "time"++ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+ whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++type UserService interface {+ GetUser(data *CheckUserStruct, instance *instance_model.Instance) (*UserCollection, error)+ CheckUser(data *CheckUserStruct, instance *instance_model.Instance) (*CheckUserCollection, error)+ GetAvatar(data *GetAvatarStruct, instance *instance_model.Instance) (*types.ProfilePictureInfo, error)+ GetContacts(instance *instance_model.Instance) ([]ContactInfo, error)+ GetPrivacy(instance *instance_model.Instance) (types.PrivacySettings, error)+ SetPrivacy(data *PrivacyStruct, instance *instance_model.Instance) (*types.PrivacySettings, error)+ BlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error)+ UnlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error)+ GetBlockList(instance *instance_model.Instance) (*types.Blocklist, error)+ SetProfilePicture(data *SetProfilePictureStruct, instance *instance_model.Instance) (bool, error)+ SetProfileName(data *SetProfileNameStruct, instance *instance_model.Instance) (bool, error)+ SetProfileStatus(data *SetProfileStatusStruct, instance *instance_model.Instance) (bool, error)+}++type userService struct {+ clientPointer map[string]*whatsmeow.Client+ whatsmeowService whatsmeow_service.WhatsmeowService+ loggerWrapper *logger_wrapper.LoggerManager+}++type ContactInfo struct {+ Jid string `json:"Jid"`+ Found bool `json:"Found"`+ FirstName string `json:"FirstName"`+ FullName string `json:"FullName"`+ PushName string `json:"PushName"`+ BusinessName string `json:"BusinessName"`+}++type UserInfo struct {+ VerifiedName *types.VerifiedName+ Status string+ PictureID string+ Devices []types.JID+ LID *string // The local ID (if available)+}++type UserCollection struct {+ Users map[types.JID]UserInfo+}++type User struct {+ Query string+ IsInWhatsapp bool+ JID string+ RemoteJID string+ LID *string+ VerifiedName string+}++type CheckUserCollection struct {+ Users []User+}++type CheckUserStruct struct {+ Number []string `json:"number"`+ FormatJid *bool `json:"formatJid,omitempty"`+}++type GetAvatarStruct struct {+ Number string `json:"number"`+ Preview bool `json:"preview"`+}++type BlockStruct struct {+ Number string `json:"number"`+}++type SetProfilePictureStruct struct {+ Image string `json:"image"`+}++type SetProfileNameStruct struct {+ Name string `json:"name"`+}++type SetProfileStatusStruct struct {+ Status string `json:"status"`+}++type PrivacyStruct struct {+ GroupAdd types.PrivacySetting `json:"groupAdd"`+ LastSeen types.PrivacySetting `json:"lastSeen"`+ Status types.PrivacySetting `json:"status"`+ Profile types.PrivacySetting `json:"profile"`+ ReadReceipts types.PrivacySetting `json:"readReceipts"`+ CallAdd types.PrivacySetting `json:"callAdd"`+ Online types.PrivacySetting `json:"online"`+}++func (u *userService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {+ client := u.clientPointer[instanceId]+ u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)++ if client == nil {+ u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] No client found, attempting to start new instance", instanceId)+ err := u.whatsmeowService.StartInstance(instanceId)+ if err != nil {+ u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to start instance: %v", instanceId, err)+ return nil, errors.New("no active session found")+ }++ u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance started, waiting 2 seconds...", instanceId)+ time.Sleep(2 * time.Second)++ client = u.clientPointer[instanceId]+ u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking new client - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())++ if client == nil || !client.IsConnected() {+ u.loggerWrapper.GetLogger(instanceId).LogError("[%s] New client validation failed - Exists: %v, Connected: %v",+ instanceId,+ client != nil,+ client != nil && client.IsConnected())+ return nil, errors.New("no active session found")+ }+ } else if !client.IsConnected() {+ u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Existing client is disconnected - Connected status: %v",+ instanceId,+ client.IsConnected())+ return nil, errors.New("client disconnected")+ }++ u.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client successfully validated - Connected: %v", instanceId, client.IsConnected())+ return client, nil+}++func (u *userService) GetUser(data *CheckUserStruct, instance *instance_model.Instance) (*UserCollection, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ var jids []types.JID+ for _, arg := range data.Number {+ jid, ok := utils.ParseJID(arg)+ if !ok {+ return nil, errors.New("invalid phone number")+ }+ jids = append(jids, jid)+ }+ resp, err := client.GetUserInfo(context.Background(), jids)+ if err != nil {+ return nil, err+ }++ uc := new(UserCollection)+ uc.Users = make(map[types.JID]UserInfo)++ for jid, whatsmeowInfo := range resp {+ // Consultar LID Store para obter LID associado ao JID+ var lidStr *string+ if client.Store.LIDs != nil {+ if lid, err := client.Store.LIDs.GetLIDForPN(context.TODO(), jid); err == nil && !lid.IsEmpty() {+ lidString := fmt.Sprintf("%v", lid)+ lidStr = &lidString+ }+ }++ // Converter para nossa estrutura UserInfo que inclui LID+ info := UserInfo{+ VerifiedName: whatsmeowInfo.VerifiedName,+ Status: whatsmeowInfo.Status,+ PictureID: whatsmeowInfo.PictureID,+ Devices: whatsmeowInfo.Devices,+ LID: lidStr,+ }+ uc.Users[jid] = info+ }++ return uc, nil+}++func (u *userService) CheckUser(data *CheckUserStruct, instance *instance_model.Instance) (*CheckUserCollection, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ // Set formatJid to false by default for CheckUser+ formatJid := false+ if data.FormatJid != nil {+ formatJid = *data.FormatJid+ }++ // First attempt with the requested formatJid setting+ uc, shouldRetry := u.performCheckUser(client, data.Number, formatJid, instance.Id)+ if !shouldRetry {+ return uc, nil+ }++ // If formatJid was true and we got false results, retry with formatJid=false+ if formatJid {+ u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Some users not found with formatJid=true, retrying with formatJid=false", instance.Id)+ ucRetry, _ := u.performCheckUser(client, data.Number, false, instance.Id)++ // Merge results: use retry results for users that weren't found in first attempt+ return u.mergeCheckUserResults(uc, ucRetry), nil+ }++ return uc, nil+}++// performCheckUser executes the actual user check with specified formatJid+func (u *userService) performCheckUser(client *whatsmeow.Client, numbers []string, formatJid bool, instanceId string) (*CheckUserCollection, bool) {+ // Use centralized function to prepare numbers for WhatsApp check+ phoneNumbers, err := utils.PrepareNumbersForWhatsAppCheck(numbers, &formatJid)+ if err != nil {+ u.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to prepare numbers for WhatsApp check: %v", instanceId, err)+ return nil, false+ }++ resp, err := client.IsOnWhatsApp(context.Background(), phoneNumbers)+ if err != nil {+ u.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to check users on WhatsApp: %v", instanceId, err)+ return nil, false+ }++ uc := new(CheckUserCollection)+ shouldRetry := false++ for _, item := range resp {+ // Consultar LID Store para obter LID associado ao JID+ var lidStr *string+ if client.Store.LIDs != nil {+ if lid, err := client.Store.LIDs.GetLIDForPN(context.TODO(), item.JID); err == nil && !lid.IsEmpty() {+ lidString := fmt.Sprintf("%v", lid)+ lidStr = &lidString+ }+ }++ // Determine the RemoteJID to use for messaging+ remoteJID := item.Query // Default to original query+ if item.IsIn {+ // When user exists on WhatsApp, use the JID returned by WhatsApp+ remoteJID = fmt.Sprintf("%v", item.JID)+ } else if formatJid {+ // If user not found and we used formatJid=true, we should retry with formatJid=false+ shouldRetry = true+ }++ if item.VerifiedName != nil {+ var msg = User{+ Query: item.Query,+ IsInWhatsapp: item.IsIn,+ JID: fmt.Sprintf("%v", item.JID),+ RemoteJID: remoteJID,+ LID: lidStr,+ VerifiedName: item.VerifiedName.Details.GetVerifiedName(),+ }+ uc.Users = append(uc.Users, msg)+ } else {+ var msg = User{+ Query: item.Query,+ IsInWhatsapp: item.IsIn,+ JID: fmt.Sprintf("%v", item.JID),+ RemoteJID: remoteJID,+ LID: lidStr,+ VerifiedName: "",+ }+ uc.Users = append(uc.Users, msg)+ }+ }++ return uc, shouldRetry+}++// mergeCheckUserResults merges results from two CheckUser attempts+// Priority: if a user is found in retry (formatJid=false), use that result+func (u *userService) mergeCheckUserResults(original, retry *CheckUserCollection) *CheckUserCollection {+ if retry == nil {+ return original+ }++ // Create a map of retry results by original query for quick lookup+ retryMap := make(map[string]User)+ for _, user := range retry.Users {+ retryMap[user.Query] = user+ }++ // Merge results+ merged := &CheckUserCollection{}+ for _, originalUser := range original.Users {+ if retryUser, exists := retryMap[originalUser.Query]; exists && retryUser.IsInWhatsapp && !originalUser.IsInWhatsapp {+ // Use retry result if it found the user and original didn't+ merged.Users = append(merged.Users, retryUser)+ } else {+ // Use original result+ merged.Users = append(merged.Users, originalUser)+ }+ }++ return merged+}++func (u *userService) GetAvatar(data *GetAvatarStruct, instance *instance_model.Instance) (*types.ProfilePictureInfo, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ // 🔒 FIX: Verificar se o cliente está conectado antes de fazer a requisição+ if !client.IsConnected() {+ return nil, errors.New("client is not connected to WhatsApp")+ }++ // 🔒 FIX: Verificar se o cliente está autenticado+ if !client.IsLoggedIn() {+ return nil, errors.New("client is not logged in to WhatsApp")+ }++ jid, ok := utils.ParseJID(data.Number)+ if !ok {+ return nil, errors.New("invalid phone number")+ }++ u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Requesting avatar for JID: %s, Preview: %v", instance.Id, jid, data.Preview)++ var pic *types.ProfilePictureInfo++ // 🔒 FIX: Adicionar timeout ao contexto para evitar que a requisição trave indefinidamente+ // Usar timeout maior que o padrão do sendIQ (75s) para dar tempo suficiente+ ctx, cancel := context.WithTimeout(context.Background(), 80*time.Second)+ defer cancel()++ u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Starting GetProfilePictureInfo request...", instance.Id)+ pic, err = client.GetProfilePictureInfo(ctx, jid, &whatsmeow.GetProfilePictureParams{+ Preview: data.Preview,+ })+ if err != nil {+ u.loggerWrapper.GetLogger(instance.Id).LogError("[%s] GetProfilePictureInfo failed: %v", instance.Id, err)+ return nil, err+ }++ if pic == nil {+ return nil, errors.New("no profile picture found")+ }++ u.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Got avatar %s", instance.Id, pic.URL)++ return pic, nil+}++func (u *userService) GetContacts(instance *instance_model.Instance) ([]ContactInfo, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ contacts, err := client.Store.Contacts.GetAllContacts(context.Background())+ if err != nil {+ return nil, err+ }++ var contactsArray []ContactInfo++ for jid, contact := range contacts {+ contactsArray = append(contactsArray, ContactInfo{+ Jid: jid.String(),+ Found: contact.Found,+ FirstName: contact.FirstName,+ FullName: contact.FullName,+ PushName: contact.PushName,+ BusinessName: contact.BusinessName,+ })+ }++ return contactsArray, nil++}++func (u *userService) GetPrivacy(instance *instance_model.Instance) (types.PrivacySettings, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return types.PrivacySettings{}, err+ }++ privacy := client.GetPrivacySettings(context.Background())++ return privacy, nil+}++func (u *userService) SetPrivacy(data *PrivacyStruct, instance *instance_model.Instance) (*types.PrivacySettings, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ privacySettings := []struct {+ name types.PrivacySettingType+ value types.PrivacySetting+ }{+ {types.PrivacySettingTypeGroupAdd, data.GroupAdd},+ {types.PrivacySettingTypeLastSeen, data.LastSeen},+ {types.PrivacySettingTypeStatus, data.Status},+ {types.PrivacySettingTypeProfile, data.Profile},+ {types.PrivacySettingTypeReadReceipts, data.ReadReceipts},+ {types.PrivacySettingTypeCallAdd, data.CallAdd},+ {types.PrivacySettingTypeOnline, data.Online},+ }++ for _, setting := range privacySettings {+ _, err := client.SetPrivacySetting(context.Background(), setting.name, setting.value)+ if err != nil {+ return nil, err+ }+ }++ privacy := client.GetPrivacySettings(context.Background())++ return &privacy, nil+}++func (u *userService) BlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ jid, ok := utils.ParseJID(data.Number)+ if !ok {+ return nil, errors.New("invalid phone number")+ }++ resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock)+ if err != nil {+ return nil, err+ }++ return resp, nil+}++func (u *userService) UnlockContact(data *BlockStruct, instance *instance_model.Instance) (*types.Blocklist, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ jid, ok := utils.ParseJID(data.Number)+ if !ok {+ return nil, errors.New("invalid phone number")+ }++ resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock)+ if err != nil {+ return nil, err+ }++ return resp, nil+}++func (u *userService) GetBlockList(instance *instance_model.Instance) (*types.Blocklist, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return nil, err+ }++ resp, err := client.GetBlocklist(context.Background())+ if err != nil {+ return nil, err+ }++ return resp, nil+}++func (u *userService) SetProfilePicture(data *SetProfilePictureStruct, instance *instance_model.Instance) (bool, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return false, err+ }++ var filedata []byte++ resp, err := http.Get(data.Image)+ if err != nil {+ return false, fmt.Errorf("failed to fetch image from URL: %v", err)+ }+ defer resp.Body.Close()++ filedata, err = io.ReadAll(resp.Body)+ if err != nil {+ return false, fmt.Errorf("failed to read image data: %v", err)+ }++ _, err = client.SetGroupPhoto(context.Background(), types.EmptyJID, filedata)+ if err != nil {+ return false, err+ }++ return true, nil+}++func (u *userService) SetProfileName(data *SetProfileNameStruct, instance *instance_model.Instance) (bool, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return false, err+ }++ err = client.SetGroupName(context.Background(), types.EmptyJID, data.Name)+ if err != nil {+ return false, err+ }++ return true, nil+}++func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *instance_model.Instance) (bool, error) {+ client, err := u.ensureClientConnected(instance.Id)+ if err != nil {+ return false, err+ }++ err = client.SetStatusMessage(context.Background(), data.Status)+ if err != nil {+ return false, err+ }++ return true, nil+}++func NewUserService(+ clientPointer map[string]*whatsmeow.Client,+ whatsmeowService whatsmeow_service.WhatsmeowService,+ loggerWrapper *logger_wrapper.LoggerManager,+) UserService {+ return &userService{+ clientPointer: clientPointer,+ whatsmeowService: whatsmeowService,+ loggerWrapper: loggerWrapper,+ }+}diff --git a/pkg/utils/utils.go b/pkg/utils/utils.gonew file mode 100644index 0000000..cf1697f--- /dev/null+++ b/pkg/utils/utils.go@@ -0,0 +1,575 @@+package utils++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "runtime"+ "strconv"+ "strings"+ "time"++ "github.com/gomessguii/logger"+ "go.mau.fi/whatsmeow/proto/waCompanionReg"+ "go.mau.fi/whatsmeow/proto/waE2E"+ whatsmeow_types "go.mau.fi/whatsmeow/types"+ "golang.org/x/exp/rand"+ "golang.org/x/net/proxy"+)++type Values struct {+ m map[string]string+}++type VCardStruct struct {+ FullName string `json:"fullName"`+ Organization string `json:"organization"`+ Phone string `json:"phone"`+}++func GenerateRandomString(length int) string {+ characters := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+ b := make([]byte, length)+ for i := range b {+ b[i] = characters[rand.Intn(len(characters))]+ }+ return string(b)+}++func Find(slice []string, val string) bool {+ for _, item := range slice {+ if item == val {+ return true+ }+ }+ return false+}++// CreateJID creates a properly formatted WhatsApp JID from a number string+// This function matches the TypeScript createJid functionality with enhanced validation+func CreateJID(number string) (string, error) {+ if number == "" {+ return "", fmt.Errorf("number cannot be empty")+ }++ // Remove timestamp suffix if present+ // number = strings.Split(number, ":")[0]++ // Check if already a valid JID format+ if strings.Contains(number, "@g.us") ||+ strings.Contains(number, "@s.whatsapp.net") ||+ strings.Contains(number, "@lid") ||+ strings.Contains(number, "@broadcast") ||+ strings.Contains(number, "@newsletter") {+ return number, nil+ }++ // Clean the number+ number = strings.ReplaceAll(number, " ", "")+ number = strings.ReplaceAll(number, "+", "")+ number = strings.ReplaceAll(number, "(", "")+ number = strings.ReplaceAll(number, ")", "")+ number = strings.Split(number, ":")[0]++ // Check if it's a group by hyphen and length+ if strings.Contains(number, "-") && len(number) >= 24 {+ // Remove non-digit and non-hyphen characters+ groupID := strings.Map(func(r rune) rune {+ if (r >= '0' && r <= '9') || r == '-' {+ return r+ }+ return -1+ }, number)+ return groupID + "@g.us", nil+ }++ // Check if it's a group by length (18+ digits)+ if len(number) >= 18 {+ // Remove non-digit and non-hyphen characters+ groupID := strings.Map(func(r rune) rune {+ if (r >= '0' && r <= '9') || r == '-' {+ return r+ }+ return -1+ }, number)+ return groupID + "@g.us", nil+ }++ // Remove all non-numeric characters for phone numbers+ number = strings.Map(func(r rune) rune {+ if r >= '0' && r <= '9' {+ return r+ }+ return -1+ }, number)++ if number == "" {+ return "", fmt.Errorf("invalid number format")+ }++ // Format MX (52) or AR (54) numbers+ number = formatMXOrARNumber(number)++ // Format BR (55) numbers+ number = formatBRNumber(number)++ // Add + prefix for international format+ if !strings.HasPrefix(number, "+") {+ number = "+" + number+ }++ return number + "@s.whatsapp.net", nil+}++// formatMXOrARNumber formats Mexican (52) or Argentine (54) numbers+func formatMXOrARNumber(jid string) string {+ if len(jid) < 2 {+ return jid+ }++ countryCode := jid[:2]++ // Check if it's MX (52) or AR (54)+ if countryCode == "52" && len(jid) == 13 {+ // Mexico: remove 2 digits (positions 2-3)+ // 5215551234567 -> 52 + 551234567 = 52551234567+ return countryCode + jid[4:]+ } else if countryCode == "54" && len(jid) == 13 {+ // Argentina: remove 1 digit (position 2)+ // 5411123456789 -> 54 + 11123456789 = 5411123456789+ return countryCode + jid[3:]+ }++ return jid+}++// formatBRNumber formats Brazilian (55) numbers according to the mobile number rules+func formatBRNumber(jid string) string {+ // Only process if it's exactly 13 digits and starts with "55"+ if len(jid) != 13 || !strings.HasPrefix(jid, "55") {+ return jid+ }++ // Extract DDD (area code) - should be between 11-99 for Brazil+ ddd := jid[2:4]++ // Convert DDD to integer for validation+ dddNum, err := strconv.Atoi(ddd)+ if err != nil {+ return jid+ }++ // Brazilian DDD codes are between 11-99, if it's outside this range, it's not Brazil+ if dddNum < 11 || dddNum > 99 {+ return jid+ }++ // Extract the first digit after DDD+ if len(jid) < 6 {+ return jid+ }++ firstDigit := jid[4:5]+ firstDigitNum, err := strconv.Atoi(firstDigit)+ if err != nil {+ return jid+ }++ // Check if it's a mobile number (9 prefix) and DDD >= 31+ if firstDigitNum >= 7 && dddNum >= 31 {+ // Remove the 9 prefix for mobile numbers with DDD >= 31+ return jid[:4] + jid[5:]+ }++ // Keep the number as is (landline or special case)+ return jid+}++// ParseJID parses a number string into a WhatsApp JID with validation+func ParseJID(arg string) (whatsmeow_types.JID, bool) {+ if arg == "" {+ return whatsmeow_types.NewJID("", whatsmeow_types.DefaultUserServer), false+ }++ // Use CreateJID for consistent formatting+ jidString, err := CreateJID(arg)+ if err != nil {+ logger.LogWarn("Failed to create JID: %s", err.Error())+ return whatsmeow_types.NewJID("", whatsmeow_types.DefaultUserServer), false+ }++ // Parse the formatted JID+ recipient, err := whatsmeow_types.ParseJID(jidString)+ if err != nil {+ logger.LogWarn("Invalid JID: %s", err.Error())+ return recipient, false+ }++ if recipient.User == "" && !strings.Contains(jidString, "@broadcast") {+ logger.LogError("Invalid JID. No user specified: %s", jidString)+ return recipient, false+ }++ return recipient, true+}++func CreateHTTPProxy(httpHost, httpPort, user, password string) (func(*http.Request) (*url.URL, error), error) {+ address := fmt.Sprintf("http://%s:%s@%s:%s", user, password, httpHost, httpPort)++ parsed, err := url.Parse(address)+ if err != nil {+ return nil, err+ }++ return http.ProxyURL(parsed), nil+}++func CreateSocks5Proxy(socks5Host, socks5Port, user, password string) (proxy.Dialer, error) {+ auth := &proxy.Auth{+ User: user,+ Password: password,+ }++ dialer, err := proxy.SOCKS5("tcp", fmt.Sprintf("%s:%s", socks5Host, socks5Port), auth, proxy.Direct)+ if err != nil {+ return nil, err+ }++ return dialer, nil++ // return func(req *http.Request) (*url.URL, error) {+ // host := req.URL.Host+ // if !strings.Contains(host, ":") {+ // host = fmt.Sprintf("%s:443", host) // Adiciona porta padrão 443 se não especificada+ // }+ // conn, err := dialer.Dial("tcp", host)+ // if err != nil {+ // return nil, err+ // }+ // defer conn.Close()++ // return nil, nil+ // }, nil+}++func UpdateUserInfo(values interface{}, field string, value string) interface{} {+ v, ok := values.(Values)+ if !ok {+ logger.LogError("Failed to cast values to Values type")+ return values+ }++ logger.LogDebug("User info updated field: %s value: %s", field, value)+ v.m[field] = value+ return v+}++func TimestampToUnixInt(timestamp string) (int64, error) {+ layout := "2006-01-02 15:04:05"++ t, err := time.Parse(layout, timestamp)+ if err != nil {+ return 0, err+ }++ unixTimestamp := t.Unix()++ return unixTimestamp, nil+}++func GenerateVC(data VCardStruct) string {+ result := `+BEGIN:VCARD+VERSION:3.0+FN:` + data.FullName + `+ORG:` + data.Organization + `;+TEL;type=CELL;type=VOICE;waid=` + data.Phone + `:` + data.Phone + `+END:VCARD`++ return result+}++func GetObject(message []byte, keyFind string) string {+ var messageMap map[string]interface{}+ err := json.Unmarshal(message, &messageMap)+ if err != nil {+ logger.LogError("failed to unmarshal message: %s", err)+ return ""+ }+ for key, value := range messageMap {+ if key == keyFind {+ if captionStr, ok := value.(string); ok {+ return captionStr+ }+ }++ if nestedMap, ok := value.(map[string]interface{}); ok {+ nestedMapBytes, err := json.Marshal(nestedMap)+ if err != nil {+ logger.LogError("failed to marshal nestedMap: %s", err)+ continue+ }+ if caption := GetObject(nestedMapBytes, keyFind); caption != "" {+ return caption+ }+ }+ }+ return ""+}++func WhatsAppGetUserOS() string {+ switch runtime.GOOS {+ case "windows":+ return "Windows"+ case "darwin":+ return "macOS"+ default:+ return "Linux"+ }+}++func WhatsAppGetUserAgent(agentType string) waCompanionReg.DeviceProps_PlatformType {+ switch strings.ToLower(agentType) {+ case "desktop":+ return waCompanionReg.DeviceProps_DESKTOP+ case "mac":+ return waCompanionReg.DeviceProps_CATALINA+ case "android":+ return waCompanionReg.DeviceProps_ANDROID_AMBIGUOUS+ case "android-phone":+ return waCompanionReg.DeviceProps_ANDROID_PHONE+ case "andorid-tablet":+ return waCompanionReg.DeviceProps_ANDROID_TABLET+ case "ios-phone":+ return waCompanionReg.DeviceProps_IOS_PHONE+ case "ios-catalyst":+ return waCompanionReg.DeviceProps_IOS_CATALYST+ case "ipad":+ return waCompanionReg.DeviceProps_IPAD+ case "wearos":+ return waCompanionReg.DeviceProps_WEAR_OS+ case "ie":+ return waCompanionReg.DeviceProps_IE+ case "edge":+ return waCompanionReg.DeviceProps_EDGE+ case "chrome":+ return waCompanionReg.DeviceProps_CHROME+ case "safari":+ return waCompanionReg.DeviceProps_SAFARI+ case "firefox":+ return waCompanionReg.DeviceProps_FIREFOX+ case "opera":+ return waCompanionReg.DeviceProps_OPERA+ case "uwp":+ return waCompanionReg.DeviceProps_UWP+ case "aloha":+ return waCompanionReg.DeviceProps_ALOHA+ case "tv-tcl":+ return waCompanionReg.DeviceProps_TCL_TV+ default:+ return waCompanionReg.DeviceProps_UNKNOWN+ }+}++func GetMessageType(waMsg *waE2E.Message) string {+ switch {+ case waMsg == nil:+ return "ignore"+ case waMsg.Conversation != nil, waMsg.ExtendedTextMessage != nil:+ return "text"+ case waMsg.ImageMessage != nil:+ return fmt.Sprintf("image %s", waMsg.GetImageMessage().GetMimetype())+ case waMsg.StickerMessage != nil:+ return fmt.Sprintf("sticker %s", waMsg.GetStickerMessage().GetMimetype())+ case waMsg.VideoMessage != nil:+ return fmt.Sprintf("video %s", waMsg.GetVideoMessage().GetMimetype())+ case waMsg.PtvMessage != nil:+ return fmt.Sprintf("round video %s", waMsg.GetPtvMessage().GetMimetype())+ case waMsg.AudioMessage != nil:+ return fmt.Sprintf("audio %s", waMsg.GetAudioMessage().GetMimetype())+ case waMsg.DocumentMessage != nil:+ return fmt.Sprintf("document %s", waMsg.GetDocumentMessage().GetMimetype())+ case waMsg.ContactMessage != nil:+ return "contact"+ case waMsg.ContactsArrayMessage != nil:+ return "contact array"+ case waMsg.LocationMessage != nil:+ return "location"+ case waMsg.LiveLocationMessage != nil:+ return "live location start"+ case waMsg.GroupInviteMessage != nil:+ return "group invite"+ case waMsg.GroupMentionedMessage != nil:+ return "group mention"+ case waMsg.ScheduledCallCreationMessage != nil:+ return "scheduled call create"+ case waMsg.ScheduledCallEditMessage != nil:+ return "scheduled call edit"+ case waMsg.ReactionMessage != nil:+ if waMsg.ReactionMessage.GetText() == "" {+ return "reaction remove"+ }+ return "reaction"+ case waMsg.EncReactionMessage != nil:+ return "encrypted reaction"+ case waMsg.PollCreationMessage != nil || waMsg.PollCreationMessageV2 != nil || waMsg.PollCreationMessageV3 != nil:+ return "poll create"+ case waMsg.PollUpdateMessage != nil:+ return "poll update"+ case waMsg.ProtocolMessage != nil:+ switch waMsg.GetProtocolMessage().GetType() {+ case waE2E.ProtocolMessage_REVOKE:+ if waMsg.GetProtocolMessage().GetKey() == nil {+ return "ignore"+ }+ return "revoke"+ case waE2E.ProtocolMessage_MESSAGE_EDIT:+ return "edit"+ case waE2E.ProtocolMessage_EPHEMERAL_SETTING:+ return "disappearing timer change"+ case waE2E.ProtocolMessage_APP_STATE_SYNC_KEY_SHARE,+ waE2E.ProtocolMessage_HISTORY_SYNC_NOTIFICATION,+ waE2E.ProtocolMessage_INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC:+ return "ignore"+ default:+ return fmt.Sprintf("unknown_protocol_%d", waMsg.GetProtocolMessage().GetType())+ }+ case waMsg.ButtonsMessage != nil:+ return "buttons"+ case waMsg.ButtonsResponseMessage != nil:+ return "buttons response"+ case waMsg.TemplateMessage != nil:+ return "template"+ case waMsg.HighlyStructuredMessage != nil:+ return "highly structured template"+ case waMsg.TemplateButtonReplyMessage != nil:+ return "template button reply"+ case waMsg.InteractiveMessage != nil:+ return "interactive"+ case waMsg.ListMessage != nil:+ return "list"+ case waMsg.ProductMessage != nil:+ return "product"+ case waMsg.ListResponseMessage != nil:+ return "list response"+ case waMsg.OrderMessage != nil:+ return "order"+ case waMsg.InvoiceMessage != nil:+ return "invoice"+ case waMsg.BotInvokeMessage != nil:+ return "bot invoke"+ case waMsg.EventMessage != nil:+ return "event"+ case waMsg.EventCoverImage != nil:+ return "event cover image"+ case waMsg.EncEventResponseMessage != nil:+ return "ignore" // these are ignored for now as they're not meant to be shown as new messages+ //return "encrypted event response"+ case waMsg.CommentMessage != nil:+ return "comment"+ case waMsg.EncCommentMessage != nil:+ return "encrypted comment"+ case waMsg.NewsletterAdminInviteMessage != nil:+ return "newsletter admin invite"+ case waMsg.SecretEncryptedMessage != nil:+ return "secret encrypted"+ case waMsg.PollResultSnapshotMessage != nil:+ return "poll result snapshot"+ case waMsg.MessageHistoryBundle != nil:+ return "message history bundle"+ case waMsg.RequestPhoneNumberMessage != nil:+ return "request phone number"+ case waMsg.KeepInChatMessage != nil:+ return "keep in chat"+ case waMsg.StatusMentionMessage != nil:+ return "status mention"+ case waMsg.StickerPackMessage != nil:+ return "sticker pack"+ case waMsg.AlbumMessage != nil:+ return "album" // or maybe these should be ignored?+ case waMsg.SendPaymentMessage != nil, waMsg.RequestPaymentMessage != nil,+ waMsg.DeclinePaymentRequestMessage != nil, waMsg.CancelPaymentRequestMessage != nil,+ waMsg.PaymentInviteMessage != nil:+ return "payment"+ case waMsg.Call != nil:+ return "call"+ case waMsg.Chat != nil:+ return "chat"+ case waMsg.PlaceholderMessage != nil:+ return "placeholder"+ case waMsg.SenderKeyDistributionMessage != nil, waMsg.StickerSyncRmrMessage != nil:+ return "ignore"+ default:+ return "unknown"+ }+}++func GetStringValue(s *string) string {+ if s == nil {+ return ""+ }+ return *s+}++// PrepareNumbersForWhatsAppCheck prepares phone numbers for IsOnWhatsApp call+// based on formatJid flag. This centralizes the logic used by both CheckUser and SendText.+func PrepareNumbersForWhatsAppCheck(numbers []string, formatJid *bool) ([]string, error) {+ // Default formatJid to true if not specified+ shouldFormat := true+ if formatJid != nil {+ shouldFormat = *formatJid+ }++ var phoneNumbers []string++ if shouldFormat {+ // Normalize numbers using CreateJID for consistent formatting+ for _, number := range numbers {+ // First, extract the raw number if it's already a JID+ rawNumber := number+ if strings.Contains(number, "@s.whatsapp.net") {+ rawNumber = strings.Split(number, "@")[0]+ }++ // Use CreateJID to normalize the raw number format+ normalizedJID, err := CreateJID(rawNumber)+ if err != nil {+ // Continue with original number if normalization fails+ phoneNumbers = append(phoneNumbers, number)+ continue+ }++ // Extract the phone number part from the JID for IsOnWhatsApp call+ // e.g., "[email protected]" -> "+5511999999999" (keep + for IsOnWhatsApp)+ if strings.Contains(normalizedJID, "@s.whatsapp.net") {+ phoneNumber := strings.Split(normalizedJID, "@")[0]+ phoneNumbers = append(phoneNumbers, phoneNumber)+ } else if strings.Contains(normalizedJID, "@g.us") || strings.Contains(normalizedJID, "@broadcast") || strings.Contains(normalizedJID, "@lid") {+ // For groups, broadcasts, and LIDs, use the full JID+ phoneNumbers = append(phoneNumbers, normalizedJID)+ } else {+ phoneNumbers = append(phoneNumbers, normalizedJID)+ }+ }+ } else {+ // Use numbers exactly as received (raw format)+ phoneNumbers = append(phoneNumbers, numbers...)+ }++ return phoneNumbers, nil+}++// PrepareNumberForWhatsAppCheck prepares a single phone number for IsOnWhatsApp call+// This is used by SendText which works with single numbers+func PrepareNumberForWhatsAppCheck(phone string, formatJid bool) (string, error) {+ formatJidPtr := &formatJid+ numbers, err := PrepareNumbersForWhatsAppCheck([]string{phone}, formatJidPtr)+ if err != nil {+ return "", err+ }+ if len(numbers) == 0 {+ return "", fmt.Errorf("no valid number processed")+ }+ return numbers[0], nil+}diff --git a/pkg/utils/utils_test.go b/pkg/utils/utils_test.gonew file mode 100644index 0000000..25a9979--- /dev/null+++ b/pkg/utils/utils_test.go@@ -0,0 +1,327 @@+package utils++import (+ "testing"+)++func TestCreateJID(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected string+ hasError bool+ }{+ // Basic phone numbers+ {+ name: "Simple US number",+ input: "15551234567",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Number with spaces and parentheses",+ input: "+1 (555) 123-4567",+ expected: "[email protected]",+ hasError: false,+ },++ // Brazilian numbers (55)+ {+ name: "BR mobile number with 9 prefix - should remove 9",+ input: "5531987654321",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "BR landline number - should keep as is",+ input: "5531123456789",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "BR number with DDD < 31 - should keep as is",+ input: "5521987654321",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "BR number with first digit < 7 - should keep as is",+ input: "5531687654321",+ expected: "[email protected]",+ hasError: false,+ },++ // Portuguese numbers (351) - should not be treated as Brazilian+ {+ name: "Portugal number - should not apply BR formatting",+ input: "351932933862",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Portugal number with + - should not apply BR formatting",+ input: "+351932933862",+ expected: "[email protected]",+ hasError: false,+ },++ // Mexican numbers (52)+ {+ name: "MX number with extra digit - should remove",+ input: "5215551234567",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "MX number without extra digit",+ input: "525551234567",+ expected: "[email protected]",+ hasError: false,+ },++ // Argentine numbers (54)+ {+ name: "AR number with extra digit - should remove",+ input: "5411123456789",+ expected: "[email protected]",+ hasError: false,+ },++ // Group IDs+ {+ name: "Group ID with hyphen",+ input: "[email protected]",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Group ID by length",+ input: "120363123456789012345",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Group ID with hyphen and extra chars",+ input: "120363-123456789012-345abc",+ expected: "[email protected]",+ hasError: false,+ },++ // Already formatted JIDs+ {+ name: "Already formatted user JID",+ input: "[email protected]",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Already formatted group JID",+ input: "[email protected]",+ expected: "[email protected]",+ hasError: false,+ },+ {+ name: "Broadcast JID",+ input: "status@broadcast",+ expected: "status@broadcast",+ hasError: false,+ },+ {+ name: "LID JID",+ input: "12345@lid",+ expected: "12345@lid",+ hasError: false,+ },++ // Error cases+ {+ name: "Empty string",+ input: "",+ expected: "",+ hasError: true,+ },+ {+ name: "Only special characters",+ input: "+-()@#$%",+ expected: "",+ hasError: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result, err := CreateJID(tt.input)++ if tt.hasError {+ if err == nil {+ t.Errorf("Expected error for input %q, but got none", tt.input)+ }+ return+ }++ if err != nil {+ t.Errorf("Unexpected error for input %q: %v", tt.input, err)+ return+ }++ if result != tt.expected {+ t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)+ }+ })+ }+}++func TestFormatMXOrARNumber(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected string+ }{+ {+ name: "MX number with 13 digits",+ input: "5215551234567",+ expected: "52551234567",+ },+ {+ name: "MX number with 12 digits",+ input: "525551234567",+ expected: "525551234567",+ },+ {+ name: "AR number with 13 digits",+ input: "5411123456789",+ expected: "541123456789",+ },+ {+ name: "Non-MX/AR number",+ input: "5511987654321",+ expected: "5511987654321",+ },+ {+ name: "Short number",+ input: "52",+ expected: "52",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := formatMXOrARNumber(tt.input)+ if result != tt.expected {+ t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)+ }+ })+ }+}++func TestFormatBRNumber(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected string+ }{+ {+ name: "BR mobile number with DDD >= 31 and 9 prefix",+ input: "5531987654321",+ expected: "553187654321",+ },+ {+ name: "BR number with DDD < 31",+ input: "5521987654321",+ expected: "5521987654321",+ },+ {+ name: "BR number with first digit < 7",+ input: "5531687654321",+ expected: "5531687654321",+ },+ {+ name: "Non-BR number",+ input: "15551234567",+ expected: "15551234567",+ },+ {+ name: "BR number with wrong length",+ input: "551198765432",+ expected: "551198765432",+ },+ {+ name: "BR landline number",+ input: "5531123456789",+ expected: "5531123456789",+ },+ {+ name: "Portugal number starting with 55 - should not be treated as BR",+ input: "351932933862",+ expected: "351932933862",+ },+ {+ name: "Number starting with 55 but invalid DDD - should not be treated as BR",+ input: "5509987654321",+ expected: "5509987654321",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := formatBRNumber(tt.input)+ if result != tt.expected {+ t.Errorf("For input %q, expected %q, but got %q", tt.input, tt.expected, result)+ }+ })+ }+}++func TestParseJID(t *testing.T) {+ tests := []struct {+ name string+ input string+ expectOk bool+ expectJID string+ }{+ {+ name: "Valid phone number",+ input: "15551234567",+ expectOk: true,+ expectJID: "[email protected]",+ },+ {+ name: "Valid BR number",+ input: "5531987654321",+ expectOk: true,+ expectJID: "[email protected]",+ },+ {+ name: "Valid group ID",+ input: "[email protected]",+ expectOk: true,+ expectJID: "[email protected]",+ },+ {+ name: "Empty string",+ input: "",+ expectOk: false,+ expectJID: "@s.whatsapp.net",+ },+ {+ name: "Invalid format",+ input: "+-()@#$%",+ expectOk: false,+ expectJID: "@s.whatsapp.net",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ jid, ok := ParseJID(tt.input)++ if ok != tt.expectOk {+ t.Errorf("For input %q, expected ok=%v, but got ok=%v", tt.input, tt.expectOk, ok)+ }++ if tt.expectOk && jid.String() != tt.expectJID {+ t.Errorf("For input %q, expected JID %q, but got %q", tt.input, tt.expectJID, jid.String())+ }+ })+ }+}diff --git a/pkg/whatsmeow/service/whatsmeow.go b/pkg/whatsmeow/service/whatsmeow.gonew file mode 100644index 0000000..6af7174--- /dev/null+++ b/pkg/whatsmeow/service/whatsmeow.go@@ -0,0 +1,2526 @@+package whatsmeow_service++import (+ "bytes"+ "context"+ "database/sql"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "image/png"+ "io"+ "math/rand"+ "net/http"+ "regexp"+ "strconv"+ "strings"+ "time"++ "golang.org/x/image/webp"+ "google.golang.org/protobuf/proto"++ _ "github.com/lib/pq"+ "github.com/patrickmn/go-cache"+ "github.com/skip2/go-qrcode"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/appstate"+ "go.mau.fi/whatsmeow/proto/waCompanionReg"+ "go.mau.fi/whatsmeow/proto/waE2E"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/store/sqlstore"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ waLog "go.mau.fi/whatsmeow/util/log"++ "github.com/EvolutionAPI/evolution-go/pkg/config"+ producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"+ instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"+ instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"+ "github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"+ label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"+ label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"+ logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"+ message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"+ message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"+ poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"+ storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"+ "github.com/EvolutionAPI/evolution-go/pkg/utils"+)++type WhatsmeowService interface {+ StartClient(clientData *ClientData)+ ConnectOnStartup(clientName string)+ StartInstance(instanceId string) error+ ReconnectClient(instanceId string) error+ ClearInstanceCache(instanceId string, token string) error+ CallWebhook(instance *instance_model.Instance, queueName string, jsonData []byte)+ SendToGlobalQueues(event string, jsonData []byte, userId string)+ ForceUpdateJid(instanceId string, number string) error+ UpdateInstanceSettings(instanceId string) error+ UpdateInstanceAdvancedSettings(instanceId string) error+ GetPollService() poll_service.PollService // NOVO: Acesso ao serviço de polls+}++type clientVersion struct {+ Major int+ Minor int+ Patch int+}++type whatsmeowService struct {+ instanceRepository instance_repository.InstanceRepository+ authDB *sql.DB+ messageRepository message_repository.MessageRepository+ labelRepository label_repository.LabelRepository+ pollService poll_service.PollService // NOVO: Serviço de enquetes+ config *config.Config+ killChannel map[string](chan bool)+ userInfoCache *cache.Cache+ clientPointer map[string]*whatsmeow.Client+ myClientPointer map[string]*MyClient+ rabbitmqProducer producer_interfaces.Producer+ webhookProducer producer_interfaces.Producer+ websocketProducer producer_interfaces.Producer+ sqliteDB *sql.DB+ exPath string+ mediaStorage storage_interfaces.MediaStorage+ processedMessages *cache.Cache+ natsProducer producer_interfaces.Producer+ loggerWrapper *logger_wrapper.LoggerManager+}++type MyClient struct {+ service WhatsmeowService+ WAClient *whatsmeow.Client+ eventHandlerID uint32+ userID string+ Instance *instance_model.Instance+ token string+ subscriptions []string+ webhookUrl string+ rabbitmqEnable string+ natsEnable string+ websocketEnable string+ instanceRepository instance_repository.InstanceRepository+ messageRepository message_repository.MessageRepository+ labelRepository label_repository.LabelRepository+ pollService poll_service.PollService // NOVO: Serviço de enquetes+ clientPointer map[string]*whatsmeow.Client+ killChannel map[string](chan bool)+ userInfoCache *cache.Cache+ config *config.Config+ historySyncID int32+ rabbitmqProducer producer_interfaces.Producer+ webhookProducer producer_interfaces.Producer+ websocketProducer producer_interfaces.Producer+ mediaStorage storage_interfaces.MediaStorage+ processedMessages *cache.Cache+ natsProducer producer_interfaces.Producer+ loggerWrapper *logger_wrapper.LoggerManager+ qrcodeCount int+}++type ClientData struct {+ Instance *instance_model.Instance+ Subscriptions []string+ Phone string+ IsProxy bool+}++type Values struct {+ m map[string]string+}++func (v Values) Get(key string) string {+ return v.m[key]+}++type UserCollection struct {+ Users map[types.JID]types.UserInfo+}++type ProxyConfig struct {+ Host string `json:"host"`+ Password string `json:"password"`+ Port string `json:"port"`+ Username string `json:"username"`+}++func (w whatsmeowService) ReconnectClient(instanceId string) error {+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting reconnection process - simulating restart", instanceId)++ // Passo 1: Limpar conexão existente se houver+ if client, exists := w.clientPointer[instanceId]; exists {+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Disconnecting existing client", instanceId)++ // Desconectar o cliente WebSocket+ if client.IsConnected() {+ client.Disconnect()+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] WebSocket disconnected", instanceId)+ }++ // Remover event handler se existir+ if mycli, ok := w.myClientPointer[instanceId]; ok {+ if mycli.eventHandlerID != 0 {+ client.RemoveEventHandler(mycli.eventHandlerID)+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Event handler removed", instanceId)+ }+ }+ }++ // Passo 2: Limpar todos os recursos da instância+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Cleaning up resources", instanceId)++ // Enviar sinal de kill se o canal existir+ if killChan, exists := w.killChannel[instanceId]; exists {+ select {+ case killChan <- true:+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill signal sent", instanceId)+ default:+ // Canal pode estar bloqueado, continua+ }+ }++ // Remover das estruturas+ delete(w.clientPointer, instanceId)+ delete(w.myClientPointer, instanceId)+ delete(w.killChannel, instanceId)++ // Limpar cache de userInfo para esta instância+ if instance, err := w.instanceRepository.GetInstanceByID(instanceId); err == nil {+ w.userInfoCache.Delete(instance.Token)+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] UserInfo cache cleared for token: %s", instanceId, instance.Token)+ }++ // Passo 3: Atualizar status no banco+ instance, err := w.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ return fmt.Errorf("failed to get instance: %v", err)+ }++ instance.Connected = false+ instance.DisconnectReason = "Reconnecting"+ err = w.instanceRepository.UpdateConnected(instanceId, false, "Reconnecting")+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Failed to update disconnect status: %v", instanceId, err)+ }++ // Passo 4: Aguardar um pouco para garantir limpeza completa+ time.Sleep(2 * time.Second)++ // Passo 5: Iniciar nova instância como se fosse a primeira vez+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting fresh instance", instanceId)+ return w.StartInstance(instanceId)+}++func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error {+ instance, err := w.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting instance: %v", instanceId, err)+ return err+ }++ if instance.Jid == "" && number != "" {+ sqlDeviceSearch := fmt.Sprintf("SELECT jid FROM whatsmeow_device WHERE jid LIKE '%%%s%%'", number)+ rows, err := w.authDB.Query(sqlDeviceSearch)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting device: %v", instanceId, err)+ return err+ }++ defer rows.Close()++ var latestJid string+ var latestSession int++ for rows.Next() {+ type deviceStruct struct {+ Jid string `json:"jid"`+ }+ var device deviceStruct+ err := rows.Scan(&device.Jid)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting device: %v", instanceId, err)+ return err+ }++ // Extrair o número da sessão do JID+ parts := strings.Split(device.Jid, ":")+ if len(parts) == 2 {+ sessionPart := strings.Split(parts[1], "@")[0]+ session, err := strconv.Atoi(sessionPart)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error parsing session number: %v", instanceId, err)+ return err+ }++ // Atualizar se for a sessão mais recente+ if session > latestSession {+ latestSession = session+ latestJid = device.Jid+ }+ }+ }++ // Atualizar a instância com o JID mais recente+ if latestJid != "" {+ instance.Jid = latestJid+ err = w.instanceRepository.UpdateJid(instanceId, latestJid)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error updating instance: %v", instanceId, err)+ }+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updated instance with latest JID: %s (session: %d)", instanceId, latestJid, latestSession)+ }+ }++ return nil+}++func (w whatsmeowService) StartClient(cd *ClientData) {++ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id)++ var deviceStore *store.Device+ var err error++ if w.clientPointer[cd.Instance.Id] != nil {+ if w.clientPointer[cd.Instance.Id].IsConnected() {+ return+ }+ }++ var container *sqlstore.Container++ if w.config.WaDebug != "" {+ dbLog := waLog.Stdout("Database", w.config.WaDebug, true)+ if w.config.PostgresAuthDB != "" {+ container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, dbLog)+ } else {+ dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)+ container, err = sqlstore.New(context.Background(), "sqlite", dsn, dbLog)+ }+ } else {+ if w.config.PostgresAuthDB != "" {+ container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, nil)+ } else {+ dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath)+ container, err = sqlstore.New(context.Background(), "sqlite", dsn, nil)+ }+ }++ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err)+ return+ }++ if cd.Instance.Jid != "" {+ jid, _ := utils.ParseJID(cd.Instance.Jid)+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Jid found. Getting device store for jid: %s", cd.Instance.Id, jid)+ deviceStore, err = container.GetDevice(context.Background(), jid)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Erro ao obter device store: %v", cd.Instance.Id, err)+ return+ }+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] No jid found. Creating new device", cd.Instance.Id)+ deviceStore = container.NewDevice()+ }++ if deviceStore == nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] No store found. Creating new one", cd.Instance.Id)+ deviceStore = container.NewDevice()++ cd.Instance.Connected = false+ err := w.instanceRepository.UpdateConnected(cd.Instance.Id, cd.Instance.Connected, cd.Instance.DisconnectReason)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)+ }+ }++ var version clientVersion++ platformID, ok := waCompanionReg.DeviceProps_PlatformType_value[strings.ToUpper("chrome")]+ if ok {+ store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_PlatformType(platformID).Enum()+ }+ if cd.Instance.OsName == "" {+ cd.Instance.OsName = utils.WhatsAppGetUserOS()+ }++ store.DeviceProps.Os = &cd.Instance.OsName+ store.DeviceProps.RequireFullSync = proto.Bool(true)++ if w.config.WhatsappVersionMajor != 0 && w.config.WhatsappVersionMinor != 0 && w.config.WhatsappVersionPatch != 0 {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version to %d.%d.%d", cd.Instance.Id, w.config.WhatsappVersionMajor, w.config.WhatsappVersionMinor, w.config.WhatsappVersionPatch)+ version.Major = w.config.WhatsappVersionMajor+ if err == nil {+ store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))+ }+ version.Minor = w.config.WhatsappVersionMinor+ if err == nil {+ store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))+ }+ version.Patch = w.config.WhatsappVersionPatch+ if err == nil {+ store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))+ }+ } else {+ // Try to fetch version from WhatsApp Web+ webVersion, err := fetchWhatsAppWebVersion()+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to fetch WhatsApp Web version: %v", cd.Instance.Id, err)+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Setting whatsapp version from web to %d.%d.%d", cd.Instance.Id, webVersion.Major, webVersion.Minor, webVersion.Patch)+ version = *webVersion+ store.DeviceProps.Version.Primary = proto.Uint32(uint32(version.Major))+ store.DeviceProps.Version.Secondary = proto.Uint32(uint32(version.Minor))+ store.DeviceProps.Version.Tertiary = proto.Uint32(uint32(version.Patch))+ }+ }++ // 🔒 FIX: Sempre criar logger, mesmo que WaDebug esteja vazio+ // Usar "INFO" como nível mínimo para garantir que logs importantes apareçam+ minLevel := w.config.WaDebug+ if minLevel == "" {+ minLevel = "INFO" // Nível mínimo para garantir que logs INFO apareçam+ }+ clientLog := waLog.Stdout("Client", minLevel, true)+ client := whatsmeow.NewClient(deviceStore, clientLog)++ w.clientPointer[cd.Instance.Id] = client++ if cd.IsProxy {+ var proxyConfig ProxyConfig+ err := json.Unmarshal([]byte(cd.Instance.Proxy), &proxyConfig)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] error unmarshalling proxy config", cd.Instance.Id)+ return+ }++ proxyHost := proxyConfig.Host+ proxyPort := proxyConfig.Port+ proxyUsername := proxyConfig.Username+ proxyPassword := proxyConfig.Password++ if proxyConfig.Host == "" {+ proxyHost = w.config.ProxyHost+ }++ if proxyConfig.Port == "" {+ proxyPort = w.config.ProxyPort+ }++ if proxyConfig.Username == "" {+ proxyUsername = w.config.ProxyUsername+ }++ if proxyConfig.Password == "" {+ proxyPassword = w.config.ProxyPassword+ }++ proxy, err := utils.CreateSocks5Proxy(proxyHost, proxyPort, proxyUsername, proxyPassword)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy error, continuing without proxy: %v", cd.Instance.Id, err)+ } else {+ client.SetSOCKSProxy(proxy)+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Proxy enabled", cd.Instance.Id)+ }+ }++ client.EnableAutoReconnect = false+ client.AutoTrustIdentity = true++ mycli := &MyClient{+ service: &w,+ Instance: cd.Instance,+ WAClient: client,+ eventHandlerID: 1,+ userID: cd.Instance.Id,+ token: cd.Instance.Token,+ subscriptions: cd.Subscriptions,+ webhookUrl: cd.Instance.Webhook,+ rabbitmqEnable: cd.Instance.RabbitmqEnable,+ natsEnable: cd.Instance.NatsEnable,+ websocketEnable: cd.Instance.WebSocketEnable,+ instanceRepository: w.instanceRepository,+ messageRepository: w.messageRepository,+ labelRepository: w.labelRepository,+ pollService: w.pollService, // NOVO: Serviço de enquetes+ userInfoCache: w.userInfoCache,+ clientPointer: w.clientPointer,+ killChannel: w.killChannel,+ config: w.config,+ historySyncID: 0,+ rabbitmqProducer: w.rabbitmqProducer,+ webhookProducer: w.webhookProducer,+ websocketProducer: w.websocketProducer,+ mediaStorage: w.mediaStorage,+ processedMessages: w.processedMessages,+ natsProducer: w.natsProducer,+ loggerWrapper: w.loggerWrapper,+ qrcodeCount: 0,+ }++ mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)++ // Armazena o MyClient no map para permitir atualizações posteriores+ w.myClientPointer[cd.Instance.Id] = mycli++ if client.Store.ID != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Already logged in with JID: %s", cd.Instance.Id, client.Store.ID.String())+ err = client.Connect()+ if err != nil {+ if strings.Contains(err.Error(), "EOF") {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Erro de conexão WebSocket (EOF). Tentando reconectar em 5 segundos...", cd.Instance.Id)+ time.Sleep(5 * time.Second)+ err = client.Connect()+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Falha na segunda tentativa de conexão: %v", cd.Instance.Id, err)+ return+ }+ } else if strings.Contains(err.Error(), "username/password authentication failed") {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy authentication failed, attempting to connect without proxy", cd.Instance.Id)++ // Desabilita o proxy+ client.SetProxy(nil)++ // Tenta conectar sem proxy+ err = client.Connect()+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect even without proxy: %v", cd.Instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Successfully connected without proxy", cd.Instance.Id)+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect: %v", cd.Instance.Id, err)+ return+ }+ }+ } else {+ qrChan, err := client.GetQRChannel(context.Background())+ if err != nil {+ if !errors.Is(err, whatsmeow.ErrQRStoreContainsID) {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to get QR channel: %v", cd.Instance.Id, err)+ return+ }+ } else {+ err = client.Connect()+ if err != nil {+ if strings.Contains(err.Error(), "EOF") {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Erro de conexão WebSocket (EOF). Tentando reconectar em 5 segundos...", cd.Instance.Id)+ time.Sleep(5 * time.Second)+ err = client.Connect()+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Falha na segunda tentativa de conexão: %v", cd.Instance.Id, err)+ return+ }+ } else if strings.Contains(err.Error(), "username/password authentication failed") {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy authentication failed during QR connection, attempting without proxy", cd.Instance.Id)++ // Desabilita o proxy+ client.SetProxy(nil)++ // Tenta conectar sem proxy+ err = client.Connect()+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect even without proxy: %v", cd.Instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Successfully connected without proxy", cd.Instance.Id)+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect: %v", cd.Instance.Id, err)+ return+ }+ }++ for evt := range qrChan {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Received QR code event %s", cd.Instance.Id, evt.Event)+ if evt.Event == "code" {+ // Incrementar contador de QR codes+ mycli.qrcodeCount++++ // Log com status do limite+ if w.config.QrcodeMaxCount > 0 {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR code generated #%d (max: %d)", cd.Instance.Id, mycli.qrcodeCount, w.config.QrcodeMaxCount)+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR code generated #%d (limit disabled)", cd.Instance.Id, mycli.qrcodeCount)+ }++ // Verificar se atingiu o limite máximo (0 = desabilitado)+ if w.config.QrcodeMaxCount > 0 && mycli.qrcodeCount >= w.config.QrcodeMaxCount {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Maximum QR code count reached (%d), forcing logout and QRTimeout", cd.Instance.Id, w.config.QrcodeMaxCount)++ // 1. Forçar logout da instância+ if mycli.WAClient.IsConnected() {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Forcing client logout due to QR limit", cd.Instance.Id)+ err := mycli.WAClient.Logout(context.Background())+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Error during forced logout: %v", cd.Instance.Id, err)+ }+ }++ // 2. Limpar QR code no banco+ cd.Instance.Qrcode = ""+ err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, "")+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error clearing QR code: %v", cd.Instance.Id, err)+ }++ // 3. Atualizar status da instância como desconectada+ cd.Instance.Connected = false+ cd.Instance.DisconnectReason = fmt.Sprintf("QR code limit reached (%d)", w.config.QrcodeMaxCount)+ err = w.instanceRepository.UpdateConnected(cd.Instance.Id, false, cd.Instance.DisconnectReason)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance status: %v", cd.Instance.Id, err)+ }++ // 4. Limpar recursos+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Cleaning up resources due to QR limit", cd.Instance.Id)+ delete(w.clientPointer, cd.Instance.Id)+ delete(w.myClientPointer, cd.Instance.Id)++ // 5. Enviar sinal de kill+ if killChan, exists := w.killChannel[cd.Instance.Id]; exists {+ select {+ case killChan <- true:+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Kill signal sent due to QR limit", cd.Instance.Id)+ default:+ // Canal pode estar bloqueado+ }+ delete(w.killChannel, cd.Instance.Id)+ }++ // 6. Enviar evento QRTimeout+ postMap := make(map[string]interface{})+ postMap["event"] = "QRTimeout"+ postMap["data"] = map[string]interface{}{+ "reason": fmt.Sprintf("Maximum QR code count (%d) reached", w.config.QrcodeMaxCount),+ "qrcount": mycli.qrcodeCount,+ "maxCount": w.config.QrcodeMaxCount,+ "forceLogout": true,+ }+ postMap["instanceToken"] = mycli.token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = cd.Instance.Name++ queueName := strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))+ values, err := json.Marshal(postMap)+ if err == nil {+ go w.CallWebhook(cd.Instance, queueName, values)+ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }+ }++ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QRTimeout event sent due to QR limit enforcement", cd.Instance.Id)+ return+ }++ if w.config.LogType != "json" {+ fmt.Println("QR code:\n", evt.Code)+ }++ image, _ := qrcode.Encode(evt.Code, qrcode.Medium, 256)+ base64qrcode := "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)++ base64WithCode := base64qrcode + "|" + evt.Code++ cd.Instance.Qrcode = base64WithCode++ err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, base64WithCode)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)+ }++ postMap := make(map[string]interface{})++ postMap["event"] = "QRCode"++ dataMap := make(map[string]interface{})++ dataMap["qrcode"] = base64qrcode+ dataMap["code"] = evt.Code+ dataMap["count"] = mycli.qrcodeCount+ dataMap["maxCount"] = w.config.QrcodeMaxCount++ postMap["data"] = dataMap++ postMap["instanceToken"] = mycli.token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = cd.Instance.Name++ var queueName string++ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))+ }++ values, err := json.Marshal(postMap)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to marshal JSON for queue", cd.Instance.Id)+ return+ }++ go w.CallWebhook(cd.Instance, queueName, values)++ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }+ } else if evt.Event == "timeout" {+ cd.Instance.Qrcode = ""++ err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, "")+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)+ }++ w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] QR timeout killing channel", cd.Instance.Id)+ delete(w.clientPointer, cd.Instance.Id)+ delete(w.myClientPointer, cd.Instance.Id)+ w.killChannel[cd.Instance.Id] <- true++ postMap := make(map[string]interface{})++ postMap["event"] = "QRTimeout"++ dataMap := make(map[string]interface{})++ postMap["data"] = dataMap++ postMap["instanceToken"] = mycli.token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = cd.Instance.Name++ var queueName string++ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))+ }++ values, err := json.Marshal(postMap)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to marshal JSON for queue", cd.Instance.Id)+ return+ }++ go w.CallWebhook(cd.Instance, queueName, values)++ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }+ } else if evt.Event == "success" {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR pairing ok!", cd.Instance.Id)+ } else {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Login event: %s", cd.Instance.Id, evt.Event)+ }+ }+ }+ }++ // Removed auto-reconnect logic to prevent infinite loops++ for {+ select {+ case <-w.killChannel[cd.Instance.Id]:+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Received kill signal for user '%s'", cd.Instance.Id)+ client.Disconnect()++ delete(w.clientPointer, cd.Instance.Id)+ delete(w.myClientPointer, cd.Instance.Id)++ // Limpar cache de userInfo para esta instância+ w.userInfoCache.Delete(cd.Instance.Token)+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] UserInfo cache cleared for token: %s", cd.Instance.Id, cd.Instance.Token)++ cd.Instance.Connected = false++ err := w.instanceRepository.UpdateConnected(cd.Instance.Id, cd.Instance.Connected, cd.Instance.DisconnectReason)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)+ }++ postMap := make(map[string]interface{})++ postMap["event"] = "LoggedOut"++ dataMap := make(map[string]interface{})++ dataMap["reason"] = "Logged out"++ postMap["data"] = dataMap++ postMap["instanceToken"] = mycli.token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = cd.Instance.Name++ var queueName string++ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))+ }++ values, err := json.Marshal(postMap)+ if err != nil {+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to marshal JSON for queue", cd.Instance.Id)+ return+ }++ go w.CallWebhook(cd.Instance, queueName, values)++ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }++ // restart client+ w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Restarting client", cd.Instance.Id)+ w.StartClient(cd)+ return+ default:+ time.Sleep(1000 * time.Millisecond)+ }+ }+}++func schedulePresenceUpdates(mycli *MyClient) {+ ticker := time.NewTicker(1 * time.Minute)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ // Verificar se a instância ainda existe+ _, err := mycli.instanceRepository.GetInstanceByID(mycli.userID)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Instance no longer exists, stopping presence updates", mycli.userID)+ return // Encerra a goroutine se a instância não existir mais+ }++ processPresenceUpdates(mycli)++ ticker.Stop()+ randomInterval := time.Duration(1+rand.Intn(3)) * time.Hour+ ticker = time.NewTicker(randomInterval)++ case <-mycli.killChannel[mycli.userID]:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received kill signal, stopping presence updates", mycli.userID)+ return // Encerra a goroutine quando receber sinal de kill+ }+ }+}++func processPresenceUpdates(mycli *MyClient) {+ now := time.Now()+ location, _ := time.LoadLocation("America/Sao_Paulo")+ nowSp := now.In(location)++ if nowSp.Hour() >= 1 && nowSp.Hour() < 24 {+ err := mycli.WAClient.SendPresence(context.Background(), types.PresenceUnavailable)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to set presence as unavailable %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Marked self as unavailable", mycli.userID)+ }++ time.Sleep(time.Duration(1+rand.Intn(5)) * time.Second)++ err = mycli.WAClient.SendPresence(context.Background(), types.PresenceAvailable)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to set presence as available %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Marked self as available", mycli.userID)+ }+ }+}++func (mycli *MyClient) myEventHandler(rawEvt interface{}) {+ userID := mycli.userID+ postMap := make(map[string]interface{})+ postMap["data"] = rawEvt+ doWebhook := false++ switch evt := rawEvt.(type) {+ case *events.AppStateSyncComplete:+ if len(mycli.WAClient.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {+ err := mycli.WAClient.SendPresence(context.Background(), types.PresenceUnavailable)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to send unavailable presence %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Marked self as unavailable", mycli.userID)+ }+ }+ case *events.Connected, *events.PushNameSetting:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] events.Connected to Whatsapp for user '%s'", mycli.userID, mycli.WAClient.Store.PushName)+ if len(mycli.WAClient.Store.PushName) > 0 {+ doWebhook = true+ postMap["event"] = "Connected"++ if postMap["data"] != nil {+ jsonBytes, err := json.Marshal(postMap["data"])+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)+ return+ }++ var dataMap map[string]interface{}+ err = json.Unmarshal(jsonBytes, &dataMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)+ return+ }++ postMap["data"] = dataMap+ } else {+ postMap["data"] = make(map[string]interface{})+ }++ dataMap := postMap["data"].(map[string]interface{})++ dataMap["status"] = "open"+ dataMap["jid"] = mycli.WAClient.Store.ID.String()+ dataMap["pushName"] = mycli.WAClient.Store.PushName++ // jid, ok := utils.ParseJID(mycli.WAClient.Store.ID.ToNonAD().User)+ // if ok {+ // profilePicUrl, err := mycli.clientPointer[mycli.userID].GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{+ // Preview: false,+ // })+ // if err != nil {+ // w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to get profile picture info: %v", mycli.userID, err)+ // } else {+ // dataMap["profilePicUrl"] = profilePicUrl.URL+ // }+ // }++ postMap["data"] = dataMap++ go schedulePresenceUpdates(mycli)++ err := mycli.WAClient.SendPresence(context.Background(), types.PresenceAvailable)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to send available presence %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Marked self as available", mycli.userID)+ }++ mycli.Instance.Connected = true+ mycli.Instance.DisconnectReason = ""+ err = mycli.instanceRepository.UpdateConnected(mycli.Instance.Id, mycli.Instance.Connected, mycli.Instance.DisconnectReason)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.Instance.Id, err)+ }++ err = mycli.instanceRepository.UpdateQrcode(mycli.Instance.Id, "")+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.Instance.Id, err)+ }+ }+ case *events.PairSuccess:+ doWebhook = true+ postMap["event"] = "PairSuccess"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("QR Pair Success for user '%s' with JID '%s' - '%s'", mycli.userID, evt.ID.String(), mycli.WAClient.Store.ID.String())++ instance, err := mycli.instanceRepository.GetInstanceByID(mycli.userID)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error getting instance: %s", mycli.userID, err)+ }++ instance.Qrcode = ""+ instance.Connected = true+ instance.DisconnectReason = ""+ instance.Jid = mycli.WAClient.Store.ID.String()++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Updating JID: %s in Instance: %s", mycli.userID, mycli.WAClient.Store.ID.String(), instance.Jid)++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Attempting to update instance in DB: %+v", mycli.userID, instance)+ err = mycli.instanceRepository.Update(instance)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Instance successfully updated", mycli.userID)+ }++ myUserInfo, found := mycli.userInfoCache.Get(mycli.token)++ if !found {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] No user info cached on pairing?", mycli.userID)+ } else {+ txtid := myUserInfo.(Values).Get("Id")+ token := myUserInfo.(Values).Get("Token")++ updatedUserInfo := utils.UpdateUserInfo(myUserInfo, "Jid", evt.ID.String())++ mycli.userInfoCache.Set(token, updatedUserInfo, cache.NoExpiration)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] User information set for user '%s'", mycli.userID, txtid)+ }++ if postMap["data"] != nil {+ jsonBytes, err := json.Marshal(postMap["data"])+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)+ return+ }++ var dataMap map[string]interface{}+ err = json.Unmarshal(jsonBytes, &dataMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)+ return+ }++ postMap["data"] = dataMap+ } else {+ postMap["data"] = make(map[string]interface{})+ }++ dataMap := postMap["data"].(map[string]interface{})++ dataMap["status"] = "open"+ dataMap["jid"] = mycli.WAClient.Store.ID.String()++ if mycli.WAClient.Store.PushName != "" {+ dataMap["pushName"] = mycli.WAClient.Store.PushName+ }++ postMap["data"] = dataMap+ case *events.StreamReplaced:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received StreamReplaced event", mycli.userID)+ return+ case *events.TemporaryBan:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] User received temporary ban for %s", mycli.userID, evt.Code.String())+ doWebhook = true+ postMap["event"] = "TemporaryBan"++ if postMap["data"] != nil {+ jsonBytes, err := json.Marshal(postMap["data"])+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)+ return+ }++ var dataMap map[string]interface{}+ err = json.Unmarshal(jsonBytes, &dataMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)+ return+ }++ postMap["data"] = dataMap+ } else {+ postMap["data"] = make(map[string]interface{})+ }++ dataMap := postMap["data"].(map[string]interface{})++ dataMap["reason"] = evt.Code.String()+ dataMap["expire"] = evt.Expire++ postMap["data"] = dataMap+ case *events.Message:+ doWebhook = true+ postMap["event"] = "Message"+ // Message received++ // Log message arrival with detailed info+ messageSize := "unknown"+ if evt.Message.GetDocumentMessage() != nil && evt.Message.GetDocumentMessage().FileLength != nil {+ messageSize = fmt.Sprintf("%d bytes", *evt.Message.GetDocumentMessage().FileLength)+ } else if evt.Message.GetVideoMessage() != nil && evt.Message.GetVideoMessage().FileLength != nil {+ messageSize = fmt.Sprintf("%d bytes", *evt.Message.GetVideoMessage().FileLength)+ } else if evt.Message.GetImageMessage() != nil && evt.Message.GetImageMessage().FileLength != nil {+ messageSize = fmt.Sprintf("%d bytes", *evt.Message.GetImageMessage().FileLength)+ } else if evt.Message.GetAudioMessage() != nil && evt.Message.GetAudioMessage().FileLength != nil {+ messageSize = fmt.Sprintf("%d bytes", *evt.Message.GetAudioMessage().FileLength)+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== MESSAGE RECEIVED ===== ID: %s, From: %s, Type: %s, Size: %s", mycli.userID, evt.Info.ID, evt.Info.Chat.String(), evt.Info.Type, messageSize)++ // se readMessages for true ele marca como lida+ if mycli.Instance.ReadMessages {+ messageIDs := []string{evt.Info.ID}+ err := mycli.WAClient.MarkRead(context.Background(), messageIDs, time.Now(), evt.Info.Sender, evt.Info.Sender)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to auto-mark message as read: %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Auto-marked message as read from %s", mycli.userID, evt.Info.Chat.String())+ }+ }++ // se ignoreStatus for true e o chat for broadcast ou o id for broadcast retorna+ if mycli.Instance.IgnoreStatus && (strings.Contains(evt.Info.Chat.String(), "@broadcast") || strings.Contains(evt.Info.ID, "@broadcast")) {+ return+ }++ // se ignoreGroup for true e o chat for grupo retorna+ if mycli.Instance.IgnoreGroups && strings.Contains(evt.Info.Chat.String(), "@g.us") {+ return+ }++ // Verifica advanced settings para ignorar grupos+ if (mycli.config.EventIgnoreGroup || mycli.Instance.IgnoreGroups) && strings.Contains(evt.Info.Chat.String(), "@g.us") {+ return+ }++ // Verifica advanced settings para ignorar status/broadcast+ if (mycli.config.EventIgnoreStatus || mycli.Instance.IgnoreStatus) && (strings.Contains(evt.Info.Chat.String(), "@broadcast") || strings.Contains(evt.Info.ID, "@broadcast")) {+ return+ }++ // Trata o caso especial onde Sender é @lid e SenderAlt é @s.whatsapp.net+ // Neste caso, devemos inverter: Sender e Chat devem ser @s.whatsapp.net, SenderAlt deve ser @lid+ senderStr := evt.Info.Sender.String()+ senderAltStr := evt.Info.SenderAlt.String()+ chatStr := evt.Info.Chat.String()++ if strings.Contains(senderStr, "@lid") && strings.Contains(senderAltStr, "@s.whatsapp.net") {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Detected LID/WhatsApp JID swap case - Sender: %s, SenderAlt: %s", mycli.userID, senderStr, senderAltStr)++ // Limpa os IDs antes de fazer a troca+ cleanSenderAlt := cleanSenderID(senderAltStr)+ cleanSender := cleanSenderID(senderStr)++ // Inverte: Sender e Chat recebem o @s.whatsapp.net, SenderAlt recebe o @lid+ if cleanedWhatsAppJID, err := types.ParseJID(cleanSenderAlt); err == nil {+ evt.Info.Sender = cleanedWhatsAppJID+ // Se Chat também é @lid, atualiza para @s.whatsapp.net+ if strings.Contains(chatStr, "@lid") {+ evt.Info.Chat = cleanedWhatsAppJID+ }+ }++ if cleanedLID, err := types.ParseJID(cleanSender); err == nil {+ evt.Info.SenderAlt = cleanedLID+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] JID swap completed - New Sender: %s, New SenderAlt: %s, New Chat: %s",+ mycli.userID, evt.Info.Sender.String(), evt.Info.SenderAlt.String(), evt.Info.Chat.String())+ } else {+ // Comportamento normal: apenas limpa os IDs+ cleanSender := cleanSenderID(senderStr)+ if cleanedJID, err := types.ParseJID(cleanSender); err == nil {+ evt.Info.Sender = cleanedJID+ }++ cleanSenderAlt := cleanSenderID(senderAltStr)+ if cleanedLID, err := types.ParseJID(cleanSenderAlt); err == nil {+ evt.Info.SenderAlt = cleanedLID+ }+ }++ // Auto-marca mensagens como lidas se configurado+ if mycli.Instance.ReadMessages && !evt.Info.IsFromMe {+ go func() {+ time.Sleep(1 * time.Second) // Pequeno delay para parecer mais natural+ err := mycli.WAClient.MarkRead(context.Background(), []types.MessageID{evt.Info.ID}, evt.Info.Timestamp, evt.Info.Chat, evt.Info.Sender)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to auto-mark message as read: %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Auto-marked message as read from %s", mycli.userID, evt.Info.Chat.String())+ }+ }()+ }++ parsedMessageType := utils.GetMessageType(evt.Message)+ if parsedMessageType == "ignore" || strings.HasPrefix(parsedMessageType, "unknown_protocol_") {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message ignored because it's a unknown protocol message", mycli.userID)+ return+ }++ if postMap["data"] != nil {+ jsonBytes, err := json.Marshal(postMap["data"])+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)+ return+ }++ var dataMap map[string]interface{}+ err = json.Unmarshal(jsonBytes, &dataMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)+ return+ }++ postMap["data"] = dataMap+ } else {+ postMap["data"] = make(map[string]interface{})+ }++ dataMap, ok := postMap["data"].(map[string]interface{})+ if !ok {+ dataMap = make(map[string]interface{})+ }++ if evt.Message.GetPollUpdateMessage() != nil {+ fmt.Printf("[POLL DEBUG] 🎯 PollUpdateMessage detected!\n")+ fmt.Printf("[POLL DEBUG] � BEFORE accessing evt.Info - Sender: %s, Server: %s\n", evt.Info.Sender.String(), evt.Info.Sender.Server)+ fmt.Printf("[POLL DEBUG] 📍 BEFORE accessing evt.Info - SenderAlt: %s\n", evt.Info.SenderAlt.String())+ fmt.Printf("[POLL DEBUG] �� mycli.WAClient is nil: %v\n", mycli.WAClient == nil)+ if mycli.WAClient != nil {+ fmt.Printf("[POLL DEBUG] ✅ mycli.WAClient is initialized: %s\n", mycli.WAClient.Store.ID)+ }++ decrypted, err := mycli.clientPointer[mycli.userID].DecryptPollVote(context.Background(), evt)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decrypt vote: %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Selected options in decrypted vote:", mycli.userID)+ for _, option := range decrypted.SelectedOptions {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("- %X", option)++ }++ // NOVO: Salvar voto no banco de dados de forma NÃO-INVASIVA+ if mycli.pollService != nil {+ go func() {+ defer func() {+ if r := recover(); r != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Panic ao salvar voto: %v", mycli.userID, r)+ }+ }()++ pollKey := evt.Message.GetPollUpdateMessage().GetPollCreationMessageKey()+ if pollKey == nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] PollCreationMessageKey not found", mycli.userID)+ return+ }++ pollInfo := &types.MessageInfo{+ ID: pollKey.GetID(),+ MessageSource: types.MessageSource{+ Chat: evt.Info.Chat, // Usar o chat do evento atual+ },+ }++ // Construir modelo de voto usando helper seguro+ // evt.Info já passou pelo JID swap, então Sender = número real+ pollVote := poll_service.BuildPollVoteFromEvent(+ pollInfo,+ &evt.Info,+ decrypted,+ "", // CompanyID não disponível no MyClient, será vazio+ mycli.Instance.Id,+ )++ // Salvar no banco com timeout de segurança+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ if err := mycli.pollService.SavePollVote(ctx, pollVote); err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to save poll vote to database: %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Poll vote saved to database successfully", mycli.userID)+ }+ }()+ }+ }+ }++ var quotedMessage *waE2E.Message+ var stanzaID string++ if evt.Message.GetExtendedTextMessage() != nil {+ quotedMessage = evt.Message.GetExtendedTextMessage().GetContextInfo().GetQuotedMessage()+ stanzaID = evt.Message.GetExtendedTextMessage().GetContextInfo().GetStanzaID()+ } else if evt.Message.GetImageMessage() != nil {+ quotedMessage = evt.Message.GetImageMessage().GetContextInfo().GetQuotedMessage()+ stanzaID = evt.Message.GetImageMessage().GetContextInfo().GetStanzaID()+ } else if evt.Message.GetAudioMessage() != nil {+ quotedMessage = evt.Message.GetAudioMessage().GetContextInfo().GetQuotedMessage()+ stanzaID = evt.Message.GetAudioMessage().GetContextInfo().GetStanzaID()+ } else if evt.Message.GetDocumentMessage() != nil {+ quotedMessage = evt.Message.GetDocumentMessage().GetContextInfo().GetQuotedMessage()+ stanzaID = evt.Message.GetDocumentMessage().GetContextInfo().GetStanzaID()+ } else if evt.Message.GetVideoMessage() != nil {+ quotedMessage = evt.Message.GetVideoMessage().GetContextInfo().GetQuotedMessage()+ stanzaID = evt.Message.GetVideoMessage().GetContextInfo().GetStanzaID()+ }++ if stanzaID != "" && quotedMessage != nil {+ quotedMap := make(map[string]interface{})++ quotedMap["stanzaID"] = stanzaID+ quotedMap["quotedMessage"] = quotedMessage++ dataMap["quoted"] = quotedMap+ dataMap["isQuoted"] = true+ }++ if mycli.config.WebhookFiles {+ isMedia := false++ img := evt.Message.GetImageMessage()+ audio := evt.Message.GetAudioMessage()+ document := evt.Message.GetDocumentMessage()+ video := evt.Message.GetVideoMessage()+ sticker := evt.Message.GetStickerMessage()++ // Check for associated child messages (like media in replies)+ var associatedImg *waE2E.ImageMessage+ var associatedAudio *waE2E.AudioMessage+ var associatedDocument *waE2E.DocumentMessage+ var associatedVideo *waE2E.VideoMessage+ var associatedSticker *waE2E.StickerMessage++ if evt.Message.GetAssociatedChildMessage() != nil {+ childMsg := evt.Message.GetAssociatedChildMessage().GetMessage()+ if childMsg != nil {+ associatedImg = childMsg.GetImageMessage()+ associatedAudio = childMsg.GetAudioMessage()+ associatedDocument = childMsg.GetDocumentMessage()+ associatedVideo = childMsg.GetVideoMessage()+ associatedSticker = childMsg.GetStickerMessage()+ }+ }++ if img != nil || audio != nil || document != nil || video != nil || sticker != nil ||+ associatedImg != nil || associatedAudio != nil || associatedDocument != nil ||+ associatedVideo != nil || associatedSticker != nil {+ isMedia = true+ }++ if isMedia {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing media message - ID: %s", mycli.userID, evt.Info.ID)++ var data []byte+ var err error+ var extension string+ var mimeType string+ var mediaSize int64++ // Create context with timeout for large files+ downloadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ downloadStart := time.Now()++ // Handle regular media messages+ if img != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Downloading image - ID: %s", mycli.userID, evt.Info.ID)+ data, err = mycli.WAClient.Download(downloadCtx, img)+ extension = ".jpg"+ mimeType = "image/jpeg"+ if img.FileLength != nil {+ mediaSize = int64(*img.FileLength)+ }+ } else if audio != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Downloading audio - ID: %s", mycli.userID, evt.Info.ID)+ data, err = mycli.WAClient.Download(downloadCtx, audio)+ extension = ".ogg"+ mimeType = "audio/ogg"+ if audio.FileLength != nil {+ mediaSize = int64(*audio.FileLength)+ }+ } else if document != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Downloading document - ID: %s, FileName: %s, Size: %d bytes", mycli.userID, evt.Info.ID, document.GetFileName(), document.GetFileLength())+ data, err = mycli.WAClient.Download(downloadCtx, document)+ extension = getExtensionFromMimeType(document.GetMimetype())+ mimeType = document.GetMimetype()+ if document.FileLength != nil {+ mediaSize = int64(*document.FileLength)+ }+ } else if video != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Downloading video - ID: %s, Size: %d bytes", mycli.userID, evt.Info.ID, video.GetFileLength())+ data, err = mycli.WAClient.Download(downloadCtx, video)+ extension = ".mp4"+ mimeType = "video/mp4"+ if video.FileLength != nil {+ mediaSize = int64(*video.FileLength)+ }+ } else if sticker != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Downloading sticker - ID: %s", mycli.userID, evt.Info.ID)+ data, err = mycli.WAClient.Download(downloadCtx, sticker)+ extension = ".png"+ mimeType = "image/png"+ if sticker.FileLength != nil {+ mediaSize = int64(*sticker.FileLength)+ }++ if err == nil {+ webpReader := bytes.NewReader(data)+ img, err := webp.Decode(webpReader)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decode webp image: %v", mycli.userID, err)+ return+ }++ var pngBuffer bytes.Buffer+ err = png.Encode(&pngBuffer, img)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to encode png image: %v", mycli.userID, err)+ return+ }++ data = pngBuffer.Bytes()+ }+ // Handle associated child media messages+ } else if associatedImg != nil {+ data, err = mycli.WAClient.Download(context.Background(), associatedImg)+ extension = ".jpg"+ mimeType = "image/jpeg"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child image message", mycli.userID)+ } else if associatedAudio != nil {+ data, err = mycli.WAClient.Download(context.Background(), associatedAudio)+ extension = ".ogg"+ mimeType = "audio/ogg"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child audio message", mycli.userID)+ } else if associatedDocument != nil {+ data, err = mycli.WAClient.Download(context.Background(), associatedDocument)+ extension = getExtensionFromMimeType(associatedDocument.GetMimetype())+ mimeType = associatedDocument.GetMimetype()+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child document message", mycli.userID)+ } else if associatedVideo != nil {+ data, err = mycli.WAClient.Download(context.Background(), associatedVideo)+ extension = ".mp4"+ mimeType = "video/mp4"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child video message", mycli.userID)+ } else if associatedSticker != nil {+ data, err = mycli.WAClient.Download(context.Background(), associatedSticker)+ extension = ".png"+ mimeType = "image/png"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing associated child sticker message", mycli.userID)++ webpReader := bytes.NewReader(data)+ img, err := webp.Decode(webpReader)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to decode webp image: %v", mycli.userID, err)+ return+ }++ var pngBuffer bytes.Buffer+ err = png.Encode(&pngBuffer, img)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to encode png image: %v", mycli.userID, err)+ return+ }++ data = pngBuffer.Bytes()+ }++ downloadDuration := time.Since(downloadStart)++ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to download media - ID: %s, Size: %d bytes, Duration: %v, Error: %v", mycli.userID, evt.Info.ID, mediaSize, downloadDuration, err)++ // Check if it's a timeout error+ if downloadCtx.Err() == context.DeadlineExceeded {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Download timeout exceeded (5 minutes) for large file - ID: %s, Size: %d bytes", mycli.userID, evt.Info.ID, mediaSize)+ }++ // Don't return here - continue processing the message without media+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Continuing message processing without media download - ID: %s", mycli.userID, evt.Info.ID)+ } else {+ actualSize := len(data)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Media download successful - ID: %s, Expected: %d bytes, Actual: %d bytes, Duration: %v", mycli.userID, evt.Info.ID, mediaSize, actualSize, downloadDuration)++ // Check for size mismatch+ if mediaSize > 0 && int64(actualSize) != mediaSize {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Size mismatch detected - ID: %s, Expected: %d, Got: %d", mycli.userID, evt.Info.ID, mediaSize, actualSize)+ }++ // Log large file processing+ if actualSize > 13*1024*1024 { // 13MB+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Processing large file (>13MB) - ID: %s, Size: %d bytes", mycli.userID, evt.Info.ID, actualSize)+ }+ }++ messageMap, ok := dataMap["Message"].(map[string]interface{})+ if !ok {+ messageMap = make(map[string]interface{})+ }++ // Only process storage if download was successful+ if err == nil && len(data) > 0 {+ if mycli.config.MinioEnabled {+ fileName := evt.Info.ID + extension+ storageStart := time.Now()++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Uploading to S3/Minio - ID: %s, FileName: %s, Size: %d bytes", mycli.userID, evt.Info.ID, fileName, len(data))++ mediaURL, err := mycli.mediaStorage.Store(context.Background(), data, fileName, mimeType)+ storageDuration := time.Since(storageStart)++ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to store media in S3/Minio - ID: %s, Size: %d bytes, Duration: %v, Error: %v", mycli.userID, evt.Info.ID, len(data), storageDuration, err)++ // Continue processing without storage URL+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Continuing message processing without S3 URL - ID: %s", mycli.userID, evt.Info.ID)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] S3/Minio upload successful - ID: %s, Size: %d bytes, Duration: %v, URL: %s", mycli.userID, evt.Info.ID, len(data), storageDuration, mediaURL)+ messageMap["mediaUrl"] = mediaURL+ messageMap["mimetype"] = mimeType+ }+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Encoding to base64 - ID: %s, Size: %d bytes", mycli.userID, evt.Info.ID, len(data))+ encodeStart := time.Now()++ encodeData := base64.StdEncoding.EncodeToString(data)+ encodeDuration := time.Since(encodeStart)++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Base64 encoding completed - ID: %s, Original: %d bytes, Encoded: %d chars, Duration: %v", mycli.userID, evt.Info.ID, len(data), len(encodeData), encodeDuration)+ messageMap["base64"] = encodeData+ }+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Skipping media storage due to download failure - ID: %s", mycli.userID, evt.Info.ID)+ }++ dataMap["Message"] = messageMap+ }+ }++ isGroup := strings.HasSuffix(evt.Info.Chat.String(), "@g.us")+ if isGroup {+ groupData, err := mycli.WAClient.GetGroupInfo(context.Background(), evt.Info.Chat)+ if err == nil {+ dataMap["groupData"] = groupData+ }+ }++ delete(dataMap, "RawMessage")++ if message, ok := dataMap["Message"].(map[string]interface{}); ok {+ if imageMessage, ok := message["imageMessage"].(map[string]interface{}); ok {+ delete(imageMessage, "JPEGThumbnail")+ message["imageMessage"] = imageMessage+ dataMap["Message"] = message+ }++ if videoMessage, ok := message["videoMessage"].(map[string]interface{}); ok {+ delete(videoMessage, "JPEGThumbnail")+ message["videoMessage"] = videoMessage+ dataMap["Message"] = message+ }++ if documentMessage, ok := message["documentMessage"].(map[string]interface{}); ok {+ delete(documentMessage, "JPEGThumbnail")+ message["documentMessage"] = documentMessage+ dataMap["Message"] = message+ }+ }++ postMap["data"] = dataMap++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== MESSAGE PROCESSING COMPLETED ===== ID: %s, From: %s, Type: %s, Webhook: %v", mycli.userID, evt.Info.ID, evt.Info.Chat.String(), evt.Info.Type, doWebhook)+ case *events.Receipt:+ doWebhook = true+ postMap["event"] = "Receipt"++ // se ignoreGroup for true e o chat for grupo retorna+ if mycli.Instance.IgnoreGroups && strings.Contains(evt.Chat.String(), "@g.us") {+ return+ }++ if mycli.config.EventIgnoreGroup && strings.Contains(evt.Chat.String(), "@g.us") {+ return+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Receipt received with ID: %s from %s with type %s", mycli.userID, evt.MessageIDs[0], evt.SourceString(), evt.Type)++ if evt.Type == types.ReceiptTypeRead || evt.Type == types.ReceiptTypeReadSelf {++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message was read by %s", mycli.userID, evt.SourceString())+ if evt.Type == types.ReceiptTypeRead {+ postMap["state"] = "Read"+ for _, v := range evt.MessageIDs {+ messageKey := fmt.Sprintf("%s_%s_%s", mycli.userID, v, "Read")+ if _, found := mycli.processedMessages.Get(messageKey); found {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message duplicated ignored: %s", mycli.userID, v)+ continue+ }++ mycli.processedMessages.Set(messageKey, true, 30*time.Minute)++ var message message_model.Message++ message.MessageID = v+ message.Timestamp = evt.Timestamp.Format("2006-01-02 15:04:05")+ message.Status = "Read"+ message.Source = evt.Chat.ToNonAD().User++ if mycli.config.DatabaseSaveMessages {+ go mycli.messageRepository.InsertMessage(message)+ }+ }+ } else {+ postMap["state"] = "ReadSelf"+ }+ } else if evt.Type == types.ReceiptTypeDelivered {+ postMap["state"] = "Delivered"++ var message message_model.Message++ message.MessageID = evt.MessageIDs[0]+ message.Timestamp = evt.Timestamp.Format("2006-01-02 15:04:05")+ message.Status = "Delivered"+ message.Source = evt.Chat.ToNonAD().User++ messageKey := fmt.Sprintf("%s_%s_%s", mycli.userID, evt.MessageIDs[0], "Delivered")+ if _, found := mycli.processedMessages.Get(messageKey); found {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message duplicated ignored: %s", mycli.userID, evt.MessageIDs[0])+ return+ }++ mycli.processedMessages.Set(messageKey, true, 30*time.Minute)++ if mycli.config.DatabaseSaveMessages {+ go mycli.messageRepository.InsertMessage(message)+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message delivered to %s", mycli.userID, evt.SourceString())+ } else {+ return+ }+ case *events.Presence:+ doWebhook = true+ postMap["event"] = "Presence"++ if evt.Unavailable {+ postMap["state"] = "offline"+ if evt.LastSeen.IsZero() {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] User is now offline", mycli.userID)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] User is now offline since %s", mycli.userID, evt.LastSeen.Format("2006-01-02 15:04:05"))+ }+ } else {+ postMap["state"] = "online"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] User is now online", mycli.userID)+ }+ case *events.Archive:+ doWebhook = true+ postMap["event"] = "Archive"++ dataMap := postMap["data"].(map[string]interface{})+ dataMap["JID"] = evt.JID+ dataMap["Timestamp"] = evt.Timestamp+ dataMap["Action"] = evt.Action+ dataMap["FromFullSync"] = evt.FromFullSync+ postMap["data"] = dataMap++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Chat archived", mycli.userID)+ case *events.HistorySync:+ doWebhook = true+ postMap["event"] = "HistorySync"++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] History sync event received %+v", mycli.userID, evt.Data.SyncType)+ case *events.AppState:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] App state event received %+v", mycli.userID, evt)+ case *events.LoggedOut:+ doWebhook = true+ postMap["event"] = "LoggedOut"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Logged out for reason %s", mycli.userID, evt.Reason.String())++ // Limpar cache de userInfo para esta instância+ mycli.userInfoCache.Delete(mycli.Instance.Token)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] UserInfo cache cleared for token: %s", mycli.userID, mycli.Instance.Token)++ mycli.Instance.DisconnectReason = evt.Reason.String()+ mycli.Instance.Connected = false+ err := mycli.instanceRepository.UpdateConnected(mycli.Instance.Id, mycli.Instance.Connected, mycli.Instance.DisconnectReason)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.Instance.Id, err)+ }++ if postMap["data"] != nil {+ jsonBytes, err := json.Marshal(postMap["data"])+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal postMap['data']: %v", mycli.userID, err)+ return+ }++ var dataMap map[string]interface{}+ err = json.Unmarshal(jsonBytes, &dataMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to unmarshal postMap['data'] to map[string]interface{}: %v", mycli.userID, err)+ return+ }++ postMap["data"] = dataMap+ } else {+ postMap["data"] = make(map[string]interface{})+ }++ dataMap := postMap["data"].(map[string]interface{})++ dataMap["reason"] = evt.Reason.String()++ // Enviar evento LoggedOut para webhook/RabbitMQ ANTES de matar o canal+ postMap["instanceToken"] = mycli.Instance.Token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = mycli.Instance.Name++ values, err := json.Marshal(postMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal JSON for LoggedOut event", mycli.userID)+ } else {+ var queueName string+ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", mycli.userID, postMap["event"]))+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== DISPATCHING LOGGEDOUT EVENT ===== Queue: %s", mycli.userID, queueName)++ // Enviar para webhook/RabbitMQ+ go mycli.service.CallWebhook(mycli.Instance, queueName, values)++ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Sending LoggedOut to global queues - AMQP: %v, NATS: %v", mycli.userID, mycli.config.AmqpGlobalEnabled, mycli.config.NatsGlobalEnabled)+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }+ }++ // Agora mata o canal DEPOIS de enviar o evento+ mycli.killChannel[mycli.userID] <- true+ case *events.ChatPresence:+ doWebhook = true+ postMap["event"] = "ChatPresence"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Chat presence received %+v", mycli.userID, evt)+ case *events.CallOffer:+ doWebhook = true+ postMap["event"] = "CallOffer"++ // Verifica se deve rejeitar chamadas automaticamente+ if mycli.Instance.RejectCall {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Auto-rejecting call from %s", mycli.userID, evt.CallCreator.String())++ // Rejeita a chamada+ mycli.WAClient.RejectCall(context.Background(), evt.CallCreator, evt.CallID)++ // Envia mensagem de rejeição se configurada+ if mycli.Instance.MsgRejectCall != "" {+ msg := &waE2E.Message{+ ExtendedTextMessage: &waE2E.ExtendedTextMessage{+ Text: &mycli.Instance.MsgRejectCall,+ },+ }++ _, err := mycli.WAClient.SendMessage(context.Background(), evt.CallCreator, msg)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to send reject call message: %v", mycli.userID, err)+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Sent reject call message to %s", mycli.userID, evt.CallCreator.String())+ }+ }+ return+ }++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got call offer %+v", mycli.userID, evt)+ case *events.CallAccept:+ doWebhook = true+ postMap["event"] = "CallAccept"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got call accept %+v", mycli.userID, evt)+ case *events.CallTerminate:+ doWebhook = true+ postMap["event"] = "CallTerminate"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got call terminate %+v", mycli.userID, evt)+ case *events.CallOfferNotice:+ doWebhook = true+ postMap["event"] = "CallOfferNotice"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got call offer notice %+v", mycli.userID, evt)+ case *events.CallRelayLatency:+ doWebhook = true+ postMap["event"] = "CallRelayLatency"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got call relay latency %+v", mycli.userID, evt)+ case *events.OfflineSyncCompleted:+ doWebhook = true+ postMap["event"] = "OfflineSyncCompleted"+ case *events.ConnectFailure:+ doWebhook = true+ postMap["event"] = "ConnectFailure"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Connection failed with reason %s", mycli.userID, evt.Reason.String())++ // Limpar cache de userInfo para esta instância+ mycli.userInfoCache.Delete(mycli.Instance.Token)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] UserInfo cache cleared for token: %s", mycli.userID, mycli.Instance.Token)++ mycli.Instance.DisconnectReason = evt.Reason.String()+ mycli.Instance.Connected = false+ err := mycli.instanceRepository.UpdateConnected(mycli.Instance.Id, mycli.Instance.Connected, mycli.Instance.DisconnectReason)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.Instance.Id, err)+ }+ case *events.Disconnected:+ doWebhook = true+ postMap["event"] = "Disconnected"++ // Limpar cache de userInfo para esta instância (mas não para reconexão automática)+ mycli.userInfoCache.Delete(mycli.Instance.Token)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] UserInfo cache cleared for token: %s", mycli.userID, mycli.Instance.Token)++ mycli.Instance.DisconnectReason = "Disconnected emitted because the websocket is closed by the server."+ mycli.Instance.Connected = false+ err := mycli.instanceRepository.UpdateConnected(mycli.Instance.Id, mycli.Instance.Connected, mycli.Instance.DisconnectReason)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error updating instance: %s", mycli.Instance.Id, err)+ }++ // Trigger instance restart via websocket-capable service (non-blocking)+ go func(instanceID string) {+ mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Disconnected detected, restarting instance", instanceID)+ if err := mycli.service.ReconnectClient(instanceID); err != nil {+ mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to restart instance: %v", instanceID, err)+ }+ }(mycli.userID)+ case *events.LabelEdit:+ doWebhook = true+ postMap["event"] = "LabelEdit"+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Got label edit %+v", mycli.userID, evt.Action)++ label := label_model.Label{+ InstanceID: mycli.userID,+ LabelID: evt.LabelID,+ LabelName: utils.GetStringValue(evt.Action.Name),+ LabelColor: fmt.Sprintf("%d", evt.Action.Color),+ PredefinedId: fmt.Sprintf("%d", evt.Action.PredefinedID),+ }++ err := mycli.labelRepository.UpsertLabel(label)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to upsert label: %v", mycli.userID, err)+ }+ case *events.LabelAssociationChat:+ doWebhook = true+ postMap["event"] = "LabelAssociationChat"++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Label association chat received %+v", mycli.userID, evt)+ case *events.LabelAssociationMessage:+ doWebhook = true+ postMap["event"] = "LabelAssociationMessage"++ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Label association message received %+v", mycli.userID, evt)+ case *events.Contact:+ doWebhook = true+ postMap["event"] = "Contact"+ case *events.PushName:+ doWebhook = true+ postMap["event"] = "PushName"+ case *events.IdentityChange:+ doWebhook = false+ case *events.GroupInfo:+ doWebhook = true+ postMap["event"] = "GroupInfo"+ case *events.JoinedGroup:+ doWebhook = true+ postMap["event"] = "JoinedGroup"+ case *events.NewsletterJoin:+ doWebhook = true+ postMap["event"] = "NewsletterJoin"+ case *events.NewsletterLeave:+ doWebhook = true+ postMap["event"] = "NewsletterLeave"+ case *events.UndecryptableMessage:+ jsonEvt, err := json.Marshal(evt)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Undecryptable message received: %s", mycli.userID, evt.Info.ID)+ }+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Undecryptable message received all: %+v", mycli.userID, string(jsonEvt))++ if evt.UnavailableType == "view_once" {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Undecryptable message received view_once: %s", mycli.userID, evt.Info.ID)++ doWebhook = true+ postMap["event"] = "Message"++ postMap["data"] = evt+ } else if strings.HasPrefix(evt.Info.ID, "66") || strings.HasPrefix(evt.Info.ID, "67") {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] ID 66 or 67 found, reconnecting client", mycli.userID)+ mycli.WAClient.Disconnect()+ err := mycli.WAClient.Connect()+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Error reconnecting client: %s", mycli.userID, err)+ }+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] ID is not 66 or 67 or view_once, skipping", mycli.userID)+ }+ default:+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Unhandled event %s: %+v", mycli.userID, fmt.Sprintf("%T", evt), evt)+ return+ }++ if doWebhook {+ postMap["instanceToken"] = mycli.token+ postMap["instanceId"] = mycli.userID+ postMap["instanceName"] = mycli.Instance.Name++ values, err := json.Marshal(postMap)+ if err != nil {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal JSON for queue", mycli.userID)+ return+ }++ var queueName string+ if _, ok := postMap["event"]; ok {+ queueName = strings.ToLower(fmt.Sprintf("%s.%s", userID, postMap["event"]))+ }++ // Log webhook dispatch+ eventType := "unknown"+ if event, ok := postMap["event"].(string); ok {+ eventType = event+ }++ dataSize := len(values)+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] ===== DISPATCHING WEBHOOK ===== Event: %s, Queue: %s, DataSize: %d bytes", mycli.userID, eventType, queueName, dataSize)++ go mycli.service.CallWebhook(mycli.Instance, queueName, values)++ if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Sending to global queues - Event: %s, AMQP: %v, NATS: %v", mycli.userID, eventType, mycli.config.AmqpGlobalEnabled, mycli.config.NatsGlobalEnabled)+ go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)+ }+ } else {+ mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] ===== WEBHOOK SKIPPED ===== doWebhook=false", mycli.userID)+ }+}++func (w *whatsmeowService) CallWebhook(instance *instance_model.Instance, queueName string, jsonData []byte) {+ var data map[string]interface{}+ if err := json.Unmarshal(jsonData, &data); err != nil {+ return+ }++ eventType, ok := data["event"].(string)+ if !ok {+ return+ }++ eventArray := strings.Split(instance.Events, ",")++ var subscriptions []string++ if len(eventArray) < 1 {+ subscriptions = append(subscriptions, event_types.MESSAGE)+ } else {+ for _, arg := range eventArray {+ if !event_types.IsEventType(arg) {+ w.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Message type discarded: %s", instance.Id, arg)+ continue+ }+ if !utils.Find(subscriptions, arg) {+ subscriptions = append(subscriptions, arg)+ }++ }+ }++ if contains(subscriptions, "ALL") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ return+ }++ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] subscriptions %s eventType %s", instance.Id, subscriptions, eventType)++ switch eventType {+ case "Message":+ if contains(subscriptions, "MESSAGE") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "SendMessage":+ if contains(subscriptions, "SEND_MESSAGE") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "Receipt":+ if contains(subscriptions, "READ_RECEIPT") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "Presence":+ if contains(subscriptions, "PRESENCE") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "HistorySync":+ if contains(subscriptions, "HISTORY_SYNC") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "ChatPresence", "Archive":+ if contains(subscriptions, "CHAT_PRESENCE") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "CallOffer", "CallAccept", "CallTerminate", "CallOfferNotice", "CallRelayLatency":+ if contains(subscriptions, "CALL") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "Connected", "PairSuccess", "TemporaryBan", "LoggedOut", "ConnectFailure", "Disconnected":+ if contains(subscriptions, "CONNECTION") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "LabelEdit", "LabelAssociationChat", "LabelAssociationMessage":+ if contains(subscriptions, "LABEL") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "Contact", "PushName":+ if contains(subscriptions, "CONTACT") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "GroupInfo", "JoinedGroup":+ if contains(subscriptions, "GROUP") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "NewsletterJoin", "NewsletterLeave":+ if contains(subscriptions, "NEWSLETTER") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }+ case "QRCode", "QRTimeout", "QRSuccess":+ if contains(subscriptions, "QRCODE") {+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)+ w.sendToQueueOrWebhook(instance, queueName, jsonData)+ }++ default:+ return+ }+}++func contains(subscriptions []string, event string) bool {+ for _, sub := range subscriptions {+ if strings.EqualFold(sub, event) {+ return true+ }+ }+ return false+}++func (w *whatsmeowService) sendToQueueOrWebhook(instance *instance_model.Instance, queueName string, jsonData []byte) {+ if instance.RabbitmqEnable == "enabled" || instance.RabbitmqEnable == "true" {+ err := w.rabbitmqProducer.Produce(queueName, jsonData, instance.RabbitmqEnable, instance.Id)+ if err != nil {+ w.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to send message to rabbitmq: %s", instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent to rabbitmq successfully", instance.Id)+ }++ if instance.NatsEnable == "enabled" || instance.NatsEnable == "true" {+ err := w.natsProducer.Produce(queueName, jsonData, instance.NatsEnable, instance.Id)+ if err != nil {+ w.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to send message to nats: %s", instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent to nats successfully", instance.Id)+ }++ if instance.WebSocketEnable == "enabled" || instance.WebSocketEnable == "true" {+ err := w.websocketProducer.Produce(queueName, jsonData, instance.Id, instance.Token)+ if err != nil {+ w.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to send message to websocket: %s", instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent to websocket successfully", instance.Id)+ }++ if instance.Webhook != "" && instance.Webhook != "disabled" {+ err := w.webhookProducer.Produce(queueName, jsonData, instance.Webhook, instance.Id)+ if err != nil {+ w.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Failed to send message to webhook: %s", instance.Id, err)+ return+ }+ w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Message sent to webhook successfully", instance.Id)+ }+}++func (w whatsmeowService) StartInstance(instanceId string) error {+ instance, err := w.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ return err+ }++ if instance.Proxy == "" && w.config.ProxyHost != "" && w.config.ProxyPort != "" && w.config.ProxyUsername != "" && w.config.ProxyPassword != "" {+ instance.Proxy = fmt.Sprintf(`{"host": "%s", "port": "%s", "username": "%s", "password": "%s"}`, w.config.ProxyHost, w.config.ProxyPort, w.config.ProxyUsername, w.config.ProxyPassword)++ err = w.instanceRepository.UpdateProxy(instance.Id, instance.Proxy)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Failed to update instance: %s", instanceId, err)+ return err+ }+ }++ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Starting client", instance.Id)++ v := Values{map[string]string{+ "Id": instance.Id,+ "Jid": instance.Jid,+ "Token": instance.Token,+ "Events": instance.Events,+ "osName": instance.OsName,+ "Proxy": instance.Proxy,+ }}++ w.userInfoCache.Set(instance.Token, v, cache.NoExpiration)++ eventArray := strings.Split(instance.Events, ",")++ var subscribedEvents []string++ if len(eventArray) < 1 {+ subscribedEvents = append(subscribedEvents, event_types.MESSAGE)+ } else {+ for _, arg := range eventArray {+ if !event_types.IsEventType(arg) {+ w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Message type discarded: %s", instanceId, arg)+ continue+ }+ if !utils.Find(subscribedEvents, arg) {+ subscribedEvents = append(subscribedEvents, arg)+ }++ }+ }++ w.killChannel[instance.Id] = make(chan bool)++ clientData := &ClientData{+ Instance: instance,+ Subscriptions: subscribedEvents,+ Phone: "",+ IsProxy: false,+ }++ if instance.Proxy != "" {+ var proxyConfig ProxyConfig+ err := json.Unmarshal([]byte(instance.Proxy), &proxyConfig)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] error unmarshalling proxy config", instanceId)+ return err+ }++ if proxyConfig.Host != "" {+ clientData.IsProxy = true+ }+ }++ go w.StartClient(clientData)++ return nil+}++func (w whatsmeowService) ConnectOnStartup(clientName string) {+ w.loggerWrapper.GetLogger(clientName).LogInfo("Connecting all instances on startup")+ var instances []*instance_model.Instance+ var err error++ if clientName != "" {+ instances, err = w.instanceRepository.GetAllConnectedInstancesByClientName(clientName)+ if err != nil {+ w.loggerWrapper.GetLogger(clientName).LogError("[%s] Error getting all connected instances: %s", clientName, err)+ return+ }+ } else {+ instances, err = w.instanceRepository.GetAllConnectedInstances()+ if err != nil {+ w.loggerWrapper.GetLogger(clientName).LogError("[%s] Error getting all connected instances: %s", clientName, err)+ return+ }+ }++ w.loggerWrapper.GetLogger(clientName).LogInfo("[%s] Found %d connected instances", clientName, len(instances))++ for _, instance := range instances {+ w.loggerWrapper.GetLogger(clientName).LogInfo("[%s] Starting client for user '%s'", clientName, instance.Id)++ err := w.StartInstance(instance.Id)+ if err != nil {+ w.loggerWrapper.GetLogger(clientName).LogError("[%s] Error starting client: %s", clientName, err)+ }+ }+}++func getExtensionFromMimeType(mimeType string) string {+ switch mimeType {+ case "image/jpeg":+ return ".jpg"+ case "image/png":+ return ".png"+ case "image/webp":+ return ".webp"+ case "video/mp4":+ return ".mp4"+ case "audio/ogg":+ return ".ogg"+ case "audio/mpeg":+ return ".mp3"+ case "application/pdf":+ return ".pdf"+ case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":+ return ".docx"+ case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":+ return ".xlsx"+ case "application/vnd.openxmlformats-officedocument.presentationml.presentation":+ return ".pptx"+ default:+ // Se não encontrar um tipo conhecido, extrai a extensão do mimetype+ parts := strings.Split(mimeType, "/")+ if len(parts) > 1 {+ return "." + parts[1]+ }+ return ".bin"+ }+}++func (w *whatsmeowService) SendToGlobalQueues(eventType string, payload []byte, userId string) {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Starting sendToGlobalQueues for event: %s", userId, eventType)++ // AMQP: AMQP_SPECIFIC_EVENTS tem prioridade sobre AMQP_GLOBAL_EVENTS+ if w.config.AmqpGlobalEnabled {+ var shouldSendToAmqp bool+ var amqpQueueName string++ // Se AMQP_SPECIFIC_EVENTS estiver configurada, ela tem prioridade+ if len(w.config.AmqpSpecificEvents) > 0 {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Using AMQP_SPECIFIC_EVENTS (priority over AMQP_GLOBAL_EVENTS)", userId)+ // Verifica se o evento específico está na lista+ if utils.Find(w.config.AmqpSpecificEvents, eventType) {+ shouldSendToAmqp = true+ amqpQueueName = strings.ToLower(eventType)+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Event %s found in AMQP_SPECIFIC_EVENTS", userId, eventType)+ }+ } else {+ // Fallback para AMQP_GLOBAL_EVENTS (modo antigo com grupos de eventos)+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Using AMQP_GLOBAL_EVENTS (fallback mode)", userId)++ // Mapeia o evento do Whatsmeow para o tipo de evento global+ var globalEventType string+ switch eventType {+ case "Message":+ globalEventType = "MESSAGE"+ case "SendMessage":+ globalEventType = "SEND_MESSAGE"+ case "Receipt":+ globalEventType = "READ_RECEIPT"+ case "Presence":+ globalEventType = "PRESENCE"+ case "HistorySync":+ globalEventType = "HISTORY_SYNC"+ case "ChatPresence", "Archive":+ globalEventType = "CHAT_PRESENCE"+ case "CallOffer", "CallAccept", "CallTerminate", "CallOfferNotice", "CallRelayLatency":+ globalEventType = "CALL"+ case "Connected", "PairSuccess", "TemporaryBan", "LoggedOut", "ConnectFailure", "Disconnected":+ globalEventType = "CONNECTION"+ case "LabelEdit", "LabelAssociationChat", "LabelAssociationMessage":+ globalEventType = "LABEL"+ case "Contact", "PushName":+ globalEventType = "CONTACT"+ case "GroupInfo", "JoinedGroup":+ globalEventType = "GROUP"+ case "NewsletterJoin", "NewsletterLeave":+ globalEventType = "NEWSLETTER"+ case "QRCode", "QRTimeout", "QRSuccess":+ globalEventType = "QRCODE"+ default:+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Event %s not mapped to global event type", userId, eventType)+ return+ }++ // Verifica se o grupo de eventos está na lista+ if utils.Find(w.config.AmqpGlobalEvents, globalEventType) {+ shouldSendToAmqp = true+ amqpQueueName = strings.ToLower(eventType)+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Event group %s found in AMQP_GLOBAL_EVENTS", userId, globalEventType)+ }+ }++ // Envia para RabbitMQ se necessário+ if shouldSendToAmqp {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Sending to AMQP queue: %s", userId, amqpQueueName)+ err := w.rabbitmqProducer.Produce(amqpQueueName, payload, "global", userId)+ if err != nil {+ w.loggerWrapper.GetLogger(userId).LogError("[%s] Failed to send message to RabbitMQ global queue %s: %v", userId, amqpQueueName, err)+ } else {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Successfully sent message to RabbitMQ global queue %s", userId, amqpQueueName)+ }+ } else {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Event %s not configured for AMQP", userId, eventType)+ }+ }++ // NATS: Mantém o comportamento original por enquanto (só NATS_GLOBAL_EVENTS)+ if w.config.NatsGlobalEnabled {+ // Mapeia o evento para grupo (necessário para NATS por enquanto)+ var globalEventType string+ switch eventType {+ case "Message":+ globalEventType = "MESSAGE"+ case "SendMessage":+ globalEventType = "SEND_MESSAGE"+ case "Receipt":+ globalEventType = "READ_RECEIPT"+ case "Presence":+ globalEventType = "PRESENCE"+ case "HistorySync":+ globalEventType = "HISTORY_SYNC"+ case "ChatPresence", "Archive":+ globalEventType = "CHAT_PRESENCE"+ case "CallOffer", "CallAccept", "CallTerminate", "CallOfferNotice", "CallRelayLatency":+ globalEventType = "CALL"+ case "Connected", "PairSuccess", "TemporaryBan", "LoggedOut", "ConnectFailure", "Disconnected":+ globalEventType = "CONNECTION"+ case "LabelEdit", "LabelAssociationChat", "LabelAssociationMessage":+ globalEventType = "LABEL"+ case "Contact", "PushName":+ globalEventType = "CONTACT"+ case "GroupInfo", "JoinedGroup":+ globalEventType = "GROUP"+ case "NewsletterJoin", "NewsletterLeave":+ globalEventType = "NEWSLETTER"+ case "QRCode", "QRTimeout", "QRSuccess":+ globalEventType = "QRCODE"+ default:+ globalEventType = ""+ }++ // Verifica se o evento está na lista de eventos globais NATS+ if globalEventType != "" && utils.Find(w.config.NatsGlobalEvents, globalEventType) {+ queueName := strings.ToLower(eventType)+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Sending to NATS subject: %s", userId, queueName)++ err := w.natsProducer.Produce(queueName, payload, "global", userId)+ if err != nil {+ w.loggerWrapper.GetLogger(userId).LogError("[%s] Failed to send message to NATS global subject %s: %v", userId, queueName, err)+ } else {+ w.loggerWrapper.GetLogger(userId).LogInfo("[%s] Successfully sent message to NATS global subject %s", userId, queueName)+ }+ }+ }+}++func fetchWhatsAppWebVersion() (*clientVersion, error) {+ resp, err := http.Get("https://web.whatsapp.com/sw.js")+ if err != nil {+ return nil, fmt.Errorf("failed to fetch WhatsApp Web version: %v", err)+ }+ defer resp.Body.Close()++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, fmt.Errorf("failed to read response body: %v", err)+ }++ content := string(body)++ // Múltiplas estratégias para encontrar client_revision+ patterns := []string{+ `"client_revision":\s*(\d+)`, // Formato direto+ `\\"client_revision\\":\s*(\d+)`, // Formato escaped+ `client_revision\\?\\"?:[\s]*(\d+)`, // Formato mais flexível+ `["']client_revision["'][\s]*:[\s]*(\d+)`, // Com aspas variadas+ }++ for _, pattern := range patterns {+ re := regexp.MustCompile(pattern)+ matches := re.FindStringSubmatch(content)++ if len(matches) >= 2 {+ clientRevision, err := strconv.Atoi(matches[1])+ if err != nil {+ continue // Tenta próximo padrão+ }++ // Log qual padrão funcionou+ if clientRevision > 0 {+ return &clientVersion{+ Major: 2,+ Minor: 3000,+ Patch: clientRevision,+ }, nil+ }+ }+ }++ // Se chegou aqui, nenhum padrão funcionou - log do conteúdo para debug+ // Mostra apenas uma parte para não logar muito+ previewLength := 500+ if len(content) > previewLength {+ content = content[:previewLength] + "..."+ }++ return nil, fmt.Errorf("could not find client revision in the fetched content. Content preview: %s", content)+}++func (w whatsmeowService) UpdateInstanceSettings(instanceId string) error {+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updating instance settings in runtime", instanceId)++ // Busca a instância atualizada do banco+ instance, err := w.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting instance from DB: %v", instanceId, err)+ return err+ }++ // Verifica se o MyClient existe+ myClient, exists := w.myClientPointer[instanceId]+ if !exists {+ w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)+ return fmt.Errorf("instance %s not found in runtime", instanceId)+ }++ // Atualiza as configurações no MyClient em execução+ myClient.Instance = instance+ myClient.webhookUrl = instance.Webhook+ myClient.rabbitmqEnable = instance.RabbitmqEnable+ myClient.natsEnable = instance.NatsEnable+ myClient.websocketEnable = instance.WebSocketEnable++ // Atualiza as subscriptions se os eventos mudaram+ eventArray := strings.Split(instance.Events, ",")+ var subscribedEvents []string++ if len(eventArray) < 1 {+ subscribedEvents = append(subscribedEvents, event_types.MESSAGE)+ } else {+ for _, arg := range eventArray {+ if !event_types.IsEventType(arg) {+ w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] Message type discarded: %s", instanceId, arg)+ continue+ }+ if !utils.Find(subscribedEvents, arg) {+ subscribedEvents = append(subscribedEvents, arg)+ }+ }+ }++ myClient.subscriptions = subscribedEvents++ // Atualiza o cache do userInfo com as novas configurações+ v := Values{map[string]string{+ "Id": instance.Id,+ "Jid": instance.Jid,+ "Token": instance.Token,+ "Events": instance.Events,+ "osName": instance.OsName,+ "Proxy": instance.Proxy,+ }}+ w.userInfoCache.Set(instance.Token, v, cache.NoExpiration)++ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance settings and cache updated in runtime successfully", instanceId)+ return nil+}++func (w whatsmeowService) UpdateInstanceAdvancedSettings(instanceId string) error {+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Updating advanced settings in runtime", instanceId)++ // Busca a instância atualizada do banco+ instance, err := w.instanceRepository.GetInstanceByID(instanceId)+ if err != nil {+ w.loggerWrapper.GetLogger(instanceId).LogError("[%s] Error getting instance from DB: %v", instanceId, err)+ return err+ }++ // Verifica se o MyClient existe+ myClient, exists := w.myClientPointer[instanceId]+ if !exists {+ w.loggerWrapper.GetLogger(instanceId).LogWarn("[%s] MyClient not found in runtime, instance may not be connected", instanceId)+ return fmt.Errorf("instance %s not found in runtime", instanceId)+ }++ // Atualiza a instância no MyClient com as advanced settings atualizadas+ myClient.Instance = instance++ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Advanced settings updated in runtime successfully", instanceId)+ return nil+}++func (w whatsmeowService) ClearInstanceCache(instanceId string, token string) error {+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Clearing instance cache - Token: %s", instanceId, token)++ // Limpar userInfoCache+ w.userInfoCache.Delete(token)++ // Limpar myClientPointer se existir+ if _, exists := w.myClientPointer[instanceId]; exists {+ delete(w.myClientPointer, instanceId)+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] MyClient pointer cleared", instanceId)+ }++ // Limpar clientPointer se existir+ if _, exists := w.clientPointer[instanceId]; exists {+ delete(w.clientPointer, instanceId)+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Client pointer cleared", instanceId)+ }++ // Limpar killChannel se existir+ if killChan, exists := w.killChannel[instanceId]; exists {+ select {+ case killChan <- true:+ // Canal recebeu o sinal+ default:+ // Canal pode estar bloqueado, apenas fecha+ }+ close(killChan)+ delete(w.killChannel, instanceId)+ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Kill channel cleared", instanceId)+ }++ w.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Instance cache completely cleared", instanceId)+ return nil+}++func NewWhatsmeowService(+ instanceRepository instance_repository.InstanceRepository,+ authDB *sql.DB,+ messageRepository message_repository.MessageRepository,+ labelRepository label_repository.LabelRepository,+ config *config.Config,+ killChannel map[string](chan bool),+ clientPointer map[string]*whatsmeow.Client,+ rabbitmqProducer producer_interfaces.Producer,+ webhookProducer producer_interfaces.Producer,+ websocketProducer producer_interfaces.Producer,+ sqliteDB *sql.DB,+ exPath string,+ mediaStorage storage_interfaces.MediaStorage,+ natsProducer producer_interfaces.Producer,+ loggerWrapper *logger_wrapper.LoggerManager,+) WhatsmeowService {+ // Inicializar PollService de forma segura+ pollSvc := poll_service.NewPollService(authDB, loggerWrapper)++ return &whatsmeowService{+ instanceRepository: instanceRepository,+ authDB: authDB,+ messageRepository: messageRepository,+ labelRepository: labelRepository,+ pollService: pollSvc, // NOVO: Serviço de enquetes+ config: config,+ killChannel: killChannel,+ userInfoCache: cache.New(5*time.Minute, 10*time.Minute),+ clientPointer: clientPointer,+ myClientPointer: make(map[string]*MyClient),+ rabbitmqProducer: rabbitmqProducer,+ webhookProducer: webhookProducer,+ websocketProducer: websocketProducer,+ sqliteDB: sqliteDB,+ exPath: exPath,+ mediaStorage: mediaStorage,+ processedMessages: cache.New(30*time.Minute, 1*time.Hour),+ natsProducer: natsProducer,+ loggerWrapper: loggerWrapper,+ }+}++// GetPollService retorna o serviço de polls (evita dupla inicialização)+func (w *whatsmeowService) GetPollService() poll_service.PollService {+ return w.pollService+}++// cleanSenderID remove a parte ":numero" do sender ID para exibir apenas o remoteJid correto+// Exemplo: "557499879409:[email protected]" -> "[email protected]"+func cleanSenderID(senderID string) string {+ // Procura pelo padrão ":numero" antes do @+ if colonIndex := strings.Index(senderID, ":"); colonIndex != -1 {+ if atIndex := strings.Index(senderID, "@"); atIndex != -1 && colonIndex < atIndex {+ // Remove a parte ":numero" mantendo apenas o número principal e o domínio+ return senderID[:colonIndex] + senderID[atIndex:]+ }+ }+ return senderID+}diff --git a/public/images/atendai-logo.png b/public/images/atendai-logo.pngnew file mode 100644index 0000000..92e4cccBinary files /dev/null and b/public/images/atendai-logo.png differdiff --git a/public/images/bmc_qr.png b/public/images/bmc_qr.pngnew file mode 100644index 0000000..1024d76Binary files /dev/null and b/public/images/bmc_qr.png differdiff --git a/public/images/code.png b/public/images/code.pngnew file mode 100644index 0000000..50b2898Binary files /dev/null and b/public/images/code.png differdiff --git a/public/images/cover.png b/public/images/cover.pngnew file mode 100644index 0000000..57a1994Binary files /dev/null and b/public/images/cover.png differdiff --git a/public/images/evolution-logo.png b/public/images/evolution-logo.pngnew file mode 100644index 0000000..bd9b385Binary files /dev/null and b/public/images/evolution-logo.png differdiff --git a/public/images/evolution-pro.png b/public/images/evolution-pro.pngnew file mode 100644index 0000000..8813f6eBinary files /dev/null and b/public/images/evolution-pro.png differdiff --git a/public/images/picpay-image.png b/public/images/picpay-image.pngnew file mode 100644index 0000000..eaf89f6Binary files /dev/null and b/public/images/picpay-image.png differdiff --git a/public/images/picpay-qr.jpeg b/public/images/picpay-qr.jpegnew file mode 100644index 0000000..de91165Binary files /dev/null and b/public/images/picpay-qr.jpeg differdiff --git a/public/images/qrcode-pix.png b/public/images/qrcode-pix.pngnew file mode 100644index 0000000..36ef00cBinary files /dev/null and b/public/images/qrcode-pix.png differdiff --git a/public/images/video-cover.png b/public/images/video-cover.pngnew file mode 100644index 0000000..4632f39Binary files /dev/null and b/public/images/video-cover.png differ